1package eu.siacs.conversations.services;
2
3import android.annotation.SuppressLint;
4import android.app.AlarmManager;
5import android.app.PendingIntent;
6import android.app.Service;
7import android.content.Context;
8import android.content.Intent;
9import android.content.IntentFilter;
10import android.content.SharedPreferences;
11import android.database.ContentObserver;
12import android.graphics.Bitmap;
13import android.media.AudioManager;
14import android.net.ConnectivityManager;
15import android.net.NetworkInfo;
16import android.net.Uri;
17import android.os.Binder;
18import android.os.Build;
19import android.os.Bundle;
20import android.os.FileObserver;
21import android.os.IBinder;
22import android.os.Looper;
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.security.KeyChainException;
30import android.util.Log;
31import android.util.LruCache;
32import android.util.DisplayMetrics;
33
34import net.java.otr4j.OtrException;
35import net.java.otr4j.session.Session;
36import net.java.otr4j.session.SessionID;
37import net.java.otr4j.session.SessionImpl;
38import net.java.otr4j.session.SessionStatus;
39
40import org.bouncycastle.asn1.x500.RDN;
41import org.bouncycastle.asn1.x500.X500Name;
42import org.bouncycastle.asn1.x500.style.BCStyle;
43import org.bouncycastle.asn1.x500.style.IETFUtils;
44import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
45import org.bouncycastle.jce.PrincipalUtil;
46import org.bouncycastle.jce.X509Principal;
47import org.openintents.openpgp.util.OpenPgpApi;
48import org.openintents.openpgp.util.OpenPgpServiceConnection;
49
50import java.math.BigInteger;
51import java.security.PrivateKey;
52import java.security.SecureRandom;
53import java.security.cert.CertificateEncodingException;
54import java.security.cert.CertificateParsingException;
55import java.security.cert.X509Certificate;
56import java.util.ArrayList;
57import java.util.Arrays;
58import java.util.Collection;
59import java.util.Collections;
60import java.util.Comparator;
61import java.util.Hashtable;
62import java.util.Iterator;
63import java.util.List;
64import java.util.Locale;
65import java.util.Map;
66import java.util.concurrent.CopyOnWriteArrayList;
67
68import de.duenndns.ssl.MemorizingTrustManager;
69import eu.siacs.conversations.Config;
70import eu.siacs.conversations.R;
71import eu.siacs.conversations.crypto.PgpEngine;
72import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
73import eu.siacs.conversations.entities.Account;
74import eu.siacs.conversations.entities.Blockable;
75import eu.siacs.conversations.entities.Bookmark;
76import eu.siacs.conversations.entities.Contact;
77import eu.siacs.conversations.entities.Conversation;
78import eu.siacs.conversations.entities.Message;
79import eu.siacs.conversations.entities.MucOptions;
80import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
81import eu.siacs.conversations.entities.Presences;
82import eu.siacs.conversations.entities.Transferable;
83import eu.siacs.conversations.entities.TransferablePlaceholder;
84import eu.siacs.conversations.generator.IqGenerator;
85import eu.siacs.conversations.generator.MessageGenerator;
86import eu.siacs.conversations.generator.PresenceGenerator;
87import eu.siacs.conversations.http.HttpConnectionManager;
88import eu.siacs.conversations.parser.IqParser;
89import eu.siacs.conversations.parser.MessageParser;
90import eu.siacs.conversations.parser.PresenceParser;
91import eu.siacs.conversations.persistance.DatabaseBackend;
92import eu.siacs.conversations.persistance.FileBackend;
93import eu.siacs.conversations.ui.UiCallback;
94import eu.siacs.conversations.utils.CryptoHelper;
95import eu.siacs.conversations.utils.ExceptionHelper;
96import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
97import eu.siacs.conversations.utils.PRNGFixes;
98import eu.siacs.conversations.utils.PhoneHelper;
99import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
100import eu.siacs.conversations.utils.Xmlns;
101import eu.siacs.conversations.xml.Element;
102import eu.siacs.conversations.xmpp.OnBindListener;
103import eu.siacs.conversations.xmpp.OnContactStatusChanged;
104import eu.siacs.conversations.xmpp.OnIqPacketReceived;
105import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
106import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
107import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
108import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
109import eu.siacs.conversations.xmpp.OnStatusChanged;
110import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
111import eu.siacs.conversations.xmpp.XmppConnection;
112import eu.siacs.conversations.xmpp.chatstate.ChatState;
113import eu.siacs.conversations.xmpp.forms.Data;
114import eu.siacs.conversations.xmpp.forms.Field;
115import eu.siacs.conversations.xmpp.jid.InvalidJidException;
116import eu.siacs.conversations.xmpp.jid.Jid;
117import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
118import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
119import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
120import eu.siacs.conversations.xmpp.pep.Avatar;
121import eu.siacs.conversations.xmpp.stanzas.IqPacket;
122import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
123import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
124import me.leolin.shortcutbadger.ShortcutBadger;
125
126public class XmppConnectionService extends Service implements OnPhoneContactsLoadedListener {
127
128 public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
129 public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground";
130 private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
131 public static final String ACTION_TRY_AGAIN = "try_again";
132 public static final String ACTION_DISABLE_ACCOUNT = "disable_account";
133 private ContentObserver contactObserver = new ContentObserver(null) {
134 @Override
135 public void onChange(boolean selfChange) {
136 super.onChange(selfChange);
137 Intent intent = new Intent(getApplicationContext(),
138 XmppConnectionService.class);
139 intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
140 startService(intent);
141 }
142 };
143
144 private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
145 private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
146
147 private final IBinder mBinder = new XmppConnectionBinder();
148 private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
149 private final FileObserver fileObserver = new FileObserver(
150 FileBackend.getConversationsImageDirectory()) {
151
152 @Override
153 public void onEvent(int event, String path) {
154 if (event == FileObserver.DELETE) {
155 markFileDeleted(path.split("\\.")[0]);
156 }
157 }
158 };
159 private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
160
161 @Override
162 public void onJinglePacketReceived(Account account, JinglePacket packet) {
163 mJingleConnectionManager.deliverPacket(account, packet);
164 }
165 };
166 private final OnBindListener mOnBindListener = new OnBindListener() {
167
168 @Override
169 public void onBind(final Account account) {
170 account.getRoster().clearPresences();
171 fetchRosterFromServer(account);
172 fetchBookmarks(account);
173 sendPresence(account);
174 connectMultiModeConversations(account);
175 mMessageArchiveService.executePendingQueries(account);
176 mJingleConnectionManager.cancelInTransmission();
177 syncDirtyContacts(account);
178 account.getAxolotlService().publishBundlesIfNeeded(true);
179 }
180 };
181 private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
182
183 @Override
184 public void onMessageAcknowledged(Account account, String uuid) {
185 for (final Conversation conversation : getConversations()) {
186 if (conversation.getAccount() == account) {
187 Message message = conversation.findUnsentMessageWithUuid(uuid);
188 if (message != null) {
189 markMessage(message, Message.STATUS_SEND);
190 if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
191 databaseBackend.updateConversation(conversation);
192 }
193 }
194 }
195 }
196 }
197 };
198 private final IqGenerator mIqGenerator = new IqGenerator(this);
199 public DatabaseBackend databaseBackend;
200 public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
201
202 @Override
203 public void onContactStatusChanged(Contact contact, boolean online) {
204 Conversation conversation = find(getConversations(), contact);
205 if (conversation != null) {
206 if (online) {
207 conversation.endOtrIfNeeded();
208 if (contact.getPresences().size() == 1) {
209 sendUnsentMessages(conversation);
210 }
211 } else {
212 if (contact.getPresences().size() >= 1) {
213 if (conversation.hasValidOtrSession()) {
214 String otrResource = conversation.getOtrSession().getSessionID().getUserID();
215 if (!(Arrays.asList(contact.getPresences().asStringArray()).contains(otrResource))) {
216 conversation.endOtrIfNeeded();
217 }
218 }
219 } else {
220 conversation.endOtrIfNeeded();
221 }
222 }
223 }
224 }
225 };
226 private FileBackend fileBackend = new FileBackend(this);
227 private MemorizingTrustManager mMemorizingTrustManager;
228 private NotificationService mNotificationService = new NotificationService(
229 this);
230 private OnMessagePacketReceived mMessageParser = new MessageParser(this);
231 private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
232 private IqParser mIqParser = new IqParser(this);
233 private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() {
234 @Override
235 public void onIqPacketReceived(Account account, IqPacket packet) {
236 if (packet.getType() != IqPacket.TYPE.RESULT) {
237 Element error = packet.findChild("error");
238 String text = error != null ? error.findChildContent("text") : null;
239 if (text != null) {
240 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received iq error - "+text);
241 }
242 }
243 }
244 };
245 private MessageGenerator mMessageGenerator = new MessageGenerator(this);
246 private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
247 private List<Account> accounts;
248 private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
249 this);
250 private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
251 this);
252 private AvatarService mAvatarService = new AvatarService(this);
253 private final List<String> mInProgressAvatarFetches = new ArrayList<>();
254 private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
255 private OnConversationUpdate mOnConversationUpdate = null;
256 private int convChangedListenerCount = 0;
257 private OnShowErrorToast mOnShowErrorToast = null;
258 private int showErrorToastListenerCount = 0;
259 private int unreadCount = -1;
260 private OnAccountUpdate mOnAccountUpdate = null;
261 private OnCaptchaRequested mOnCaptchaRequested = null;
262 private OnStatusChanged statusListener = new OnStatusChanged() {
263
264 @Override
265 public void onStatusChanged(Account account) {
266 XmppConnection connection = account.getXmppConnection();
267 if (mOnAccountUpdate != null) {
268 mOnAccountUpdate.onAccountUpdate();
269 }
270 if (account.getStatus() == Account.State.ONLINE) {
271 if (connection != null && connection.getFeatures().csi()) {
272 if (checkListeners()) {
273 Log.d(Config.LOGTAG, account.getJid().toBareJid()+ " sending csi//inactive");
274 connection.sendInactive();
275 } else {
276 Log.d(Config.LOGTAG, account.getJid().toBareJid()+ " sending csi//active");
277 connection.sendActive();
278 }
279 }
280 List<Conversation> conversations = getConversations();
281 for (Conversation conversation : conversations) {
282 if (conversation.getAccount() == account) {
283 conversation.startOtrIfNeeded();
284 sendUnsentMessages(conversation);
285 }
286 }
287 for (Conversation conversation : account.pendingConferenceLeaves) {
288 leaveMuc(conversation);
289 }
290 account.pendingConferenceLeaves.clear();
291 for (Conversation conversation : account.pendingConferenceJoins) {
292 joinMuc(conversation);
293 }
294 account.pendingConferenceJoins.clear();
295 scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
296 } else if (account.getStatus() == Account.State.OFFLINE) {
297 resetSendingToWaiting(account);
298 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
299 int timeToReconnect = mRandom.nextInt(20) + 10;
300 scheduleWakeUpCall(timeToReconnect,account.getUuid().hashCode());
301 }
302 } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
303 databaseBackend.updateAccount(account);
304 reconnectAccount(account, true, false);
305 } else if ((account.getStatus() != Account.State.CONNECTING)
306 && (account.getStatus() != Account.State.NO_INTERNET)) {
307 if (connection != null) {
308 int next = connection.getTimeToNextAttempt();
309 Log.d(Config.LOGTAG, account.getJid().toBareJid()
310 + ": error connecting account. try again in "
311 + next + "s for the "
312 + (connection.getAttempt() + 1) + " time");
313 scheduleWakeUpCall(next,account.getUuid().hashCode());
314 }
315 }
316 getNotificationService().updateErrorNotification();
317 }
318 };
319 private int accountChangedListenerCount = 0;
320 private int captchaRequestedListenerCount = 0;
321 private OnRosterUpdate mOnRosterUpdate = null;
322 private OnUpdateBlocklist mOnUpdateBlocklist = null;
323 private int updateBlocklistListenerCount = 0;
324 private int rosterChangedListenerCount = 0;
325 private OnMucRosterUpdate mOnMucRosterUpdate = null;
326 private int mucRosterChangedListenerCount = 0;
327 private OnKeyStatusUpdated mOnKeyStatusUpdated = null;
328 private int keyStatusUpdatedListenerCount = 0;
329 private SecureRandom mRandom;
330 private OpenPgpServiceConnection pgpServiceConnection;
331 private PgpEngine mPgpEngine = null;
332 private WakeLock wakeLock;
333 private PowerManager pm;
334 private LruCache<String, Bitmap> mBitmapCache;
335 private Thread mPhoneContactMergerThread;
336 private EventReceiver mEventReceiver = new EventReceiver();
337
338 private boolean mRestoredFromDatabase = false;
339 public boolean areMessagesInitialized() {
340 return this.mRestoredFromDatabase;
341 }
342
343 public PgpEngine getPgpEngine() {
344 if (pgpServiceConnection.isBound()) {
345 if (this.mPgpEngine == null) {
346 this.mPgpEngine = new PgpEngine(new OpenPgpApi(
347 getApplicationContext(),
348 pgpServiceConnection.getService()), this);
349 }
350 return mPgpEngine;
351 } else {
352 return null;
353 }
354
355 }
356
357 public FileBackend getFileBackend() {
358 return this.fileBackend;
359 }
360
361 public AvatarService getAvatarService() {
362 return this.mAvatarService;
363 }
364
365 public void attachLocationToConversation(final Conversation conversation,
366 final Uri uri,
367 final UiCallback<Message> callback) {
368 int encryption = conversation.getNextEncryption();
369 if (encryption == Message.ENCRYPTION_PGP) {
370 encryption = Message.ENCRYPTION_DECRYPTED;
371 }
372 Message message = new Message(conversation,uri.toString(),encryption);
373 if (conversation.getNextCounterpart() != null) {
374 message.setCounterpart(conversation.getNextCounterpart());
375 }
376 if (encryption == Message.ENCRYPTION_DECRYPTED) {
377 getPgpEngine().encrypt(message, callback);
378 } else {
379 callback.success(message);
380 }
381 }
382
383 public void attachFileToConversation(final Conversation conversation,
384 final Uri uri,
385 final UiCallback<Message> callback) {
386 final Message message;
387 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
388 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
389 } else {
390 message = new Message(conversation, "", conversation.getNextEncryption());
391 }
392 message.setCounterpart(conversation.getNextCounterpart());
393 message.setType(Message.TYPE_FILE);
394 String path = getFileBackend().getOriginalPath(uri);
395 if (path!=null) {
396 message.setRelativeFilePath(path);
397 getFileBackend().updateFileParams(message);
398 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
399 getPgpEngine().encrypt(message, callback);
400 } else {
401 callback.success(message);
402 }
403 } else {
404 mFileAddingExecutor.execute(new Runnable() {
405 @Override
406 public void run() {
407 try {
408 getFileBackend().copyFileToPrivateStorage(message, uri);
409 getFileBackend().updateFileParams(message);
410 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
411 getPgpEngine().encrypt(message, callback);
412 } else {
413 callback.success(message);
414 }
415 } catch (FileBackend.FileCopyException e) {
416 callback.error(e.getResId(), message);
417 }
418 }
419 });
420 }
421 }
422
423 public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
424 if (getFileBackend().useImageAsIs(uri)) {
425 Log.d(Config.LOGTAG,"using image as is");
426 attachFileToConversation(conversation, uri, callback);
427 return;
428 }
429 final Message message;
430 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
431 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
432 } else {
433 message = new Message(conversation, "",conversation.getNextEncryption());
434 }
435 message.setCounterpart(conversation.getNextCounterpart());
436 message.setType(Message.TYPE_IMAGE);
437 mFileAddingExecutor.execute(new Runnable() {
438
439 @Override
440 public void run() {
441 try {
442 getFileBackend().copyImageToPrivateStorage(message, uri);
443 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
444 getPgpEngine().encrypt(message, callback);
445 } else {
446 callback.success(message);
447 }
448 } catch (final FileBackend.FileCopyException e) {
449 callback.error(e.getResId(), message);
450 }
451 }
452 });
453 }
454
455 public Conversation find(Bookmark bookmark) {
456 return find(bookmark.getAccount(), bookmark.getJid());
457 }
458
459 public Conversation find(final Account account, final Jid jid) {
460 return find(getConversations(), account, jid);
461 }
462
463 @Override
464 public int onStartCommand(Intent intent, int flags, int startId) {
465 final String action = intent == null ? null : intent.getAction();
466 boolean interactive = false;
467 if (action != null) {
468 Log.d(Config.LOGTAG,"action: "+action);
469 switch (action) {
470 case ConnectivityManager.CONNECTIVITY_ACTION:
471 if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
472 resetAllAttemptCounts(true);
473 }
474 break;
475 case ACTION_MERGE_PHONE_CONTACTS:
476 if (mRestoredFromDatabase) {
477 PhoneHelper.loadPhoneContacts(getApplicationContext(),
478 new CopyOnWriteArrayList<Bundle>(),
479 this);
480 }
481 return START_STICKY;
482 case Intent.ACTION_SHUTDOWN:
483 logoutAndSave();
484 return START_NOT_STICKY;
485 case ACTION_CLEAR_NOTIFICATION:
486 mNotificationService.clear();
487 break;
488 case ACTION_DISABLE_FOREGROUND:
489 getPreferences().edit().putBoolean("keep_foreground_service",false).commit();
490 toggleForegroundService();
491 break;
492 case ACTION_TRY_AGAIN:
493 resetAllAttemptCounts(false);
494 interactive = true;
495 break;
496 case ACTION_DISABLE_ACCOUNT:
497 try {
498 String jid = intent.getStringExtra("account");
499 Account account = jid == null ? null : findAccountByJid(Jid.fromString(jid));
500 if (account != null) {
501 account.setOption(Account.OPTION_DISABLED,true);
502 updateAccount(account);
503 }
504 } catch (final InvalidJidException ignored) {
505 break;
506 }
507 break;
508 case AudioManager.RINGER_MODE_CHANGED_ACTION:
509 if (xaOnSilentMode()) {
510 refreshAllPresences();
511 }
512 break;
513 case Intent.ACTION_SCREEN_OFF:
514 case Intent.ACTION_SCREEN_ON:
515 if (awayWhenScreenOff()) {
516 refreshAllPresences();
517 }
518 break;
519 }
520 }
521 this.wakeLock.acquire();
522
523 for (Account account : accounts) {
524 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
525 if (!hasInternetConnection()) {
526 account.setStatus(Account.State.NO_INTERNET);
527 if (statusListener != null) {
528 statusListener.onStatusChanged(account);
529 }
530 } else {
531 if (account.getStatus() == Account.State.NO_INTERNET) {
532 account.setStatus(Account.State.OFFLINE);
533 if (statusListener != null) {
534 statusListener.onStatusChanged(account);
535 }
536 }
537 if (account.getStatus() == Account.State.ONLINE) {
538 long lastReceived = account.getXmppConnection().getLastPacketReceived();
539 long lastSent = account.getXmppConnection().getLastPingSent();
540 long pingInterval = "ui".equals(action) ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
541 long msToNextPing = (Math.max(lastReceived,lastSent) + pingInterval) - SystemClock.elapsedRealtime();
542 long pingTimeoutIn = (lastSent + Config.PING_TIMEOUT * 1000) - SystemClock.elapsedRealtime();
543 if (lastSent > lastReceived) {
544 if (pingTimeoutIn < 0) {
545 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
546 this.reconnectAccount(account, true, interactive);
547 } else {
548 int secs = (int) (pingTimeoutIn / 1000);
549 this.scheduleWakeUpCall(secs,account.getUuid().hashCode());
550 }
551 } else if (msToNextPing <= 0) {
552 account.getXmppConnection().sendPing();
553 Log.d(Config.LOGTAG, account.getJid().toBareJid()+" send ping");
554 this.scheduleWakeUpCall(Config.PING_TIMEOUT,account.getUuid().hashCode());
555 } else {
556 this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
557 }
558 } else if (account.getStatus() == Account.State.OFFLINE) {
559 reconnectAccount(account,true, interactive);
560 } else if (account.getStatus() == Account.State.CONNECTING) {
561 long timeout = Config.CONNECT_TIMEOUT - ((SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000);
562 if (timeout < 0) {
563 Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting");
564 reconnectAccount(account, true, interactive);
565 } else {
566 scheduleWakeUpCall((int) timeout,account.getUuid().hashCode());
567 }
568 } else {
569 if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
570 reconnectAccount(account, true, interactive);
571 }
572 }
573
574 }
575 if (mOnAccountUpdate != null) {
576 mOnAccountUpdate.onAccountUpdate();
577 }
578 }
579 }
580 if (wakeLock.isHeld()) {
581 try {
582 wakeLock.release();
583 } catch (final RuntimeException ignored) {
584 }
585 }
586 return START_STICKY;
587 }
588
589 private boolean xaOnSilentMode() {
590 return getPreferences().getBoolean("xa_on_silent_mode", false);
591 }
592
593 private boolean awayWhenScreenOff() {
594 return getPreferences().getBoolean("away_when_screen_off", false);
595 }
596
597 private int getTargetPresence() {
598 if (xaOnSilentMode() && isPhoneSilenced()) {
599 return Presences.XA;
600 } else if (awayWhenScreenOff() && !isInteractive()) {
601 return Presences.AWAY;
602 } else {
603 return Presences.ONLINE;
604 }
605 }
606
607 @SuppressLint("NewApi")
608 @SuppressWarnings("deprecation")
609 public boolean isInteractive() {
610 final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
611
612 final boolean isScreenOn;
613 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
614 isScreenOn = pm.isScreenOn();
615 } else {
616 isScreenOn = pm.isInteractive();
617 }
618 return isScreenOn;
619 }
620
621 private boolean isPhoneSilenced() {
622 AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
623 return audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
624 }
625
626 private void resetAllAttemptCounts(boolean reallyAll) {
627 Log.d(Config.LOGTAG,"resetting all attepmt counts");
628 for(Account account : accounts) {
629 if (account.hasErrorStatus() || reallyAll) {
630 final XmppConnection connection = account.getXmppConnection();
631 if (connection != null) {
632 connection.resetAttemptCount();
633 }
634 }
635 }
636 }
637
638 public boolean hasInternetConnection() {
639 ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
640 .getSystemService(Context.CONNECTIVITY_SERVICE);
641 NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
642 return activeNetwork != null && activeNetwork.isConnected();
643 }
644
645 @SuppressLint("TrulyRandom")
646 @Override
647 public void onCreate() {
648 ExceptionHelper.init(getApplicationContext());
649 PRNGFixes.apply();
650 this.mRandom = new SecureRandom();
651 updateMemorizingTrustmanager();
652 final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
653 final int cacheSize = maxMemory / 8;
654 this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
655 @Override
656 protected int sizeOf(final String key, final Bitmap bitmap) {
657 return bitmap.getByteCount() / 1024;
658 }
659 };
660
661 this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
662 this.accounts = databaseBackend.getAccounts();
663
664 restoreFromDatabase();
665
666 getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
667 this.fileObserver.startWatching();
668
669 this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain");
670 this.pgpServiceConnection.bindToService();
671
672 this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
673 this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"XmppConnectionService");
674 toggleForegroundService();
675 updateUnreadCountBadge();
676 toggleScreenEventReceiver();
677 }
678
679 @Override
680 public void onDestroy() {
681 try {
682 unregisterReceiver(this.mEventReceiver);
683 } catch (IllegalArgumentException e) {
684 //ignored
685 }
686 super.onDestroy();
687 }
688
689 public void toggleScreenEventReceiver() {
690 if (awayWhenScreenOff()) {
691 final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
692 filter.addAction(Intent.ACTION_SCREEN_OFF);
693 registerReceiver(this.mEventReceiver, filter);
694 } else {
695 try {
696 unregisterReceiver(this.mEventReceiver);
697 } catch (IllegalArgumentException e) {
698 //ignored
699 }
700 }
701 }
702
703 public void toggleForegroundService() {
704 if (getPreferences().getBoolean("keep_foreground_service", false)) {
705 startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
706 } else {
707 stopForeground(true);
708 }
709 }
710
711 @Override
712 public void onTaskRemoved(final Intent rootIntent) {
713 super.onTaskRemoved(rootIntent);
714 if (!getPreferences().getBoolean("keep_foreground_service",false)) {
715 this.logoutAndSave();
716 }
717 }
718
719 private void logoutAndSave() {
720 for (final Account account : accounts) {
721 databaseBackend.writeRoster(account.getRoster());
722 if (account.getXmppConnection() != null) {
723 disconnect(account, false);
724 }
725 }
726 Context context = getApplicationContext();
727 AlarmManager alarmManager = (AlarmManager) context
728 .getSystemService(Context.ALARM_SERVICE);
729 Intent intent = new Intent(context, EventReceiver.class);
730 alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
731 Log.d(Config.LOGTAG, "good bye");
732 stopSelf();
733 }
734
735 protected void scheduleWakeUpCall(int seconds, int requestCode) {
736 final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
737
738 Context context = getApplicationContext();
739 AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
740
741 Intent intent = new Intent(context, EventReceiver.class);
742 intent.setAction("ping");
743 PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
744 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
745 }
746
747 public XmppConnection createConnection(final Account account) {
748 final SharedPreferences sharedPref = getPreferences();
749 account.setResource(sharedPref.getString("resource", "mobile")
750 .toLowerCase(Locale.getDefault()));
751 final XmppConnection connection = new XmppConnection(account, this);
752 connection.setOnMessagePacketReceivedListener(this.mMessageParser);
753 connection.setOnStatusChangedListener(this.statusListener);
754 connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
755 connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
756 connection.setOnJinglePacketReceivedListener(this.jingleListener);
757 connection.setOnBindListener(this.mOnBindListener);
758 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
759 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
760 return connection;
761 }
762
763 public void sendChatState(Conversation conversation) {
764 if (sendChatStates()) {
765 MessagePacket packet = mMessageGenerator.generateChatState(conversation);
766 sendMessagePacket(conversation.getAccount(), packet);
767 }
768 }
769
770 private void sendFileMessage(final Message message, final boolean delay) {
771 Log.d(Config.LOGTAG, "send file message");
772 final Account account = message.getConversation().getAccount();
773 final XmppConnection connection = account.getXmppConnection();
774 if (connection != null && connection.getFeatures().httpUpload()) {
775 mHttpConnectionManager.createNewUploadConnection(message, delay);
776 } else {
777 mJingleConnectionManager.createNewConnection(message);
778 }
779 }
780
781 public void sendMessage(final Message message) {
782 sendMessage(message, false, false);
783 }
784
785 private void sendMessage(final Message message, final boolean resend, final boolean delay) {
786 final Account account = message.getConversation().getAccount();
787 final Conversation conversation = message.getConversation();
788 account.deactivateGracePeriod();
789 MessagePacket packet = null;
790 boolean saveInDb = true;
791 message.setStatus(Message.STATUS_WAITING);
792
793 if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
794 message.getConversation().endOtrIfNeeded();
795 message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
796 new Conversation.OnMessageFound() {
797 @Override
798 public void onMessageFound(Message message) {
799 markMessage(message,Message.STATUS_SEND_FAILED);
800 }
801 });
802 }
803
804 if (account.isOnlineAndConnected()) {
805 switch (message.getEncryption()) {
806 case Message.ENCRYPTION_NONE:
807 if (message.needsUploading()) {
808 if (account.httpUploadAvailable() || message.fixCounterpart()) {
809 this.sendFileMessage(message,delay);
810 } else {
811 break;
812 }
813 } else {
814 packet = mMessageGenerator.generateChat(message);
815 }
816 break;
817 case Message.ENCRYPTION_PGP:
818 case Message.ENCRYPTION_DECRYPTED:
819 if (message.needsUploading()) {
820 if (account.httpUploadAvailable() || message.fixCounterpart()) {
821 this.sendFileMessage(message,delay);
822 } else {
823 break;
824 }
825 } else {
826 packet = mMessageGenerator.generatePgpChat(message);
827 }
828 break;
829 case Message.ENCRYPTION_OTR:
830 SessionImpl otrSession = conversation.getOtrSession();
831 if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
832 try {
833 message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
834 } catch (InvalidJidException e) {
835 break;
836 }
837 if (message.needsUploading()) {
838 mJingleConnectionManager.createNewConnection(message);
839 } else {
840 packet = mMessageGenerator.generateOtrChat(message);
841 }
842 } else if (otrSession == null) {
843 if (message.fixCounterpart()) {
844 conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
845 } else {
846 break;
847 }
848 }
849 break;
850 case Message.ENCRYPTION_AXOLOTL:
851 message.setAxolotlFingerprint(account.getAxolotlService().getOwnFingerprint());
852 if (message.needsUploading()) {
853 if (account.httpUploadAvailable() || message.fixCounterpart()) {
854 this.sendFileMessage(message,delay);
855 } else {
856 break;
857 }
858 } else {
859 XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
860 if (axolotlMessage == null) {
861 account.getAxolotlService().preparePayloadMessage(message, delay);
862 } else {
863 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
864 }
865 }
866 break;
867
868 }
869 if (packet != null) {
870 if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
871 message.setStatus(Message.STATUS_UNSEND);
872 } else {
873 message.setStatus(Message.STATUS_SEND);
874 }
875 }
876 } else {
877 switch(message.getEncryption()) {
878 case Message.ENCRYPTION_DECRYPTED:
879 if (!message.needsUploading()) {
880 String pgpBody = message.getEncryptedBody();
881 String decryptedBody = message.getBody();
882 message.setBody(pgpBody);
883 message.setEncryption(Message.ENCRYPTION_PGP);
884 databaseBackend.createMessage(message);
885 saveInDb = false;
886 message.setBody(decryptedBody);
887 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
888 }
889 break;
890 case Message.ENCRYPTION_OTR:
891 if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
892 conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
893 }
894 break;
895 case Message.ENCRYPTION_AXOLOTL:
896 message.setAxolotlFingerprint(account.getAxolotlService().getOwnFingerprint());
897 break;
898 }
899 }
900
901 if (resend) {
902 if (packet != null) {
903 if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
904 markMessage(message,Message.STATUS_UNSEND);
905 } else {
906 markMessage(message,Message.STATUS_SEND);
907 }
908 }
909 } else {
910 conversation.add(message);
911 if (saveInDb && (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages())) {
912 databaseBackend.createMessage(message);
913 }
914 updateConversationUi();
915 }
916 if (packet != null) {
917 if (delay) {
918 mMessageGenerator.addDelay(packet,message.getTimeSent());
919 }
920 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
921 if (this.sendChatStates()) {
922 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
923 }
924 }
925 sendMessagePacket(account, packet);
926 }
927 }
928
929 private void sendUnsentMessages(final Conversation conversation) {
930 conversation.findWaitingMessages(new Conversation.OnMessageFound() {
931
932 @Override
933 public void onMessageFound(Message message) {
934 resendMessage(message, true);
935 }
936 });
937 }
938
939 public void resendMessage(final Message message, final boolean delay) {
940 sendMessage(message, true, delay);
941 }
942
943 public void fetchRosterFromServer(final Account account) {
944 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
945 if (!"".equals(account.getRosterVersion())) {
946 Log.d(Config.LOGTAG, account.getJid().toBareJid()
947 + ": fetching roster version " + account.getRosterVersion());
948 } else {
949 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
950 }
951 iqPacket.query(Xmlns.ROSTER).setAttribute("ver", account.getRosterVersion());
952 sendIqPacket(account, iqPacket, mIqParser);
953 }
954
955 public void fetchBookmarks(final Account account) {
956 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
957 final Element query = iqPacket.query("jabber:iq:private");
958 query.addChild("storage", "storage:bookmarks");
959 final OnIqPacketReceived callback = new OnIqPacketReceived() {
960
961 @Override
962 public void onIqPacketReceived(final Account account, final IqPacket packet) {
963 if (packet.getType() == IqPacket.TYPE.RESULT) {
964 final Element query = packet.query();
965 final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
966 final Element storage = query.findChild("storage", "storage:bookmarks");
967 if (storage != null) {
968 for (final Element item : storage.getChildren()) {
969 if (item.getName().equals("conference")) {
970 final Bookmark bookmark = Bookmark.parse(item, account);
971 bookmarks.add(bookmark);
972 Conversation conversation = find(bookmark);
973 if (conversation != null) {
974 conversation.setBookmark(bookmark);
975 } else if (bookmark.autojoin() && bookmark.getJid() != null) {
976 conversation = findOrCreateConversation(
977 account, bookmark.getJid(), true);
978 conversation.setBookmark(bookmark);
979 joinMuc(conversation);
980 }
981 }
982 }
983 }
984 account.setBookmarks(bookmarks);
985 } else {
986 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not fetch bookmarks");
987 }
988 }
989 };
990 sendIqPacket(account, iqPacket, callback);
991 }
992
993 public void pushBookmarks(Account account) {
994 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
995 Element query = iqPacket.query("jabber:iq:private");
996 Element storage = query.addChild("storage", "storage:bookmarks");
997 for (Bookmark bookmark : account.getBookmarks()) {
998 storage.addChild(bookmark);
999 }
1000 sendIqPacket(account, iqPacket, mDefaultIqHandler);
1001 }
1002
1003 public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
1004 if (mPhoneContactMergerThread != null) {
1005 mPhoneContactMergerThread.interrupt();
1006 }
1007 mPhoneContactMergerThread = new Thread(new Runnable() {
1008 @Override
1009 public void run() {
1010 Log.d(Config.LOGTAG,"start merging phone contacts with roster");
1011 for (Account account : accounts) {
1012 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1013 for (Bundle phoneContact : phoneContacts) {
1014 if (Thread.interrupted()) {
1015 Log.d(Config.LOGTAG,"interrupted merging phone contacts");
1016 return;
1017 }
1018 Jid jid;
1019 try {
1020 jid = Jid.fromString(phoneContact.getString("jid"));
1021 } catch (final InvalidJidException e) {
1022 continue;
1023 }
1024 final Contact contact = account.getRoster().getContact(jid);
1025 String systemAccount = phoneContact.getInt("phoneid")
1026 + "#"
1027 + phoneContact.getString("lookup");
1028 contact.setSystemAccount(systemAccount);
1029 if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
1030 getAvatarService().clear(contact);
1031 }
1032 contact.setSystemName(phoneContact.getString("displayname"));
1033 withSystemAccounts.remove(contact);
1034 }
1035 for(Contact contact : withSystemAccounts) {
1036 contact.setSystemAccount(null);
1037 contact.setSystemName(null);
1038 if (contact.setPhotoUri(null)) {
1039 getAvatarService().clear(contact);
1040 }
1041 }
1042 }
1043 Log.d(Config.LOGTAG,"finished merging phone contacts");
1044 updateAccountUi();
1045 }
1046 });
1047 mPhoneContactMergerThread.start();
1048 }
1049
1050 private void restoreFromDatabase() {
1051 synchronized (this.conversations) {
1052 final Map<String, Account> accountLookupTable = new Hashtable<>();
1053 for (Account account : this.accounts) {
1054 accountLookupTable.put(account.getUuid(), account);
1055 }
1056 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1057 for (Conversation conversation : this.conversations) {
1058 Account account = accountLookupTable.get(conversation.getAccountUuid());
1059 conversation.setAccount(account);
1060 }
1061 Runnable runnable =new Runnable() {
1062 @Override
1063 public void run() {
1064 Log.d(Config.LOGTAG,"restoring roster");
1065 for(Account account : accounts) {
1066 databaseBackend.readRoster(account.getRoster());
1067 account.initAccountServices(XmppConnectionService.this);
1068 }
1069 getBitmapCache().evictAll();
1070 Looper.prepare();
1071 PhoneHelper.loadPhoneContacts(getApplicationContext(),
1072 new CopyOnWriteArrayList<Bundle>(),
1073 XmppConnectionService.this);
1074 Log.d(Config.LOGTAG,"restoring messages");
1075 for (Conversation conversation : conversations) {
1076 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1077 checkDeletedFiles(conversation);
1078 }
1079 mRestoredFromDatabase = true;
1080 Log.d(Config.LOGTAG,"restored all messages");
1081 updateConversationUi();
1082 }
1083 };
1084 mDatabaseExecutor.execute(runnable);
1085 }
1086 }
1087
1088 public List<Conversation> getConversations() {
1089 return this.conversations;
1090 }
1091
1092 private void checkDeletedFiles(Conversation conversation) {
1093 conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1094
1095 @Override
1096 public void onMessageFound(Message message) {
1097 if (!getFileBackend().isFileAvailable(message)) {
1098 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1099 final int s = message.getStatus();
1100 if(s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1101 markMessage(message,Message.STATUS_SEND_FAILED);
1102 }
1103 }
1104 }
1105 });
1106 }
1107
1108 private void markFileDeleted(String uuid) {
1109 for (Conversation conversation : getConversations()) {
1110 Message message = conversation.findMessageWithFileAndUuid(uuid);
1111 if (message != null) {
1112 if (!getFileBackend().isFileAvailable(message)) {
1113 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1114 final int s = message.getStatus();
1115 if(s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1116 markMessage(message,Message.STATUS_SEND_FAILED);
1117 } else {
1118 updateConversationUi();
1119 }
1120 }
1121 return;
1122 }
1123 }
1124 }
1125
1126 public void populateWithOrderedConversations(final List<Conversation> list) {
1127 populateWithOrderedConversations(list, true);
1128 }
1129
1130 public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1131 list.clear();
1132 if (includeNoFileUpload) {
1133 list.addAll(getConversations());
1134 } else {
1135 for (Conversation conversation : getConversations()) {
1136 if (conversation.getMode() == Conversation.MODE_SINGLE
1137 || conversation.getAccount().httpUploadAvailable()) {
1138 list.add(conversation);
1139 }
1140 }
1141 }
1142 Collections.sort(list, new Comparator<Conversation>() {
1143 @Override
1144 public int compare(Conversation lhs, Conversation rhs) {
1145 Message left = lhs.getLatestMessage();
1146 Message right = rhs.getLatestMessage();
1147 if (left.getTimeSent() > right.getTimeSent()) {
1148 return -1;
1149 } else if (left.getTimeSent() < right.getTimeSent()) {
1150 return 1;
1151 } else {
1152 return 0;
1153 }
1154 }
1155 });
1156 }
1157
1158 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1159 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
1160 return;
1161 }
1162 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1163 Runnable runnable = new Runnable() {
1164 @Override
1165 public void run() {
1166 final Account account = conversation.getAccount();
1167 List<Message> messages = databaseBackend.getMessages(conversation, 50,timestamp);
1168 if (messages.size() > 0) {
1169 conversation.addAll(0, messages);
1170 checkDeletedFiles(conversation);
1171 callback.onMoreMessagesLoaded(messages.size(), conversation);
1172 } else if (conversation.hasMessagesLeftOnServer()
1173 && account.isOnlineAndConnected()) {
1174 if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1175 || (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1176 MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1);
1177 if (query != null) {
1178 query.setCallback(callback);
1179 }
1180 callback.informUser(R.string.fetching_history_from_server);
1181 }
1182 }
1183 }
1184 };
1185 mDatabaseExecutor.execute(runnable);
1186 }
1187
1188 public List<Account> getAccounts() {
1189 return this.accounts;
1190 }
1191
1192 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1193 for (final Conversation conversation : haystack) {
1194 if (conversation.getContact() == contact) {
1195 return conversation;
1196 }
1197 }
1198 return null;
1199 }
1200
1201 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1202 if (jid == null) {
1203 return null;
1204 }
1205 for (final Conversation conversation : haystack) {
1206 if ((account == null || conversation.getAccount() == account)
1207 && (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1208 return conversation;
1209 }
1210 }
1211 return null;
1212 }
1213
1214 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1215 return this.findOrCreateConversation(account, jid, muc, null);
1216 }
1217
1218 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1219 synchronized (this.conversations) {
1220 Conversation conversation = find(account, jid);
1221 if (conversation != null) {
1222 return conversation;
1223 }
1224 conversation = databaseBackend.findConversation(account, jid);
1225 if (conversation != null) {
1226 conversation.setStatus(Conversation.STATUS_AVAILABLE);
1227 conversation.setAccount(account);
1228 if (muc) {
1229 conversation.setMode(Conversation.MODE_MULTI);
1230 conversation.setContactJid(jid);
1231 } else {
1232 conversation.setMode(Conversation.MODE_SINGLE);
1233 conversation.setContactJid(jid.toBareJid());
1234 }
1235 conversation.setNextEncryption(-1);
1236 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1237 this.databaseBackend.updateConversation(conversation);
1238 } else {
1239 String conversationName;
1240 Contact contact = account.getRoster().getContact(jid);
1241 if (contact != null) {
1242 conversationName = contact.getDisplayName();
1243 } else {
1244 conversationName = jid.getLocalpart();
1245 }
1246 if (muc) {
1247 conversation = new Conversation(conversationName, account, jid,
1248 Conversation.MODE_MULTI);
1249 } else {
1250 conversation = new Conversation(conversationName, account, jid.toBareJid(),
1251 Conversation.MODE_SINGLE);
1252 }
1253 this.databaseBackend.createConversation(conversation);
1254 }
1255 if (account.getXmppConnection() != null
1256 && account.getXmppConnection().getFeatures().mam()
1257 && !muc) {
1258 if (query == null) {
1259 this.mMessageArchiveService.query(conversation);
1260 } else {
1261 if (query.getConversation() == null) {
1262 this.mMessageArchiveService.query(conversation, query.getStart());
1263 }
1264 }
1265 }
1266 checkDeletedFiles(conversation);
1267 this.conversations.add(conversation);
1268 updateConversationUi();
1269 return conversation;
1270 }
1271 }
1272
1273 public void archiveConversation(Conversation conversation) {
1274 getNotificationService().clear(conversation);
1275 conversation.setStatus(Conversation.STATUS_ARCHIVED);
1276 conversation.setNextEncryption(-1);
1277 synchronized (this.conversations) {
1278 if (conversation.getMode() == Conversation.MODE_MULTI) {
1279 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1280 Bookmark bookmark = conversation.getBookmark();
1281 if (bookmark != null && bookmark.autojoin()) {
1282 bookmark.setAutojoin(false);
1283 pushBookmarks(bookmark.getAccount());
1284 }
1285 }
1286 leaveMuc(conversation);
1287 } else {
1288 conversation.endOtrIfNeeded();
1289 }
1290 this.databaseBackend.updateConversation(conversation);
1291 this.conversations.remove(conversation);
1292 updateConversationUi();
1293 }
1294 }
1295
1296 public void createAccount(final Account account) {
1297 account.initAccountServices(this);
1298 databaseBackend.createAccount(account);
1299 this.accounts.add(account);
1300 this.reconnectAccountInBackground(account);
1301 updateAccountUi();
1302 }
1303
1304 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1305 new Thread(new Runnable() {
1306 @Override
1307 public void run() {
1308 try {
1309 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1310 PrivateKey key = KeyChain.getPrivateKey(XmppConnectionService.this, alias);
1311 X500Name x500name = new JcaX509CertificateHolder(chain[0]).getSubject();
1312 String email = IETFUtils.valueToString(x500name.getRDNs(BCStyle.EmailAddress)[0].getFirst().getValue());
1313 String name = IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue());
1314 Jid jid = Jid.fromString(email);
1315 if (findAccountByJid(jid) == null) {
1316 Account account = new Account(jid, "");
1317 account.setPrivateKeyAlias(alias);
1318 account.setOption(Account.OPTION_DISABLED, true);
1319 createAccount(account);
1320 callback.onAccountCreated(account);
1321 } else {
1322 callback.informUser(R.string.account_already_exists);
1323 }
1324 } catch (KeyChainException e) {
1325 callback.informUser(R.string.unable_to_parse_certificate);
1326 } catch (InterruptedException e) {
1327 callback.informUser(R.string.unable_to_parse_certificate);
1328 e.printStackTrace();
1329 } catch (CertificateEncodingException e) {
1330 callback.informUser(R.string.unable_to_parse_certificate);
1331 e.printStackTrace();
1332 } catch (InvalidJidException e) {
1333 callback.informUser(R.string.unable_to_parse_certificate);
1334 e.printStackTrace();
1335 }
1336 }
1337 }).start();
1338
1339 }
1340
1341 public void updateAccount(final Account account) {
1342 this.statusListener.onStatusChanged(account);
1343 databaseBackend.updateAccount(account);
1344 reconnectAccount(account, false, true);
1345 updateAccountUi();
1346 getNotificationService().updateErrorNotification();
1347 }
1348
1349 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1350 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1351 sendIqPacket(account, iq, new OnIqPacketReceived() {
1352 @Override
1353 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1354 if (packet.getType() == IqPacket.TYPE.RESULT) {
1355 account.setPassword(newPassword);
1356 databaseBackend.updateAccount(account);
1357 callback.onPasswordChangeSucceeded();
1358 } else {
1359 callback.onPasswordChangeFailed();
1360 }
1361 }
1362 });
1363 }
1364
1365 public void deleteAccount(final Account account) {
1366 synchronized (this.conversations) {
1367 for (final Conversation conversation : conversations) {
1368 if (conversation.getAccount() == account) {
1369 if (conversation.getMode() == Conversation.MODE_MULTI) {
1370 leaveMuc(conversation);
1371 } else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1372 conversation.endOtrIfNeeded();
1373 }
1374 conversations.remove(conversation);
1375 }
1376 }
1377 if (account.getXmppConnection() != null) {
1378 this.disconnect(account, true);
1379 }
1380 databaseBackend.deleteAccount(account);
1381 this.accounts.remove(account);
1382 updateAccountUi();
1383 getNotificationService().updateErrorNotification();
1384 }
1385 }
1386
1387 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1388 synchronized (this) {
1389 if (checkListeners()) {
1390 switchToForeground();
1391 }
1392 this.mOnConversationUpdate = listener;
1393 this.mNotificationService.setIsInForeground(true);
1394 if (this.convChangedListenerCount < 2) {
1395 this.convChangedListenerCount++;
1396 }
1397 }
1398 }
1399
1400 public void removeOnConversationListChangedListener() {
1401 synchronized (this) {
1402 this.convChangedListenerCount--;
1403 if (this.convChangedListenerCount <= 0) {
1404 this.convChangedListenerCount = 0;
1405 this.mOnConversationUpdate = null;
1406 this.mNotificationService.setIsInForeground(false);
1407 if (checkListeners()) {
1408 switchToBackground();
1409 }
1410 }
1411 }
1412 }
1413
1414 public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1415 synchronized (this) {
1416 if (checkListeners()) {
1417 switchToForeground();
1418 }
1419 this.mOnShowErrorToast = onShowErrorToast;
1420 if (this.showErrorToastListenerCount < 2) {
1421 this.showErrorToastListenerCount++;
1422 }
1423 }
1424 this.mOnShowErrorToast = onShowErrorToast;
1425 }
1426
1427 public void removeOnShowErrorToastListener() {
1428 synchronized (this) {
1429 this.showErrorToastListenerCount--;
1430 if (this.showErrorToastListenerCount <= 0) {
1431 this.showErrorToastListenerCount = 0;
1432 this.mOnShowErrorToast = null;
1433 if (checkListeners()) {
1434 switchToBackground();
1435 }
1436 }
1437 }
1438 }
1439
1440 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1441 synchronized (this) {
1442 if (checkListeners()) {
1443 switchToForeground();
1444 }
1445 this.mOnAccountUpdate = listener;
1446 if (this.accountChangedListenerCount < 2) {
1447 this.accountChangedListenerCount++;
1448 }
1449 }
1450 }
1451
1452 public void removeOnAccountListChangedListener() {
1453 synchronized (this) {
1454 this.accountChangedListenerCount--;
1455 if (this.accountChangedListenerCount <= 0) {
1456 this.mOnAccountUpdate = null;
1457 this.accountChangedListenerCount = 0;
1458 if (checkListeners()) {
1459 switchToBackground();
1460 }
1461 }
1462 }
1463 }
1464
1465 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1466 synchronized (this) {
1467 if (checkListeners()) {
1468 switchToForeground();
1469 }
1470 this.mOnCaptchaRequested = listener;
1471 if (this.captchaRequestedListenerCount < 2) {
1472 this.captchaRequestedListenerCount++;
1473 }
1474 }
1475 }
1476
1477 public void removeOnCaptchaRequestedListener() {
1478 synchronized (this) {
1479 this.captchaRequestedListenerCount--;
1480 if (this.captchaRequestedListenerCount <= 0) {
1481 this.mOnCaptchaRequested = null;
1482 this.captchaRequestedListenerCount = 0;
1483 if (checkListeners()) {
1484 switchToBackground();
1485 }
1486 }
1487 }
1488 }
1489
1490 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1491 synchronized (this) {
1492 if (checkListeners()) {
1493 switchToForeground();
1494 }
1495 this.mOnRosterUpdate = listener;
1496 if (this.rosterChangedListenerCount < 2) {
1497 this.rosterChangedListenerCount++;
1498 }
1499 }
1500 }
1501
1502 public void removeOnRosterUpdateListener() {
1503 synchronized (this) {
1504 this.rosterChangedListenerCount--;
1505 if (this.rosterChangedListenerCount <= 0) {
1506 this.rosterChangedListenerCount = 0;
1507 this.mOnRosterUpdate = null;
1508 if (checkListeners()) {
1509 switchToBackground();
1510 }
1511 }
1512 }
1513 }
1514
1515 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1516 synchronized (this) {
1517 if (checkListeners()) {
1518 switchToForeground();
1519 }
1520 this.mOnUpdateBlocklist = listener;
1521 if (this.updateBlocklistListenerCount < 2) {
1522 this.updateBlocklistListenerCount++;
1523 }
1524 }
1525 }
1526
1527 public void removeOnUpdateBlocklistListener() {
1528 synchronized (this) {
1529 this.updateBlocklistListenerCount--;
1530 if (this.updateBlocklistListenerCount <= 0) {
1531 this.updateBlocklistListenerCount = 0;
1532 this.mOnUpdateBlocklist = null;
1533 if (checkListeners()) {
1534 switchToBackground();
1535 }
1536 }
1537 }
1538 }
1539
1540 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1541 synchronized (this) {
1542 if (checkListeners()) {
1543 switchToForeground();
1544 }
1545 this.mOnKeyStatusUpdated = listener;
1546 if (this.keyStatusUpdatedListenerCount < 2) {
1547 this.keyStatusUpdatedListenerCount++;
1548 }
1549 }
1550 }
1551
1552 public void removeOnNewKeysAvailableListener() {
1553 synchronized (this) {
1554 this.keyStatusUpdatedListenerCount--;
1555 if (this.keyStatusUpdatedListenerCount <= 0) {
1556 this.keyStatusUpdatedListenerCount = 0;
1557 this.mOnKeyStatusUpdated = null;
1558 if (checkListeners()) {
1559 switchToBackground();
1560 }
1561 }
1562 }
1563 }
1564
1565 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1566 synchronized (this) {
1567 if (checkListeners()) {
1568 switchToForeground();
1569 }
1570 this.mOnMucRosterUpdate = listener;
1571 if (this.mucRosterChangedListenerCount < 2) {
1572 this.mucRosterChangedListenerCount++;
1573 }
1574 }
1575 }
1576
1577 public void removeOnMucRosterUpdateListener() {
1578 synchronized (this) {
1579 this.mucRosterChangedListenerCount--;
1580 if (this.mucRosterChangedListenerCount <= 0) {
1581 this.mucRosterChangedListenerCount = 0;
1582 this.mOnMucRosterUpdate = null;
1583 if (checkListeners()) {
1584 switchToBackground();
1585 }
1586 }
1587 }
1588 }
1589
1590 private boolean checkListeners() {
1591 return (this.mOnAccountUpdate == null
1592 && this.mOnConversationUpdate == null
1593 && this.mOnRosterUpdate == null
1594 && this.mOnCaptchaRequested == null
1595 && this.mOnUpdateBlocklist == null
1596 && this.mOnShowErrorToast == null
1597 && this.mOnKeyStatusUpdated == null);
1598 }
1599
1600 private void switchToForeground() {
1601 for (Account account : getAccounts()) {
1602 if (account.getStatus() == Account.State.ONLINE) {
1603 XmppConnection connection = account.getXmppConnection();
1604 if (connection != null && connection.getFeatures().csi()) {
1605 connection.sendActive();
1606 }
1607 }
1608 }
1609 Log.d(Config.LOGTAG, "app switched into foreground");
1610 }
1611
1612 private void switchToBackground() {
1613 for (Account account : getAccounts()) {
1614 if (account.getStatus() == Account.State.ONLINE) {
1615 XmppConnection connection = account.getXmppConnection();
1616 if (connection != null && connection.getFeatures().csi()) {
1617 connection.sendInactive();
1618 }
1619 }
1620 }
1621 for(Conversation conversation : getConversations()) {
1622 conversation.setIncomingChatState(ChatState.ACTIVE);
1623 }
1624 this.mNotificationService.setIsInForeground(false);
1625 Log.d(Config.LOGTAG, "app switched into background");
1626 }
1627
1628 private void connectMultiModeConversations(Account account) {
1629 List<Conversation> conversations = getConversations();
1630 for (Conversation conversation : conversations) {
1631 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
1632 joinMuc(conversation,true);
1633 }
1634 }
1635 }
1636
1637 public void joinMuc(Conversation conversation) {
1638 joinMuc(conversation, false);
1639 }
1640
1641 private void joinMuc(Conversation conversation, boolean now) {
1642 Account account = conversation.getAccount();
1643 account.pendingConferenceJoins.remove(conversation);
1644 account.pendingConferenceLeaves.remove(conversation);
1645 if (account.getStatus() == Account.State.ONLINE || now) {
1646 conversation.resetMucOptions();
1647 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
1648 @Override
1649 public void onConferenceConfigurationFetched(Conversation conversation) {
1650 Account account = conversation.getAccount();
1651 final String nick = conversation.getMucOptions().getProposedNick();
1652 final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1653 if (joinJid == null) {
1654 return; //safety net
1655 }
1656 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1657 PresencePacket packet = new PresencePacket();
1658 packet.setFrom(conversation.getAccount().getJid());
1659 packet.setTo(joinJid);
1660 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1661 if (conversation.getMucOptions().getPassword() != null) {
1662 x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1663 }
1664
1665 if (conversation.getMucOptions().mamSupport()) {
1666 // Use MAM instead of the limited muc history to get history
1667 x.addChild("history").setAttribute("maxchars", "0");
1668 } else {
1669 // Fallback to muc history
1670 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1671 }
1672 String sig = account.getPgpSignature();
1673 if (sig != null) {
1674 packet.addChild("status").setContent("online");
1675 packet.addChild("x", "jabber:x:signed").setContent(sig);
1676 }
1677 sendPresencePacket(account, packet);
1678 fetchConferenceConfiguration(conversation);
1679 if (!joinJid.equals(conversation.getJid())) {
1680 conversation.setContactJid(joinJid);
1681 databaseBackend.updateConversation(conversation);
1682 }
1683 conversation.setHasMessagesLeftOnServer(false);
1684 if (conversation.getMucOptions().mamSupport()) {
1685 getMessageArchiveService().catchupMUC(conversation);
1686 }
1687 }
1688 });
1689
1690 } else {
1691 account.pendingConferenceJoins.add(conversation);
1692 }
1693 }
1694
1695 public void providePasswordForMuc(Conversation conversation, String password) {
1696 if (conversation.getMode() == Conversation.MODE_MULTI) {
1697 conversation.getMucOptions().setPassword(password);
1698 if (conversation.getBookmark() != null) {
1699 conversation.getBookmark().setAutojoin(true);
1700 pushBookmarks(conversation.getAccount());
1701 }
1702 databaseBackend.updateConversation(conversation);
1703 joinMuc(conversation);
1704 }
1705 }
1706
1707 public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1708 final MucOptions options = conversation.getMucOptions();
1709 final Jid joinJid = options.createJoinJid(nick);
1710 if (options.online()) {
1711 Account account = conversation.getAccount();
1712 options.setOnRenameListener(new OnRenameListener() {
1713
1714 @Override
1715 public void onSuccess() {
1716 conversation.setContactJid(joinJid);
1717 databaseBackend.updateConversation(conversation);
1718 Bookmark bookmark = conversation.getBookmark();
1719 if (bookmark != null) {
1720 bookmark.setNick(nick);
1721 pushBookmarks(bookmark.getAccount());
1722 }
1723 callback.success(conversation);
1724 }
1725
1726 @Override
1727 public void onFailure() {
1728 callback.error(R.string.nick_in_use, conversation);
1729 }
1730 });
1731
1732 PresencePacket packet = new PresencePacket();
1733 packet.setTo(joinJid);
1734 packet.setFrom(conversation.getAccount().getJid());
1735
1736 String sig = account.getPgpSignature();
1737 if (sig != null) {
1738 packet.addChild("status").setContent("online");
1739 packet.addChild("x", "jabber:x:signed").setContent(sig);
1740 }
1741 sendPresencePacket(account, packet);
1742 } else {
1743 conversation.setContactJid(joinJid);
1744 databaseBackend.updateConversation(conversation);
1745 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1746 Bookmark bookmark = conversation.getBookmark();
1747 if (bookmark != null) {
1748 bookmark.setNick(nick);
1749 pushBookmarks(bookmark.getAccount());
1750 }
1751 joinMuc(conversation);
1752 }
1753 }
1754 }
1755
1756 public void leaveMuc(Conversation conversation) {
1757 Account account = conversation.getAccount();
1758 account.pendingConferenceJoins.remove(conversation);
1759 account.pendingConferenceLeaves.remove(conversation);
1760 if (account.getStatus() == Account.State.ONLINE) {
1761 PresencePacket packet = new PresencePacket();
1762 packet.setTo(conversation.getJid());
1763 packet.setFrom(conversation.getAccount().getJid());
1764 packet.setAttribute("type", "unavailable");
1765 sendPresencePacket(conversation.getAccount(), packet);
1766 conversation.getMucOptions().setOffline();
1767 conversation.deregisterWithBookmark();
1768 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1769 + ": leaving muc " + conversation.getJid());
1770 } else {
1771 account.pendingConferenceLeaves.add(conversation);
1772 }
1773 }
1774
1775 private String findConferenceServer(final Account account) {
1776 String server;
1777 if (account.getXmppConnection() != null) {
1778 server = account.getXmppConnection().getMucServer();
1779 if (server != null) {
1780 return server;
1781 }
1782 }
1783 for (Account other : getAccounts()) {
1784 if (other != account && other.getXmppConnection() != null) {
1785 server = other.getXmppConnection().getMucServer();
1786 if (server != null) {
1787 return server;
1788 }
1789 }
1790 }
1791 return null;
1792 }
1793
1794 public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1795 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1796 if (account.getStatus() == Account.State.ONLINE) {
1797 try {
1798 String server = findConferenceServer(account);
1799 if (server == null) {
1800 if (callback != null) {
1801 callback.error(R.string.no_conference_server_found, null);
1802 }
1803 return;
1804 }
1805 String name = new BigInteger(75, getRNG()).toString(32);
1806 Jid jid = Jid.fromParts(name, server, null);
1807 final Conversation conversation = findOrCreateConversation(account, jid, true);
1808 joinMuc(conversation);
1809 Bundle options = new Bundle();
1810 options.putString("muc#roomconfig_persistentroom", "1");
1811 options.putString("muc#roomconfig_membersonly", "1");
1812 options.putString("muc#roomconfig_publicroom", "0");
1813 options.putString("muc#roomconfig_whois", "anyone");
1814 pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1815 @Override
1816 public void onPushSucceeded() {
1817 for (Jid invite : jids) {
1818 invite(conversation, invite);
1819 }
1820 if (account.countPresences() > 1) {
1821 directInvite(conversation, account.getJid().toBareJid());
1822 }
1823 if (callback != null) {
1824 callback.success(conversation);
1825 }
1826 }
1827
1828 @Override
1829 public void onPushFailed() {
1830 if (callback != null) {
1831 callback.error(R.string.conference_creation_failed, conversation);
1832 }
1833 }
1834 });
1835
1836 } catch (InvalidJidException e) {
1837 if (callback != null) {
1838 callback.error(R.string.conference_creation_failed, null);
1839 }
1840 }
1841 } else {
1842 if (callback != null) {
1843 callback.error(R.string.not_connected_try_again, null);
1844 }
1845 }
1846 }
1847
1848 public void fetchConferenceConfiguration(final Conversation conversation) {
1849 fetchConferenceConfiguration(conversation, null);
1850 }
1851
1852 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
1853 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1854 request.setTo(conversation.getJid().toBareJid());
1855 request.query("http://jabber.org/protocol/disco#info");
1856 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1857 @Override
1858 public void onIqPacketReceived(Account account, IqPacket packet) {
1859 if (packet.getType() == IqPacket.TYPE.RESULT) {
1860 ArrayList<String> features = new ArrayList<>();
1861 for (Element child : packet.query().getChildren()) {
1862 if (child != null && child.getName().equals("feature")) {
1863 String var = child.getAttribute("var");
1864 if (var != null) {
1865 features.add(var);
1866 }
1867 }
1868 }
1869 conversation.getMucOptions().updateFeatures(features);
1870 if (callback != null) {
1871 callback.onConferenceConfigurationFetched(conversation);
1872 }
1873 updateConversationUi();
1874 }
1875 }
1876 });
1877 }
1878
1879 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1880 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1881 request.setTo(conversation.getJid().toBareJid());
1882 request.query("http://jabber.org/protocol/muc#owner");
1883 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1884 @Override
1885 public void onIqPacketReceived(Account account, IqPacket packet) {
1886 if (packet.getType() == IqPacket.TYPE.RESULT) {
1887 Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1888 for (Field field : data.getFields()) {
1889 if (options.containsKey(field.getFieldName())) {
1890 field.setValue(options.getString(field.getFieldName()));
1891 }
1892 }
1893 data.submit();
1894 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1895 set.setTo(conversation.getJid().toBareJid());
1896 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1897 sendIqPacket(account, set, new OnIqPacketReceived() {
1898 @Override
1899 public void onIqPacketReceived(Account account, IqPacket packet) {
1900 if (callback != null) {
1901 if (packet.getType() == IqPacket.TYPE.RESULT) {
1902 callback.onPushSucceeded();
1903 } else {
1904 callback.onPushFailed();
1905 }
1906 }
1907 }
1908 });
1909 } else {
1910 if (callback != null) {
1911 callback.onPushFailed();
1912 }
1913 }
1914 }
1915 });
1916 }
1917
1918 public void pushSubjectToConference(final Conversation conference, final String subject) {
1919 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1920 this.sendMessagePacket(conference.getAccount(), packet);
1921 final MucOptions mucOptions = conference.getMucOptions();
1922 final MucOptions.User self = mucOptions.getSelf();
1923 if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1924 Bundle options = new Bundle();
1925 options.putString("muc#roomconfig_persistentroom", "1");
1926 this.pushConferenceConfiguration(conference, options, null);
1927 }
1928 }
1929
1930 public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1931 final Jid jid = user.toBareJid();
1932 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1933 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1934 @Override
1935 public void onIqPacketReceived(Account account, IqPacket packet) {
1936 if (packet.getType() == IqPacket.TYPE.RESULT) {
1937 callback.onAffiliationChangedSuccessful(jid);
1938 } else {
1939 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1940 }
1941 }
1942 });
1943 }
1944
1945 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1946 List<Jid> jids = new ArrayList<>();
1947 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1948 if (user.getAffiliation() == before && user.getJid() != null) {
1949 jids.add(user.getJid());
1950 }
1951 }
1952 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1953 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1954 }
1955
1956 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1957 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1958 Log.d(Config.LOGTAG, request.toString());
1959 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1960 @Override
1961 public void onIqPacketReceived(Account account, IqPacket packet) {
1962 Log.d(Config.LOGTAG, packet.toString());
1963 if (packet.getType() == IqPacket.TYPE.RESULT) {
1964 callback.onRoleChangedSuccessful(nick);
1965 } else {
1966 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1967 }
1968 }
1969 });
1970 }
1971
1972 public void disconnect(Account account, boolean force) {
1973 if ((account.getStatus() == Account.State.ONLINE)
1974 || (account.getStatus() == Account.State.DISABLED)) {
1975 if (!force) {
1976 List<Conversation> conversations = getConversations();
1977 for (Conversation conversation : conversations) {
1978 if (conversation.getAccount() == account) {
1979 if (conversation.getMode() == Conversation.MODE_MULTI) {
1980 leaveMuc(conversation);
1981 } else {
1982 if (conversation.endOtrIfNeeded()) {
1983 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1984 + ": ended otr session with "
1985 + conversation.getJid());
1986 }
1987 }
1988 }
1989 }
1990 sendOfflinePresence(account);
1991 }
1992 account.getXmppConnection().disconnect(force);
1993 }
1994 }
1995
1996 @Override
1997 public IBinder onBind(Intent intent) {
1998 return mBinder;
1999 }
2000
2001 public void updateMessage(Message message) {
2002 databaseBackend.updateMessage(message);
2003 updateConversationUi();
2004 }
2005
2006 protected void syncDirtyContacts(Account account) {
2007 for (Contact contact : account.getRoster().getContacts()) {
2008 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2009 pushContactToServer(contact);
2010 }
2011 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2012 deleteContactOnServer(contact);
2013 }
2014 }
2015 }
2016
2017 public void createContact(Contact contact) {
2018 SharedPreferences sharedPref = getPreferences();
2019 boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
2020 if (autoGrant) {
2021 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2022 contact.setOption(Contact.Options.ASKING);
2023 }
2024 pushContactToServer(contact);
2025 }
2026
2027 public void onOtrSessionEstablished(Conversation conversation) {
2028 final Account account = conversation.getAccount();
2029 final Session otrSession = conversation.getOtrSession();
2030 Log.d(Config.LOGTAG,
2031 account.getJid().toBareJid() + " otr session established with "
2032 + conversation.getJid() + "/"
2033 + otrSession.getSessionID().getUserID());
2034 conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2035
2036 @Override
2037 public void onMessageFound(Message message) {
2038 SessionID id = otrSession.getSessionID();
2039 try {
2040 message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2041 } catch (InvalidJidException e) {
2042 return;
2043 }
2044 if (message.needsUploading()) {
2045 mJingleConnectionManager.createNewConnection(message);
2046 } else {
2047 MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2048 if (outPacket != null) {
2049 mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2050 message.setStatus(Message.STATUS_SEND);
2051 databaseBackend.updateMessage(message);
2052 sendMessagePacket(account, outPacket);
2053 }
2054 }
2055 updateConversationUi();
2056 }
2057 });
2058 }
2059
2060 public boolean renewSymmetricKey(Conversation conversation) {
2061 Account account = conversation.getAccount();
2062 byte[] symmetricKey = new byte[32];
2063 this.mRandom.nextBytes(symmetricKey);
2064 Session otrSession = conversation.getOtrSession();
2065 if (otrSession != null) {
2066 MessagePacket packet = new MessagePacket();
2067 packet.setType(MessagePacket.TYPE_CHAT);
2068 packet.setFrom(account.getJid());
2069 MessageGenerator.addMessageHints(packet);
2070 packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2071 + otrSession.getSessionID().getUserID());
2072 try {
2073 packet.setBody(otrSession
2074 .transformSending(CryptoHelper.FILETRANSFER
2075 + CryptoHelper.bytesToHex(symmetricKey))[0]);
2076 sendMessagePacket(account, packet);
2077 conversation.setSymmetricKey(symmetricKey);
2078 return true;
2079 } catch (OtrException e) {
2080 return false;
2081 }
2082 }
2083 return false;
2084 }
2085
2086 public void pushContactToServer(final Contact contact) {
2087 contact.resetOption(Contact.Options.DIRTY_DELETE);
2088 contact.setOption(Contact.Options.DIRTY_PUSH);
2089 final Account account = contact.getAccount();
2090 if (account.getStatus() == Account.State.ONLINE) {
2091 final boolean ask = contact.getOption(Contact.Options.ASKING);
2092 final boolean sendUpdates = contact
2093 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2094 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2095 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2096 iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2097 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2098 if (sendUpdates) {
2099 sendPresencePacket(account,
2100 mPresenceGenerator.sendPresenceUpdatesTo(contact));
2101 }
2102 if (ask) {
2103 sendPresencePacket(account,
2104 mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2105 }
2106 }
2107 }
2108
2109 public void publishAvatar(final Account account,
2110 final Uri image,
2111 final UiCallback<Avatar> callback) {
2112 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2113 final int size = Config.AVATAR_SIZE;
2114 final Avatar avatar = getFileBackend()
2115 .getPepAvatar(image, size, format);
2116 if (avatar != null) {
2117 avatar.height = size;
2118 avatar.width = size;
2119 if (format.equals(Bitmap.CompressFormat.WEBP)) {
2120 avatar.type = "image/webp";
2121 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2122 avatar.type = "image/jpeg";
2123 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
2124 avatar.type = "image/png";
2125 }
2126 if (!getFileBackend().save(avatar)) {
2127 callback.error(R.string.error_saving_avatar, avatar);
2128 return;
2129 }
2130 final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2131 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2132
2133 @Override
2134 public void onIqPacketReceived(Account account, IqPacket result) {
2135 if (result.getType() == IqPacket.TYPE.RESULT) {
2136 final IqPacket packet = XmppConnectionService.this.mIqGenerator
2137 .publishAvatarMetadata(avatar);
2138 sendIqPacket(account, packet, new OnIqPacketReceived() {
2139 @Override
2140 public void onIqPacketReceived(Account account, IqPacket result) {
2141 if (result.getType() == IqPacket.TYPE.RESULT) {
2142 if (account.setAvatar(avatar.getFilename())) {
2143 getAvatarService().clear(account);
2144 databaseBackend.updateAccount(account);
2145 }
2146 callback.success(avatar);
2147 } else {
2148 callback.error(
2149 R.string.error_publish_avatar_server_reject,
2150 avatar);
2151 }
2152 }
2153 });
2154 } else {
2155 callback.error(
2156 R.string.error_publish_avatar_server_reject,
2157 avatar);
2158 }
2159 }
2160 });
2161 } else {
2162 callback.error(R.string.error_publish_avatar_converting, null);
2163 }
2164 }
2165
2166 public void fetchAvatar(Account account, Avatar avatar) {
2167 fetchAvatar(account, avatar, null);
2168 }
2169
2170 private static String generateFetchKey(Account account, final Avatar avatar) {
2171 return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum;
2172 }
2173
2174 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2175 final String KEY = generateFetchKey(account, avatar);
2176 synchronized(this.mInProgressAvatarFetches) {
2177 if (this.mInProgressAvatarFetches.contains(KEY)) {
2178 return;
2179 } else {
2180 switch (avatar.origin) {
2181 case PEP:
2182 this.mInProgressAvatarFetches.add(KEY);
2183 fetchAvatarPep(account, avatar, callback);
2184 break;
2185 case VCARD:
2186 this.mInProgressAvatarFetches.add(KEY);
2187 fetchAvatarVcard(account, avatar, callback);
2188 break;
2189 }
2190 }
2191 }
2192 }
2193
2194 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2195 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2196 sendIqPacket(account, packet, new OnIqPacketReceived() {
2197
2198 @Override
2199 public void onIqPacketReceived(Account account, IqPacket result) {
2200 synchronized (mInProgressAvatarFetches) {
2201 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2202 }
2203 final String ERROR = account.getJid().toBareJid()
2204 + ": fetching avatar for " + avatar.owner + " failed ";
2205 if (result.getType() == IqPacket.TYPE.RESULT) {
2206 avatar.image = mIqParser.avatarData(result);
2207 if (avatar.image != null) {
2208 if (getFileBackend().save(avatar)) {
2209 if (account.getJid().toBareJid().equals(avatar.owner)) {
2210 if (account.setAvatar(avatar.getFilename())) {
2211 databaseBackend.updateAccount(account);
2212 }
2213 getAvatarService().clear(account);
2214 updateConversationUi();
2215 updateAccountUi();
2216 } else {
2217 Contact contact = account.getRoster()
2218 .getContact(avatar.owner);
2219 contact.setAvatar(avatar);
2220 getAvatarService().clear(contact);
2221 updateConversationUi();
2222 updateRosterUi();
2223 }
2224 if (callback != null) {
2225 callback.success(avatar);
2226 }
2227 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2228 + ": succesfuly fetched pep avatar for " + avatar.owner);
2229 return;
2230 }
2231 } else {
2232
2233 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2234 }
2235 } else {
2236 Element error = result.findChild("error");
2237 if (error == null) {
2238 Log.d(Config.LOGTAG, ERROR + "(server error)");
2239 } else {
2240 Log.d(Config.LOGTAG, ERROR + error.toString());
2241 }
2242 }
2243 if (callback != null) {
2244 callback.error(0, null);
2245 }
2246
2247 }
2248 });
2249 }
2250
2251 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2252 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2253 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2254 @Override
2255 public void onIqPacketReceived(Account account, IqPacket packet) {
2256 synchronized (mInProgressAvatarFetches) {
2257 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2258 }
2259 if (packet.getType() == IqPacket.TYPE.RESULT) {
2260 Element vCard = packet.findChild("vCard", "vcard-temp");
2261 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2262 String image = photo != null ? photo.findChildContent("BINVAL") : null;
2263 if (image != null) {
2264 avatar.image = image;
2265 if (getFileBackend().save(avatar)) {
2266 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2267 + ": successfully fetched vCard avatar for " + avatar.owner);
2268 Contact contact = account.getRoster()
2269 .getContact(avatar.owner);
2270 contact.setAvatar(avatar);
2271 getAvatarService().clear(contact);
2272 updateConversationUi();
2273 updateRosterUi();
2274 }
2275 }
2276 }
2277 }
2278 });
2279 }
2280
2281 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2282 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2283 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2284
2285 @Override
2286 public void onIqPacketReceived(Account account, IqPacket packet) {
2287 if (packet.getType() == IqPacket.TYPE.RESULT) {
2288 Element pubsub = packet.findChild("pubsub",
2289 "http://jabber.org/protocol/pubsub");
2290 if (pubsub != null) {
2291 Element items = pubsub.findChild("items");
2292 if (items != null) {
2293 Avatar avatar = Avatar.parseMetadata(items);
2294 if (avatar != null) {
2295 avatar.owner = account.getJid().toBareJid();
2296 if (fileBackend.isAvatarCached(avatar)) {
2297 if (account.setAvatar(avatar.getFilename())) {
2298 databaseBackend.updateAccount(account);
2299 }
2300 getAvatarService().clear(account);
2301 callback.success(avatar);
2302 } else {
2303 fetchAvatarPep(account, avatar, callback);
2304 }
2305 return;
2306 }
2307 }
2308 }
2309 }
2310 callback.error(0, null);
2311 }
2312 });
2313 }
2314
2315 public void deleteContactOnServer(Contact contact) {
2316 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2317 contact.resetOption(Contact.Options.DIRTY_PUSH);
2318 contact.setOption(Contact.Options.DIRTY_DELETE);
2319 Account account = contact.getAccount();
2320 if (account.getStatus() == Account.State.ONLINE) {
2321 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2322 Element item = iq.query(Xmlns.ROSTER).addChild("item");
2323 item.setAttribute("jid", contact.getJid().toString());
2324 item.setAttribute("subscription", "remove");
2325 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2326 }
2327 }
2328
2329 public void updateConversation(Conversation conversation) {
2330 this.databaseBackend.updateConversation(conversation);
2331 }
2332
2333 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2334 synchronized (account) {
2335 if (account.getXmppConnection() != null) {
2336 disconnect(account, force);
2337 }
2338 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2339
2340 synchronized (this.mInProgressAvatarFetches) {
2341 for(Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) {
2342 final String KEY = iterator.next();
2343 if (KEY.startsWith(account.getJid().toBareJid()+"_")) {
2344 iterator.remove();
2345 }
2346 }
2347 }
2348
2349 if (account.getXmppConnection() == null) {
2350 account.setXmppConnection(createConnection(account));
2351 }
2352 Thread thread = new Thread(account.getXmppConnection());
2353 account.getXmppConnection().setInteractive(interactive);
2354 thread.start();
2355 scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2356 } else {
2357 account.getRoster().clearPresences();
2358 account.setXmppConnection(null);
2359 }
2360 }
2361 }
2362
2363 public void reconnectAccountInBackground(final Account account) {
2364 new Thread(new Runnable() {
2365 @Override
2366 public void run() {
2367 reconnectAccount(account,false,true);
2368 }
2369 }).start();
2370 }
2371
2372 public void invite(Conversation conversation, Jid contact) {
2373 Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid());
2374 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2375 sendMessagePacket(conversation.getAccount(), packet);
2376 }
2377
2378 public void directInvite(Conversation conversation, Jid jid) {
2379 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2380 sendMessagePacket(conversation.getAccount(),packet);
2381 }
2382
2383 public void resetSendingToWaiting(Account account) {
2384 for (Conversation conversation : getConversations()) {
2385 if (conversation.getAccount() == account) {
2386 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2387
2388 @Override
2389 public void onMessageFound(Message message) {
2390 markMessage(message, Message.STATUS_WAITING);
2391 }
2392 });
2393 }
2394 }
2395 }
2396
2397 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2398 if (uuid == null) {
2399 return null;
2400 }
2401 for (Conversation conversation : getConversations()) {
2402 if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2403 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2404 if (message != null) {
2405 markMessage(message, status);
2406 }
2407 return message;
2408 }
2409 }
2410 return null;
2411 }
2412
2413 public boolean markMessage(Conversation conversation, String uuid, int status) {
2414 if (uuid == null) {
2415 return false;
2416 } else {
2417 Message message = conversation.findSentMessageWithUuid(uuid);
2418 if (message != null) {
2419 markMessage(message, status);
2420 return true;
2421 } else {
2422 return false;
2423 }
2424 }
2425 }
2426
2427 public void markMessage(Message message, int status) {
2428 if (status == Message.STATUS_SEND_FAILED
2429 && (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2430 .getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2431 return;
2432 }
2433 message.setStatus(status);
2434 databaseBackend.updateMessage(message);
2435 updateConversationUi();
2436 }
2437
2438 public SharedPreferences getPreferences() {
2439 return PreferenceManager
2440 .getDefaultSharedPreferences(getApplicationContext());
2441 }
2442
2443 public boolean forceEncryption() {
2444 return getPreferences().getBoolean("force_encryption", false);
2445 }
2446
2447 public boolean confirmMessages() {
2448 return getPreferences().getBoolean("confirm_messages", true);
2449 }
2450
2451 public boolean sendChatStates() {
2452 return getPreferences().getBoolean("chat_states", false);
2453 }
2454
2455 public boolean saveEncryptedMessages() {
2456 return !getPreferences().getBoolean("dont_save_encrypted", false);
2457 }
2458
2459 public boolean indicateReceived() {
2460 return getPreferences().getBoolean("indicate_received", false);
2461 }
2462
2463 public int unreadCount() {
2464 int count = 0;
2465 for(Conversation conversation : getConversations()) {
2466 count += conversation.unreadCount();
2467 }
2468 return count;
2469 }
2470
2471
2472 public void showErrorToastInUi(int resId) {
2473 if (mOnShowErrorToast != null) {
2474 mOnShowErrorToast.onShowErrorToast(resId);
2475 }
2476 }
2477
2478 public void updateConversationUi() {
2479 if (mOnConversationUpdate != null) {
2480 mOnConversationUpdate.onConversationUpdate();
2481 }
2482 }
2483
2484 public void updateAccountUi() {
2485 if (mOnAccountUpdate != null) {
2486 mOnAccountUpdate.onAccountUpdate();
2487 }
2488 }
2489
2490 public void updateRosterUi() {
2491 if (mOnRosterUpdate != null) {
2492 mOnRosterUpdate.onRosterUpdate();
2493 }
2494 }
2495
2496 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2497 boolean rc = false;
2498 if (mOnCaptchaRequested != null) {
2499 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2500 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int)(captcha.getWidth() * metrics.scaledDensity),
2501 (int)(captcha.getHeight() * metrics.scaledDensity), false);
2502
2503 mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2504 rc = true;
2505 }
2506
2507 return rc;
2508 }
2509
2510 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2511 if (mOnUpdateBlocklist != null) {
2512 mOnUpdateBlocklist.OnUpdateBlocklist(status);
2513 }
2514 }
2515
2516 public void updateMucRosterUi() {
2517 if (mOnMucRosterUpdate != null) {
2518 mOnMucRosterUpdate.onMucRosterUpdate();
2519 }
2520 }
2521
2522 public void keyStatusUpdated() {
2523 if(mOnKeyStatusUpdated != null) {
2524 mOnKeyStatusUpdated.onKeyStatusUpdated();
2525 }
2526 }
2527
2528 public Account findAccountByJid(final Jid accountJid) {
2529 for (Account account : this.accounts) {
2530 if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2531 return account;
2532 }
2533 }
2534 return null;
2535 }
2536
2537 public Conversation findConversationByUuid(String uuid) {
2538 for (Conversation conversation : getConversations()) {
2539 if (conversation.getUuid().equals(uuid)) {
2540 return conversation;
2541 }
2542 }
2543 return null;
2544 }
2545
2546 public void markRead(final Conversation conversation) {
2547 mNotificationService.clear(conversation);
2548 conversation.markRead();
2549 updateUnreadCountBadge();
2550 }
2551
2552 public synchronized void updateUnreadCountBadge() {
2553 int count = unreadCount();
2554 if (unreadCount != count) {
2555 Log.d(Config.LOGTAG, "update unread count to " + count);
2556 if (count > 0) {
2557 ShortcutBadger.with(getApplicationContext()).count(count);
2558 } else {
2559 ShortcutBadger.with(getApplicationContext()).remove();
2560 }
2561 unreadCount = count;
2562 }
2563 }
2564
2565 public void sendReadMarker(final Conversation conversation) {
2566 final Message markable = conversation.getLatestMarkableMessage();
2567 this.markRead(conversation);
2568 if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2569 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2570 Account account = conversation.getAccount();
2571 final Jid to = markable.getCounterpart();
2572 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2573 this.sendMessagePacket(conversation.getAccount(), packet);
2574 }
2575 updateConversationUi();
2576 }
2577
2578 public SecureRandom getRNG() {
2579 return this.mRandom;
2580 }
2581
2582 public MemorizingTrustManager getMemorizingTrustManager() {
2583 return this.mMemorizingTrustManager;
2584 }
2585
2586 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2587 this.mMemorizingTrustManager = trustManager;
2588 }
2589
2590 public void updateMemorizingTrustmanager() {
2591 final MemorizingTrustManager tm;
2592 final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2593 if (dontTrustSystemCAs) {
2594 tm = new MemorizingTrustManager(getApplicationContext(), null);
2595 } else {
2596 tm = new MemorizingTrustManager(getApplicationContext());
2597 }
2598 setMemorizingTrustManager(tm);
2599 }
2600
2601 public PowerManager getPowerManager() {
2602 return this.pm;
2603 }
2604
2605 public LruCache<String, Bitmap> getBitmapCache() {
2606 return this.mBitmapCache;
2607 }
2608
2609 public void syncRosterToDisk(final Account account) {
2610 Runnable runnable = new Runnable() {
2611
2612 @Override
2613 public void run() {
2614 databaseBackend.writeRoster(account.getRoster());
2615 }
2616 };
2617 mDatabaseExecutor.execute(runnable);
2618
2619 }
2620
2621 public List<String> getKnownHosts() {
2622 final List<String> hosts = new ArrayList<>();
2623 for (final Account account : getAccounts()) {
2624 if (!hosts.contains(account.getServer().toString())) {
2625 hosts.add(account.getServer().toString());
2626 }
2627 for (final Contact contact : account.getRoster().getContacts()) {
2628 if (contact.showInRoster()) {
2629 final String server = contact.getServer().toString();
2630 if (server != null && !hosts.contains(server)) {
2631 hosts.add(server);
2632 }
2633 }
2634 }
2635 }
2636 return hosts;
2637 }
2638
2639 public List<String> getKnownConferenceHosts() {
2640 final ArrayList<String> mucServers = new ArrayList<>();
2641 for (final Account account : accounts) {
2642 if (account.getXmppConnection() != null) {
2643 final String server = account.getXmppConnection().getMucServer();
2644 if (server != null && !mucServers.contains(server)) {
2645 mucServers.add(server);
2646 }
2647 }
2648 }
2649 return mucServers;
2650 }
2651
2652 public void sendMessagePacket(Account account, MessagePacket packet) {
2653 XmppConnection connection = account.getXmppConnection();
2654 if (connection != null) {
2655 connection.sendMessagePacket(packet);
2656 }
2657 }
2658
2659 public void sendPresencePacket(Account account, PresencePacket packet) {
2660 XmppConnection connection = account.getXmppConnection();
2661 if (connection != null) {
2662 connection.sendPresencePacket(packet);
2663 }
2664 }
2665
2666 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
2667 XmppConnection connection = account.getXmppConnection();
2668 if (connection != null) {
2669 connection.sendCaptchaRegistryRequest(id, data);
2670 }
2671 }
2672
2673 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2674 final XmppConnection connection = account.getXmppConnection();
2675 if (connection != null) {
2676 connection.sendIqPacket(packet, callback);
2677 }
2678 }
2679
2680 public void sendPresence(final Account account) {
2681 sendPresencePacket(account, mPresenceGenerator.selfPresence(account, getTargetPresence()));
2682 }
2683
2684 public void refreshAllPresences() {
2685 for (Account account : getAccounts()) {
2686 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2687 sendPresence(account);
2688 }
2689 }
2690 }
2691
2692 public void sendOfflinePresence(final Account account) {
2693 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2694 }
2695
2696 public MessageGenerator getMessageGenerator() {
2697 return this.mMessageGenerator;
2698 }
2699
2700 public PresenceGenerator getPresenceGenerator() {
2701 return this.mPresenceGenerator;
2702 }
2703
2704 public IqGenerator getIqGenerator() {
2705 return this.mIqGenerator;
2706 }
2707
2708 public IqParser getIqParser() {
2709 return this.mIqParser;
2710 }
2711
2712 public JingleConnectionManager getJingleConnectionManager() {
2713 return this.mJingleConnectionManager;
2714 }
2715
2716 public MessageArchiveService getMessageArchiveService() {
2717 return this.mMessageArchiveService;
2718 }
2719
2720 public List<Contact> findContacts(Jid jid) {
2721 ArrayList<Contact> contacts = new ArrayList<>();
2722 for (Account account : getAccounts()) {
2723 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2724 Contact contact = account.getRoster().getContactFromRoster(jid);
2725 if (contact != null) {
2726 contacts.add(contact);
2727 }
2728 }
2729 }
2730 return contacts;
2731 }
2732
2733 public NotificationService getNotificationService() {
2734 return this.mNotificationService;
2735 }
2736
2737 public HttpConnectionManager getHttpConnectionManager() {
2738 return this.mHttpConnectionManager;
2739 }
2740
2741 public void resendFailedMessages(final Message message) {
2742 final Collection<Message> messages = new ArrayList<>();
2743 Message current = message;
2744 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2745 messages.add(current);
2746 if (current.mergeable(current.next())) {
2747 current = current.next();
2748 } else {
2749 break;
2750 }
2751 }
2752 for (final Message msg : messages) {
2753 msg.setTime(System.currentTimeMillis());
2754 markMessage(msg, Message.STATUS_WAITING);
2755 this.resendMessage(msg,false);
2756 }
2757 }
2758
2759 public void clearConversationHistory(final Conversation conversation) {
2760 conversation.clearMessages();
2761 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2762 conversation.resetLastMessageTransmitted();
2763 new Thread(new Runnable() {
2764 @Override
2765 public void run() {
2766 databaseBackend.deleteMessagesInConversation(conversation);
2767 }
2768 }).start();
2769 }
2770
2771 public void sendBlockRequest(final Blockable blockable) {
2772 if (blockable != null && blockable.getBlockedJid() != null) {
2773 final Jid jid = blockable.getBlockedJid();
2774 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2775
2776 @Override
2777 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2778 if (packet.getType() == IqPacket.TYPE.RESULT) {
2779 account.getBlocklist().add(jid);
2780 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2781 }
2782 }
2783 });
2784 }
2785 }
2786
2787 public void sendUnblockRequest(final Blockable blockable) {
2788 if (blockable != null && blockable.getJid() != null) {
2789 final Jid jid = blockable.getBlockedJid();
2790 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2791 @Override
2792 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2793 if (packet.getType() == IqPacket.TYPE.RESULT) {
2794 account.getBlocklist().remove(jid);
2795 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2796 }
2797 }
2798 });
2799 }
2800 }
2801
2802 public interface OnAccountCreated {
2803 void onAccountCreated(Account account);
2804 void informUser(int r);
2805 }
2806
2807 public interface OnMoreMessagesLoaded {
2808 void onMoreMessagesLoaded(int count, Conversation conversation);
2809
2810 void informUser(int r);
2811 }
2812
2813 public interface OnAccountPasswordChanged {
2814 void onPasswordChangeSucceeded();
2815
2816 void onPasswordChangeFailed();
2817 }
2818
2819 public interface OnAffiliationChanged {
2820 void onAffiliationChangedSuccessful(Jid jid);
2821
2822 void onAffiliationChangeFailed(Jid jid, int resId);
2823 }
2824
2825 public interface OnRoleChanged {
2826 void onRoleChangedSuccessful(String nick);
2827
2828 void onRoleChangeFailed(String nick, int resid);
2829 }
2830
2831 public interface OnConversationUpdate {
2832 void onConversationUpdate();
2833 }
2834
2835 public interface OnAccountUpdate {
2836 void onAccountUpdate();
2837 }
2838
2839 public interface OnCaptchaRequested {
2840 void onCaptchaRequested(Account account,
2841 String id,
2842 Data data,
2843 Bitmap captcha);
2844 }
2845
2846 public interface OnRosterUpdate {
2847 void onRosterUpdate();
2848 }
2849
2850 public interface OnMucRosterUpdate {
2851 void onMucRosterUpdate();
2852 }
2853
2854 public interface OnConferenceConfigurationFetched {
2855 void onConferenceConfigurationFetched(Conversation conversation);
2856 }
2857
2858 public interface OnConferenceOptionsPushed {
2859 void onPushSucceeded();
2860
2861 void onPushFailed();
2862 }
2863
2864 public interface OnShowErrorToast {
2865 void onShowErrorToast(int resId);
2866 }
2867
2868 public class XmppConnectionBinder extends Binder {
2869 public XmppConnectionService getService() {
2870 return XmppConnectionService.this;
2871 }
2872 }
2873}