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