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