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