1package eu.siacs.conversations.services;
2
3import android.annotation.SuppressLint;
4import android.app.AlarmManager;
5import android.app.PendingIntent;
6import android.app.Service;
7import android.content.Context;
8import android.content.Intent;
9import android.content.SharedPreferences;
10import android.database.ContentObserver;
11import android.graphics.Bitmap;
12import android.net.ConnectivityManager;
13import android.net.NetworkInfo;
14import android.net.Uri;
15import android.os.Binder;
16import android.os.Bundle;
17import android.os.FileObserver;
18import android.os.IBinder;
19import android.os.PowerManager;
20import android.os.PowerManager.WakeLock;
21import android.os.SystemClock;
22import android.preference.PreferenceManager;
23import android.provider.ContactsContract;
24import android.util.Log;
25import android.util.LruCache;
26
27import net.java.otr4j.OtrException;
28import net.java.otr4j.session.Session;
29import net.java.otr4j.session.SessionID;
30import net.java.otr4j.session.SessionStatus;
31
32import org.openintents.openpgp.util.OpenPgpApi;
33import org.openintents.openpgp.util.OpenPgpServiceConnection;
34
35import java.math.BigInteger;
36import java.security.SecureRandom;
37import java.util.ArrayList;
38import java.util.Collection;
39import java.util.Collections;
40import java.util.Comparator;
41import java.util.Hashtable;
42import java.util.List;
43import java.util.Locale;
44import java.util.Map;
45import java.util.concurrent.CopyOnWriteArrayList;
46
47import de.duenndns.ssl.MemorizingTrustManager;
48import eu.siacs.conversations.Config;
49import eu.siacs.conversations.R;
50import eu.siacs.conversations.crypto.PgpEngine;
51import eu.siacs.conversations.entities.Account;
52import eu.siacs.conversations.entities.Blockable;
53import eu.siacs.conversations.entities.Bookmark;
54import eu.siacs.conversations.entities.Contact;
55import eu.siacs.conversations.entities.Conversation;
56import eu.siacs.conversations.entities.Downloadable;
57import eu.siacs.conversations.entities.DownloadablePlaceholder;
58import eu.siacs.conversations.entities.Message;
59import eu.siacs.conversations.entities.MucOptions;
60import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
61import eu.siacs.conversations.entities.Presences;
62import eu.siacs.conversations.generator.IqGenerator;
63import eu.siacs.conversations.generator.MessageGenerator;
64import eu.siacs.conversations.generator.PresenceGenerator;
65import eu.siacs.conversations.http.HttpConnectionManager;
66import eu.siacs.conversations.parser.IqParser;
67import eu.siacs.conversations.parser.MessageParser;
68import eu.siacs.conversations.parser.PresenceParser;
69import eu.siacs.conversations.persistance.DatabaseBackend;
70import eu.siacs.conversations.persistance.FileBackend;
71import eu.siacs.conversations.ui.UiCallback;
72import eu.siacs.conversations.utils.CryptoHelper;
73import eu.siacs.conversations.utils.ExceptionHelper;
74import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
75import eu.siacs.conversations.utils.PRNGFixes;
76import eu.siacs.conversations.utils.PhoneHelper;
77import eu.siacs.conversations.utils.Xmlns;
78import eu.siacs.conversations.xml.Element;
79import eu.siacs.conversations.xmpp.OnBindListener;
80import eu.siacs.conversations.xmpp.OnContactStatusChanged;
81import eu.siacs.conversations.xmpp.OnIqPacketReceived;
82import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
83import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
84import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
85import eu.siacs.conversations.xmpp.OnStatusChanged;
86import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
87import eu.siacs.conversations.xmpp.XmppConnection;
88import eu.siacs.conversations.xmpp.forms.Data;
89import eu.siacs.conversations.xmpp.forms.Field;
90import eu.siacs.conversations.xmpp.jid.InvalidJidException;
91import eu.siacs.conversations.xmpp.jid.Jid;
92import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
93import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
94import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
95import eu.siacs.conversations.xmpp.pep.Avatar;
96import eu.siacs.conversations.xmpp.stanzas.IqPacket;
97import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
98import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
99
100public class XmppConnectionService extends Service implements OnPhoneContactsLoadedListener {
101
102 public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
103 public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground";
104 private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
105 private ContentObserver contactObserver = new ContentObserver(null) {
106 @Override
107 public void onChange(boolean selfChange) {
108 super.onChange(selfChange);
109 Intent intent = new Intent(getApplicationContext(),
110 XmppConnectionService.class);
111 intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
112 startService(intent);
113 }
114 };
115 private final IBinder mBinder = new XmppConnectionBinder();
116 private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
117 private final FileObserver fileObserver = new FileObserver(
118 FileBackend.getConversationsImageDirectory()) {
119
120 @Override
121 public void onEvent(int event, String path) {
122 if (event == FileObserver.DELETE) {
123 markFileDeleted(path.split("\\.")[0]);
124 }
125 }
126 };
127 private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
128
129 @Override
130 public void onJinglePacketReceived(Account account, JinglePacket packet) {
131 mJingleConnectionManager.deliverPacket(account, packet);
132 }
133 };
134 private final OnBindListener mOnBindListener = new OnBindListener() {
135
136 @Override
137 public void onBind(final Account account) {
138 account.getRoster().clearPresences();
139 account.pendingConferenceJoins.clear();
140 account.pendingConferenceLeaves.clear();
141 fetchRosterFromServer(account);
142 fetchBookmarks(account);
143 sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
144 connectMultiModeConversations(account);
145 updateConversationUi();
146 }
147 };
148 private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
149
150 @Override
151 public void onMessageAcknowledged(Account account, String uuid) {
152 for (final Conversation conversation : getConversations()) {
153 if (conversation.getAccount() == account) {
154 Message message = conversation.findUnsentMessageWithUuid(uuid);
155 if (message != null) {
156 markMessage(message, Message.STATUS_SEND);
157 if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
158 databaseBackend.updateConversation(conversation);
159 }
160 }
161 }
162 }
163 }
164 };
165 private final IqGenerator mIqGenerator = new IqGenerator(this);
166 public DatabaseBackend databaseBackend;
167 public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
168
169 @Override
170 public void onContactStatusChanged(Contact contact, boolean online) {
171 Conversation conversation = find(getConversations(), contact);
172 if (conversation != null) {
173 if (online && contact.getPresences().size() > 1) {
174 conversation.endOtrIfNeeded();
175 } else {
176 conversation.resetOtrSession();
177 }
178 if (online && (contact.getPresences().size() == 1)) {
179 sendUnsentMessages(conversation);
180 }
181 }
182 }
183 };
184 private FileBackend fileBackend = new FileBackend(this);
185 private MemorizingTrustManager mMemorizingTrustManager;
186 private NotificationService mNotificationService = new NotificationService(
187 this);
188 private OnMessagePacketReceived mMessageParser = new MessageParser(this);
189 private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
190 private IqParser mIqParser = new IqParser(this);
191 private MessageGenerator mMessageGenerator = new MessageGenerator(this);
192 private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
193 private List<Account> accounts;
194 private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
195 this);
196 private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
197 this);
198 private AvatarService mAvatarService = new AvatarService(this);
199 private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
200 private OnConversationUpdate mOnConversationUpdate = null;
201 private Integer convChangedListenerCount = 0;
202 private OnAccountUpdate mOnAccountUpdate = null;
203 private OnStatusChanged statusListener = new OnStatusChanged() {
204
205 @Override
206 public void onStatusChanged(Account account) {
207 XmppConnection connection = account.getXmppConnection();
208 if (mOnAccountUpdate != null) {
209 mOnAccountUpdate.onAccountUpdate();
210 }
211 if (account.getStatus() == Account.State.ONLINE) {
212 for (Conversation conversation : account.pendingConferenceLeaves) {
213 leaveMuc(conversation);
214 }
215 for (Conversation conversation : account.pendingConferenceJoins) {
216 joinMuc(conversation);
217 }
218 mMessageArchiveService.executePendingQueries(account);
219 mJingleConnectionManager.cancelInTransmission();
220 List<Conversation> conversations = getConversations();
221 for (Conversation conversation : conversations) {
222 if (conversation.getAccount() == account) {
223 conversation.startOtrIfNeeded();
224 sendUnsentMessages(conversation);
225 }
226 }
227 if (connection != null && connection.getFeatures().csi()) {
228 if (checkListeners()) {
229 Log.d(Config.LOGTAG, account.getJid().toBareJid()
230 + " sending csi//inactive");
231 connection.sendInactive();
232 } else {
233 Log.d(Config.LOGTAG, account.getJid().toBareJid()
234 + " sending csi//active");
235 connection.sendActive();
236 }
237 }
238 syncDirtyContacts(account);
239 scheduleWakeUpCall(Config.PING_MAX_INTERVAL,account.getUuid().hashCode());
240 } else if (account.getStatus() == Account.State.OFFLINE) {
241 resetSendingToWaiting(account);
242 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
243 int timeToReconnect = mRandom.nextInt(50) + 10;
244 scheduleWakeUpCall(timeToReconnect,account.getUuid().hashCode());
245 }
246 } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
247 databaseBackend.updateAccount(account);
248 reconnectAccount(account, true);
249 } else if ((account.getStatus() != Account.State.CONNECTING)
250 && (account.getStatus() != Account.State.NO_INTERNET)) {
251 if (connection != null) {
252 int next = connection.getTimeToNextAttempt();
253 Log.d(Config.LOGTAG, account.getJid().toBareJid()
254 + ": error connecting account. try again in "
255 + next + "s for the "
256 + (connection.getAttempt() + 1) + " time");
257 scheduleWakeUpCall(next,account.getUuid().hashCode());
258 }
259 }
260 getNotificationService().updateErrorNotification();
261 }
262 };
263 private int accountChangedListenerCount = 0;
264 private OnRosterUpdate mOnRosterUpdate = null;
265 private OnUpdateBlocklist mOnUpdateBlocklist = null;
266 private int updateBlocklistListenerCount = 0;
267 private int rosterChangedListenerCount = 0;
268 private OnMucRosterUpdate mOnMucRosterUpdate = null;
269 private int mucRosterChangedListenerCount = 0;
270 private SecureRandom mRandom;
271 private OpenPgpServiceConnection pgpServiceConnection;
272 private PgpEngine mPgpEngine = null;
273 private WakeLock wakeLock;
274 private PowerManager pm;
275 private LruCache<String, Bitmap> mBitmapCache;
276 private Thread mPhoneContactMergerThread;
277
278 public PgpEngine getPgpEngine() {
279 if (pgpServiceConnection.isBound()) {
280 if (this.mPgpEngine == null) {
281 this.mPgpEngine = new PgpEngine(new OpenPgpApi(
282 getApplicationContext(),
283 pgpServiceConnection.getService()), this);
284 }
285 return mPgpEngine;
286 } else {
287 return null;
288 }
289
290 }
291
292 public FileBackend getFileBackend() {
293 return this.fileBackend;
294 }
295
296 public AvatarService getAvatarService() {
297 return this.mAvatarService;
298 }
299
300 public void attachFileToConversation(final Conversation conversation,
301 final Uri uri,
302 final UiCallback<Message> callback) {
303 final Message message;
304 if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
305 message = new Message(conversation, "",
306 Message.ENCRYPTION_DECRYPTED);
307 } else {
308 message = new Message(conversation, "",
309 conversation.getNextEncryption(forceEncryption()));
310 }
311 message.setCounterpart(conversation.getNextCounterpart());
312 message.setType(Message.TYPE_FILE);
313 message.setStatus(Message.STATUS_OFFERED);
314 String path = getFileBackend().getOriginalPath(uri);
315 if (path!=null) {
316 message.setRelativeFilePath(path);
317 getFileBackend().updateFileParams(message);
318 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
319 getPgpEngine().encrypt(message, callback);
320 } else {
321 callback.success(message);
322 }
323 } else {
324 new Thread(new Runnable() {
325 @Override
326 public void run() {
327 try {
328 getFileBackend().copyFileToPrivateStorage(message, uri);
329 getFileBackend().updateFileParams(message);
330 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
331 getPgpEngine().encrypt(message, callback);
332 } else {
333 callback.success(message);
334 }
335 } catch (FileBackend.FileCopyException e) {
336 callback.error(e.getResId(),message);
337 }
338 }
339 }).start();
340
341 }
342 }
343
344 public void attachImageToConversation(final Conversation conversation,
345 final Uri uri, final UiCallback<Message> callback) {
346 final Message message;
347 if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
348 message = new Message(conversation, "",
349 Message.ENCRYPTION_DECRYPTED);
350 } else {
351 message = new Message(conversation, "",
352 conversation.getNextEncryption(forceEncryption()));
353 }
354 message.setCounterpart(conversation.getNextCounterpart());
355 message.setType(Message.TYPE_IMAGE);
356 message.setStatus(Message.STATUS_OFFERED);
357 new Thread(new Runnable() {
358
359 @Override
360 public void run() {
361 try {
362 getFileBackend().copyImageToPrivateStorage(message, uri);
363 if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
364 getPgpEngine().encrypt(message, callback);
365 } else {
366 callback.success(message);
367 }
368 } catch (final FileBackend.FileCopyException e) {
369 callback.error(e.getResId(), message);
370 }
371 }
372 }).start();
373 }
374
375 public Conversation find(Bookmark bookmark) {
376 return find(bookmark.getAccount(), bookmark.getJid());
377 }
378
379 public Conversation find(final Account account, final Jid jid) {
380 return find(getConversations(), account, jid);
381 }
382
383 @Override
384 public int onStartCommand(Intent intent, int flags, int startId) {
385 final String action = intent == null ? null : intent.getAction();
386 if (action != null) {
387 switch (action) {
388 case ACTION_MERGE_PHONE_CONTACTS:
389 PhoneHelper.loadPhoneContacts(getApplicationContext(), new CopyOnWriteArrayList<Bundle>(), this);
390 return START_STICKY;
391 case Intent.ACTION_SHUTDOWN:
392 logoutAndSave();
393 return START_NOT_STICKY;
394 case ACTION_CLEAR_NOTIFICATION:
395 mNotificationService.clear();
396 break;
397 case ACTION_DISABLE_FOREGROUND:
398 getPreferences().edit().putBoolean("keep_foreground_service",false).commit();
399 toggleForegroundService();
400 break;
401 }
402 }
403 this.wakeLock.acquire();
404
405 for (Account account : accounts) {
406 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
407 if (!hasInternetConnection()) {
408 account.setStatus(Account.State.NO_INTERNET);
409 if (statusListener != null) {
410 statusListener.onStatusChanged(account);
411 }
412 } else {
413 if (account.getStatus() == Account.State.NO_INTERNET) {
414 account.setStatus(Account.State.OFFLINE);
415 if (statusListener != null) {
416 statusListener.onStatusChanged(account);
417 }
418 }
419 if (account.getStatus() == Account.State.ONLINE) {
420 long lastReceived = account.getXmppConnection().getLastPacketReceived();
421 long lastSent = account.getXmppConnection().getLastPingSent();
422 long pingInterval = "ui".equals(action) ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
423 long msToNextPing = (Math.max(lastReceived,lastSent) + pingInterval) - SystemClock.elapsedRealtime();
424 if (lastSent > lastReceived && (lastSent + Config.PING_TIMEOUT * 1000) < SystemClock.elapsedRealtime()) {
425 Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": ping timeout");
426 this.reconnectAccount(account, true);
427 } else if (msToNextPing <= 0) {
428 account.getXmppConnection().sendPing();
429 Log.d(Config.LOGTAG, account.getJid().toBareJid()+" send ping");
430 this.scheduleWakeUpCall(Config.PING_TIMEOUT,account.getUuid().hashCode());
431 } else {
432 this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
433 }
434 } else if (account.getStatus() == Account.State.OFFLINE) {
435 if (account.getXmppConnection() == null) {
436 account.setXmppConnection(this.createConnection(account));
437 }
438 new Thread(account.getXmppConnection()).start();
439 } else if ((account.getStatus() == Account.State.CONNECTING)
440 && ((SystemClock.elapsedRealtime() - account
441 .getXmppConnection().getLastConnect()) / 1000 >= Config.CONNECT_TIMEOUT)) {
442 Log.d(Config.LOGTAG, account.getJid()+ ": time out during connect reconnecting");
443 reconnectAccount(account, true);
444 } else {
445 if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
446 reconnectAccount(account, true);
447 }
448 }
449
450 }
451 if (mOnAccountUpdate != null) {
452 mOnAccountUpdate.onAccountUpdate();
453 }
454 }
455 }
456 /*PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
457 if (!pm.isScreenOn()) {
458 removeStaleListeners();
459 }*/
460 if (wakeLock.isHeld()) {
461 try {
462 wakeLock.release();
463 } catch (final RuntimeException ignored) {
464 }
465 }
466 return START_STICKY;
467 }
468
469 public boolean hasInternetConnection() {
470 ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
471 .getSystemService(Context.CONNECTIVITY_SERVICE);
472 NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
473 return activeNetwork != null && activeNetwork.isConnected();
474 }
475
476 @SuppressLint("TrulyRandom")
477 @Override
478 public void onCreate() {
479 ExceptionHelper.init(getApplicationContext());
480 PRNGFixes.apply();
481 this.mRandom = new SecureRandom();
482 this.mMemorizingTrustManager = new MemorizingTrustManager(
483 getApplicationContext());
484
485 final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
486 final int cacheSize = maxMemory / 8;
487 this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
488 @Override
489 protected int sizeOf(final String key, final Bitmap bitmap) {
490 return bitmap.getByteCount() / 1024;
491 }
492 };
493
494 this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
495 this.accounts = databaseBackend.getAccounts();
496
497 for (final Account account : this.accounts) {
498 account.initOtrEngine(this);
499 this.databaseBackend.readRoster(account.getRoster());
500 }
501 initConversations();
502 PhoneHelper.loadPhoneContacts(getApplicationContext(),new CopyOnWriteArrayList<Bundle>(), this);
503
504 getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
505 this.fileObserver.startWatching();
506 this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain");
507 this.pgpServiceConnection.bindToService();
508
509 this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
510 this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"XmppConnectionService");
511 toggleForegroundService();
512 }
513
514 public void toggleForegroundService() {
515 if (getPreferences().getBoolean("keep_foreground_service",false)) {
516 startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
517 } else {
518 stopForeground(true);
519 }
520 }
521
522 @Override
523 public void onTaskRemoved(final Intent rootIntent) {
524 super.onTaskRemoved(rootIntent);
525 if (!getPreferences().getBoolean("keep_foreground_service",false)) {
526 this.logoutAndSave();
527 }
528 }
529
530 private void logoutAndSave() {
531 for (final Account account : accounts) {
532 databaseBackend.writeRoster(account.getRoster());
533 if (account.getXmppConnection() != null) {
534 disconnect(account, false);
535 }
536 }
537 Context context = getApplicationContext();
538 AlarmManager alarmManager = (AlarmManager) context
539 .getSystemService(Context.ALARM_SERVICE);
540 Intent intent = new Intent(context, EventReceiver.class);
541 alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
542 Log.d(Config.LOGTAG, "good bye");
543 stopSelf();
544 }
545
546 protected void scheduleWakeUpCall(int seconds, int requestCode) {
547 final long timeToWake = SystemClock.elapsedRealtime() + (seconds + 1) * 1000;
548
549 Context context = getApplicationContext();
550 AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
551
552 Intent intent = new Intent(context, EventReceiver.class);
553 intent.setAction("ping");
554 PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
555 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
556 }
557
558 public XmppConnection createConnection(final Account account) {
559 final SharedPreferences sharedPref = getPreferences();
560 account.setResource(sharedPref.getString("resource", "mobile")
561 .toLowerCase(Locale.getDefault()));
562 final XmppConnection connection = new XmppConnection(account, this);
563 connection.setOnMessagePacketReceivedListener(this.mMessageParser);
564 connection.setOnStatusChangedListener(this.statusListener);
565 connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
566 connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
567 connection.setOnJinglePacketReceivedListener(this.jingleListener);
568 connection.setOnBindListener(this.mOnBindListener);
569 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
570 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
571 return connection;
572 }
573
574 public void sendMessage(final Message message) {
575 final Account account = message.getConversation().getAccount();
576 account.deactivateGracePeriod();
577 final Conversation conv = message.getConversation();
578 MessagePacket packet = null;
579 boolean saveInDb = true;
580 boolean send = false;
581 if (account.getStatus() == Account.State.ONLINE
582 && account.getXmppConnection() != null) {
583 if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
584 if (message.getCounterpart() != null) {
585 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
586 if (!conv.hasValidOtrSession()) {
587 conv.startOtrSession(message.getCounterpart().getResourcepart(),true);
588 message.setStatus(Message.STATUS_WAITING);
589 } else if (conv.hasValidOtrSession()
590 && conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
591 mJingleConnectionManager
592 .createNewConnection(message);
593 }
594 } else {
595 mJingleConnectionManager.createNewConnection(message);
596 }
597 } else {
598 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
599 conv.startOtrIfNeeded();
600 }
601 message.setStatus(Message.STATUS_WAITING);
602 }
603 } else {
604 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
605 if (!conv.hasValidOtrSession() && (message.getCounterpart() != null)) {
606 conv.startOtrSession(message.getCounterpart().getResourcepart(), true);
607 message.setStatus(Message.STATUS_WAITING);
608 } else if (conv.hasValidOtrSession()) {
609 if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
610 packet = mMessageGenerator.generateOtrChat(message);
611 send = true;
612 } else {
613 message.setStatus(Message.STATUS_WAITING);
614 conv.startOtrIfNeeded();
615 }
616 } else {
617 message.setStatus(Message.STATUS_WAITING);
618 }
619 } else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
620 message.getConversation().endOtrIfNeeded();
621 message.getConversation().findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
622 @Override
623 public void onMessageFound(Message message) {
624 markMessage(message,Message.STATUS_SEND_FAILED);
625 }
626 });
627 packet = mMessageGenerator.generatePgpChat(message);
628 send = true;
629 } else {
630 message.getConversation().endOtrIfNeeded();
631 message.getConversation().findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
632 @Override
633 public void onMessageFound(Message message) {
634 markMessage(message,Message.STATUS_SEND_FAILED);
635 }
636 });
637 packet = mMessageGenerator.generateChat(message);
638 send = true;
639 }
640 }
641 if (!account.getXmppConnection().getFeatures().sm()
642 && conv.getMode() != Conversation.MODE_MULTI) {
643 message.setStatus(Message.STATUS_SEND);
644 }
645 } else {
646 message.setStatus(Message.STATUS_WAITING);
647 if (message.getType() == Message.TYPE_TEXT) {
648 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
649 String pgpBody = message.getEncryptedBody();
650 String decryptedBody = message.getBody();
651 message.setBody(pgpBody);
652 message.setEncryption(Message.ENCRYPTION_PGP);
653 databaseBackend.createMessage(message);
654 saveInDb = false;
655 message.setBody(decryptedBody);
656 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
657 } else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
658 if (!conv.hasValidOtrSession()
659 && message.getCounterpart() != null) {
660 conv.startOtrSession(message.getCounterpart().getResourcepart(), false);
661 }
662 }
663 }
664
665 }
666 conv.add(message);
667 if (saveInDb) {
668 if (message.getEncryption() == Message.ENCRYPTION_NONE
669 || saveEncryptedMessages()) {
670 databaseBackend.createMessage(message);
671 }
672 }
673 if ((send) && (packet != null)) {
674 sendMessagePacket(account, packet);
675 }
676 updateConversationUi();
677 }
678
679 private void sendUnsentMessages(final Conversation conversation) {
680 conversation.findWaitingMessages(new Conversation.OnMessageFound() {
681
682 @Override
683 public void onMessageFound(Message message) {
684 resendMessage(message);
685 }
686 });
687 }
688
689 private void resendMessage(final Message message) {
690 Account account = message.getConversation().getAccount();
691 MessagePacket packet = null;
692 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
693 Presences presences = message.getConversation().getContact()
694 .getPresences();
695 if (!message.getConversation().hasValidOtrSession()) {
696 if ((message.getCounterpart() != null)
697 && (presences.has(message.getCounterpart().getResourcepart()))) {
698 message.getConversation().startOtrSession(message.getCounterpart().getResourcepart(), true);
699 } else {
700 if (presences.size() == 1) {
701 String presence = presences.asStringArray()[0];
702 message.getConversation().startOtrSession(presence, true);
703 }
704 }
705 } else {
706 if (message.getConversation().getOtrSession()
707 .getSessionStatus() == SessionStatus.ENCRYPTED) {
708 try {
709 message.setCounterpart(Jid.fromSessionID(message.getConversation().getOtrSession().getSessionID()));
710 if (message.getType() == Message.TYPE_TEXT) {
711 packet = mMessageGenerator.generateOtrChat(message,
712 true);
713 } else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
714 mJingleConnectionManager.createNewConnection(message);
715 }
716 } catch (final InvalidJidException ignored) {
717
718 }
719 }
720 }
721 } else if (message.getType() == Message.TYPE_TEXT) {
722 if (message.getEncryption() == Message.ENCRYPTION_NONE) {
723 packet = mMessageGenerator.generateChat(message, true);
724 } else if ((message.getEncryption() == Message.ENCRYPTION_DECRYPTED)
725 || (message.getEncryption() == Message.ENCRYPTION_PGP)) {
726 packet = mMessageGenerator.generatePgpChat(message, true);
727 }
728 } else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
729 Contact contact = message.getConversation().getContact();
730 Presences presences = contact.getPresences();
731 if ((message.getCounterpart() != null)
732 && (presences.has(message.getCounterpart().getResourcepart()))) {
733 markMessage(message, Message.STATUS_OFFERED);
734 mJingleConnectionManager.createNewConnection(message);
735 } else {
736 if (presences.size() == 1) {
737 String presence = presences.asStringArray()[0];
738 try {
739 message.setCounterpart(Jid.fromParts(contact.getJid().getLocalpart(), contact.getJid().getDomainpart(), presence));
740 } catch (InvalidJidException e) {
741 return;
742 }
743 markMessage(message, Message.STATUS_OFFERED);
744 mJingleConnectionManager.createNewConnection(message);
745 }
746 }
747 }
748 if (packet != null) {
749 if (!account.getXmppConnection().getFeatures().sm()
750 && message.getConversation().getMode() != Conversation.MODE_MULTI) {
751 markMessage(message, Message.STATUS_SEND);
752 } else {
753 markMessage(message, Message.STATUS_UNSEND);
754 }
755 sendMessagePacket(account, packet);
756 }
757 }
758
759 public void fetchRosterFromServer(final Account account) {
760 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
761 if (!"".equals(account.getRosterVersion())) {
762 Log.d(Config.LOGTAG, account.getJid().toBareJid()
763 + ": fetching roster version " + account.getRosterVersion());
764 } else {
765 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
766 }
767 iqPacket.query(Xmlns.ROSTER).setAttribute("ver",
768 account.getRosterVersion());
769 account.getXmppConnection().sendIqPacket(iqPacket, mIqParser);
770 }
771
772 public void fetchBookmarks(final Account account) {
773 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
774 final Element query = iqPacket.query("jabber:iq:private");
775 query.addChild("storage", "storage:bookmarks");
776 final OnIqPacketReceived callback = new OnIqPacketReceived() {
777
778 @Override
779 public void onIqPacketReceived(final Account account, final IqPacket packet) {
780 final Element query = packet.query();
781 final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
782 final Element storage = query.findChild("storage",
783 "storage:bookmarks");
784 if (storage != null) {
785 for (final Element item : storage.getChildren()) {
786 if (item.getName().equals("conference")) {
787 final Bookmark bookmark = Bookmark.parse(item, account);
788 bookmarks.add(bookmark);
789 Conversation conversation = find(bookmark);
790 if (conversation != null) {
791 conversation.setBookmark(bookmark);
792 } else if (bookmark.autojoin() && bookmark.getJid() != null) {
793 conversation = findOrCreateConversation(
794 account, bookmark.getJid(), true);
795 conversation.setBookmark(bookmark);
796 joinMuc(conversation);
797 }
798 }
799 }
800 }
801 account.setBookmarks(bookmarks);
802 }
803 };
804 sendIqPacket(account, iqPacket, callback);
805 }
806
807 public void pushBookmarks(Account account) {
808 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
809 Element query = iqPacket.query("jabber:iq:private");
810 Element storage = query.addChild("storage", "storage:bookmarks");
811 for (Bookmark bookmark : account.getBookmarks()) {
812 storage.addChild(bookmark);
813 }
814 sendIqPacket(account, iqPacket, null);
815 }
816
817 public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
818 if (mPhoneContactMergerThread != null) {
819 mPhoneContactMergerThread.interrupt();
820 }
821 mPhoneContactMergerThread = new Thread(new Runnable() {
822 @Override
823 public void run() {
824 Log.d(Config.LOGTAG,"start merging phone contacts with roster");
825 for (Account account : accounts) {
826 account.getRoster().clearSystemAccounts();
827 for (Bundle phoneContact : phoneContacts) {
828 if (Thread.interrupted()) {
829 Log.d(Config.LOGTAG,"interrupted merging phone contacts");
830 return;
831 }
832 Jid jid;
833 try {
834 jid = Jid.fromString(phoneContact.getString("jid"));
835 } catch (final InvalidJidException e) {
836 continue;
837 }
838 final Contact contact = account.getRoster().getContact(jid);
839 String systemAccount = phoneContact.getInt("phoneid")
840 + "#"
841 + phoneContact.getString("lookup");
842 contact.setSystemAccount(systemAccount);
843 contact.setPhotoUri(phoneContact.getString("photouri"));
844 getAvatarService().clear(contact);
845 contact.setSystemName(phoneContact.getString("displayname"));
846 }
847 }
848 Log.d(Config.LOGTAG,"finished merging phone contacts");
849 updateAccountUi();
850 }
851 });
852 mPhoneContactMergerThread.start();
853 }
854
855 private void initConversations() {
856 synchronized (this.conversations) {
857 final Map<String, Account> accountLookupTable = new Hashtable<>();
858 for (Account account : this.accounts) {
859 accountLookupTable.put(account.getUuid(), account);
860 }
861 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
862 for (Conversation conversation : this.conversations) {
863 Account account = accountLookupTable.get(conversation.getAccountUuid());
864 conversation.setAccount(account);
865 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
866 checkDeletedFiles(conversation);
867 }
868 }
869 }
870
871 public List<Conversation> getConversations() {
872 return this.conversations;
873 }
874
875 private void checkDeletedFiles(Conversation conversation) {
876 conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
877
878 @Override
879 public void onMessageFound(Message message) {
880 if (!getFileBackend().isFileAvailable(message)) {
881 message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
882 }
883 }
884 });
885 }
886
887 private void markFileDeleted(String uuid) {
888 for (Conversation conversation : getConversations()) {
889 Message message = conversation.findMessageWithFileAndUuid(uuid);
890 if (message != null) {
891 if (!getFileBackend().isFileAvailable(message)) {
892 message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
893 updateConversationUi();
894 }
895 return;
896 }
897 }
898 }
899
900 public void populateWithOrderedConversations(final List<Conversation> list) {
901 populateWithOrderedConversations(list, true);
902 }
903
904 public void populateWithOrderedConversations(final List<Conversation> list, boolean includeConferences) {
905 list.clear();
906 if (includeConferences) {
907 list.addAll(getConversations());
908 } else {
909 for (Conversation conversation : getConversations()) {
910 if (conversation.getMode() == Conversation.MODE_SINGLE) {
911 list.add(conversation);
912 }
913 }
914 }
915 Collections.sort(list, new Comparator<Conversation>() {
916 @Override
917 public int compare(Conversation lhs, Conversation rhs) {
918 Message left = lhs.getLatestMessage();
919 Message right = rhs.getLatestMessage();
920 if (left.getTimeSent() > right.getTimeSent()) {
921 return -1;
922 } else if (left.getTimeSent() < right.getTimeSent()) {
923 return 1;
924 } else {
925 return 0;
926 }
927 }
928 });
929 }
930
931 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
932 Log.d(Config.LOGTAG,"load more messages for "+conversation.getName() + " prior to "+MessageGenerator.getTimestamp(timestamp));
933 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
934 return;
935 }
936 new Thread(new Runnable() {
937 @Override
938 public void run() {
939 final Account account = conversation.getAccount();
940 List<Message> messages = databaseBackend.getMessages(conversation, 50,timestamp);
941 if (messages.size() > 0) {
942 conversation.addAll(0, messages);
943 checkDeletedFiles(conversation);
944 callback.onMoreMessagesLoaded(messages.size(), conversation);
945 } else if (conversation.hasMessagesLeftOnServer()
946 && account.isOnlineAndConnected()
947 && account.getXmppConnection().getFeatures().mam()) {
948 MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1);
949 if (query != null) {
950 query.setCallback(callback);
951 }
952 callback.informUser(R.string.fetching_history_from_server);
953 }
954 }
955 }).start();
956 }
957
958 public List<Account> getAccounts() {
959 return this.accounts;
960 }
961
962 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
963 for (final Conversation conversation : haystack) {
964 if (conversation.getContact() == contact) {
965 return conversation;
966 }
967 }
968 return null;
969 }
970
971 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
972 if (jid == null) {
973 return null;
974 }
975 for (final Conversation conversation : haystack) {
976 if ((account == null || conversation.getAccount() == account)
977 && (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
978 return conversation;
979 }
980 }
981 return null;
982 }
983
984 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
985 return this.findOrCreateConversation(account, jid, muc, null);
986 }
987
988 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
989 synchronized (this.conversations) {
990 Conversation conversation = find(account, jid);
991 if (conversation != null) {
992 return conversation;
993 }
994 conversation = databaseBackend.findConversation(account, jid);
995 if (conversation != null) {
996 conversation.setStatus(Conversation.STATUS_AVAILABLE);
997 conversation.setAccount(account);
998 if (muc) {
999 conversation.setMode(Conversation.MODE_MULTI);
1000 conversation.setContactJid(jid);
1001 } else {
1002 conversation.setMode(Conversation.MODE_SINGLE);
1003 conversation.setContactJid(jid.toBareJid());
1004 }
1005 conversation.setNextEncryption(-1);
1006 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1007 this.databaseBackend.updateConversation(conversation);
1008 } else {
1009 String conversationName;
1010 Contact contact = account.getRoster().getContact(jid);
1011 if (contact != null) {
1012 conversationName = contact.getDisplayName();
1013 } else {
1014 conversationName = jid.getLocalpart();
1015 }
1016 if (muc) {
1017 conversation = new Conversation(conversationName, account, jid,
1018 Conversation.MODE_MULTI);
1019 } else {
1020 conversation = new Conversation(conversationName, account, jid.toBareJid(),
1021 Conversation.MODE_SINGLE);
1022 }
1023 this.databaseBackend.createConversation(conversation);
1024 }
1025 if (account.getXmppConnection() != null
1026 && account.getXmppConnection().getFeatures().mam()
1027 && !muc) {
1028 if (query == null) {
1029 this.mMessageArchiveService.query(conversation);
1030 } else {
1031 if (query.getConversation() == null) {
1032 this.mMessageArchiveService.query(conversation, query.getStart());
1033 }
1034 }
1035 }
1036 checkDeletedFiles(conversation);
1037 this.conversations.add(conversation);
1038 updateConversationUi();
1039 return conversation;
1040 }
1041 }
1042
1043 public void archiveConversation(Conversation conversation) {
1044 conversation.setStatus(Conversation.STATUS_ARCHIVED);
1045 conversation.setNextEncryption(-1);
1046 synchronized (this.conversations) {
1047 if (conversation.getMode() == Conversation.MODE_MULTI) {
1048 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1049 Bookmark bookmark = conversation.getBookmark();
1050 if (bookmark != null && bookmark.autojoin()) {
1051 bookmark.setAutojoin(false);
1052 pushBookmarks(bookmark.getAccount());
1053 }
1054 }
1055 leaveMuc(conversation);
1056 } else {
1057 conversation.endOtrIfNeeded();
1058 }
1059 this.databaseBackend.updateConversation(conversation);
1060 this.conversations.remove(conversation);
1061 updateConversationUi();
1062 }
1063 }
1064
1065 public void createAccount(final Account account) {
1066 account.initOtrEngine(this);
1067 databaseBackend.createAccount(account);
1068 this.accounts.add(account);
1069 this.reconnectAccount(account, false);
1070 updateAccountUi();
1071 }
1072
1073 public void updateAccount(final Account account) {
1074 this.statusListener.onStatusChanged(account);
1075 databaseBackend.updateAccount(account);
1076 reconnectAccount(account, false);
1077 updateAccountUi();
1078 getNotificationService().updateErrorNotification();
1079 }
1080
1081 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1082 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1083 sendIqPacket(account, iq, new OnIqPacketReceived() {
1084 @Override
1085 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1086 if (packet.getType() == IqPacket.TYPE.RESULT) {
1087 account.setPassword(newPassword);
1088 databaseBackend.updateAccount(account);
1089 callback.onPasswordChangeSucceeded();
1090 } else {
1091 callback.onPasswordChangeFailed();
1092 }
1093 }
1094 });
1095 }
1096
1097 public void deleteAccount(final Account account) {
1098 synchronized (this.conversations) {
1099 for (final Conversation conversation : conversations) {
1100 if (conversation.getAccount() == account) {
1101 if (conversation.getMode() == Conversation.MODE_MULTI) {
1102 leaveMuc(conversation);
1103 } else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1104 conversation.endOtrIfNeeded();
1105 }
1106 conversations.remove(conversation);
1107 }
1108 }
1109 if (account.getXmppConnection() != null) {
1110 this.disconnect(account, true);
1111 }
1112 databaseBackend.deleteAccount(account);
1113 this.accounts.remove(account);
1114 updateAccountUi();
1115 getNotificationService().updateErrorNotification();
1116 }
1117 }
1118
1119 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1120 synchronized (this) {
1121 if (checkListeners()) {
1122 switchToForeground();
1123 }
1124 this.mOnConversationUpdate = listener;
1125 this.mNotificationService.setIsInForeground(true);
1126 if (this.convChangedListenerCount < 2) {
1127 this.convChangedListenerCount++;
1128 }
1129 }
1130 }
1131
1132 public void removeOnConversationListChangedListener() {
1133 synchronized (this) {
1134 this.convChangedListenerCount--;
1135 if (this.convChangedListenerCount <= 0) {
1136 this.convChangedListenerCount = 0;
1137 this.mOnConversationUpdate = null;
1138 this.mNotificationService.setIsInForeground(false);
1139 if (checkListeners()) {
1140 switchToBackground();
1141 }
1142 }
1143 }
1144 }
1145
1146 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1147 synchronized (this) {
1148 if (checkListeners()) {
1149 switchToForeground();
1150 }
1151 this.mOnAccountUpdate = listener;
1152 if (this.accountChangedListenerCount < 2) {
1153 this.accountChangedListenerCount++;
1154 }
1155 }
1156 }
1157
1158 public void removeOnAccountListChangedListener() {
1159 synchronized (this) {
1160 this.accountChangedListenerCount--;
1161 if (this.accountChangedListenerCount <= 0) {
1162 this.mOnAccountUpdate = null;
1163 this.accountChangedListenerCount = 0;
1164 if (checkListeners()) {
1165 switchToBackground();
1166 }
1167 }
1168 }
1169 }
1170
1171 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1172 synchronized (this) {
1173 if (checkListeners()) {
1174 switchToForeground();
1175 }
1176 this.mOnRosterUpdate = listener;
1177 if (this.rosterChangedListenerCount < 2) {
1178 this.rosterChangedListenerCount++;
1179 }
1180 }
1181 }
1182
1183 public void removeOnRosterUpdateListener() {
1184 synchronized (this) {
1185 this.rosterChangedListenerCount--;
1186 if (this.rosterChangedListenerCount <= 0) {
1187 this.rosterChangedListenerCount = 0;
1188 this.mOnRosterUpdate = null;
1189 if (checkListeners()) {
1190 switchToBackground();
1191 }
1192 }
1193 }
1194 }
1195
1196 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1197 synchronized (this) {
1198 if (checkListeners()) {
1199 switchToForeground();
1200 }
1201 this.mOnUpdateBlocklist = listener;
1202 if (this.updateBlocklistListenerCount < 2) {
1203 this.updateBlocklistListenerCount++;
1204 }
1205 }
1206 }
1207
1208 public void removeOnUpdateBlocklistListener() {
1209 synchronized (this) {
1210 this.updateBlocklistListenerCount--;
1211 if (this.updateBlocklistListenerCount <= 0) {
1212 this.updateBlocklistListenerCount = 0;
1213 this.mOnUpdateBlocklist = null;
1214 if (checkListeners()) {
1215 switchToBackground();
1216 }
1217 }
1218 }
1219 }
1220
1221 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1222 synchronized (this) {
1223 if (checkListeners()) {
1224 switchToForeground();
1225 }
1226 this.mOnMucRosterUpdate = listener;
1227 if (this.mucRosterChangedListenerCount < 2) {
1228 this.mucRosterChangedListenerCount++;
1229 }
1230 }
1231 }
1232
1233 public void removeOnMucRosterUpdateListener() {
1234 synchronized (this) {
1235 this.mucRosterChangedListenerCount--;
1236 if (this.mucRosterChangedListenerCount <= 0) {
1237 this.mucRosterChangedListenerCount = 0;
1238 this.mOnMucRosterUpdate = null;
1239 if (checkListeners()) {
1240 switchToBackground();
1241 }
1242 }
1243 }
1244 }
1245
1246 private boolean checkListeners() {
1247 return (this.mOnAccountUpdate == null
1248 && this.mOnConversationUpdate == null
1249 && this.mOnRosterUpdate == null
1250 && this.mOnUpdateBlocklist == null);
1251 }
1252
1253 private void switchToForeground() {
1254 for (Account account : getAccounts()) {
1255 if (account.getStatus() == Account.State.ONLINE) {
1256 XmppConnection connection = account.getXmppConnection();
1257 if (connection != null && connection.getFeatures().csi()) {
1258 connection.sendActive();
1259 }
1260 }
1261 }
1262 Log.d(Config.LOGTAG, "app switched into foreground");
1263 }
1264
1265 private void switchToBackground() {
1266 for (Account account : getAccounts()) {
1267 if (account.getStatus() == Account.State.ONLINE) {
1268 XmppConnection connection = account.getXmppConnection();
1269 if (connection != null && connection.getFeatures().csi()) {
1270 connection.sendInactive();
1271 }
1272 }
1273 }
1274 this.mNotificationService.setIsInForeground(false);
1275 Log.d(Config.LOGTAG, "app switched into background");
1276 }
1277
1278 private void connectMultiModeConversations(Account account) {
1279 List<Conversation> conversations = getConversations();
1280 for (Conversation conversation : conversations) {
1281 if ((conversation.getMode() == Conversation.MODE_MULTI)
1282 && (conversation.getAccount() == account)) {
1283 conversation.resetMucOptions();
1284 joinMuc(conversation);
1285 }
1286 }
1287 }
1288
1289 public void joinMuc(Conversation conversation) {
1290 Account account = conversation.getAccount();
1291 account.pendingConferenceJoins.remove(conversation);
1292 account.pendingConferenceLeaves.remove(conversation);
1293 if (account.getStatus() == Account.State.ONLINE) {
1294 final String nick = conversation.getMucOptions().getProposedNick();
1295 final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1296 if (joinJid == null) {
1297 return; //safety net
1298 }
1299 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1300 PresencePacket packet = new PresencePacket();
1301 packet.setFrom(conversation.getAccount().getJid());
1302 packet.setTo(joinJid);
1303 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1304 if (conversation.getMucOptions().getPassword() != null) {
1305 x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1306 }
1307 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1308 String sig = account.getPgpSignature();
1309 if (sig != null) {
1310 packet.addChild("status").setContent("online");
1311 packet.addChild("x", "jabber:x:signed").setContent(sig);
1312 }
1313 sendPresencePacket(account, packet);
1314 fetchConferenceConfiguration(conversation);
1315 if (!joinJid.equals(conversation.getJid())) {
1316 conversation.setContactJid(joinJid);
1317 databaseBackend.updateConversation(conversation);
1318 }
1319 conversation.setHasMessagesLeftOnServer(false);
1320 } else {
1321 account.pendingConferenceJoins.add(conversation);
1322 }
1323 }
1324
1325 public void providePasswordForMuc(Conversation conversation, String password) {
1326 if (conversation.getMode() == Conversation.MODE_MULTI) {
1327 conversation.getMucOptions().setPassword(password);
1328 if (conversation.getBookmark() != null) {
1329 conversation.getBookmark().setAutojoin(true);
1330 pushBookmarks(conversation.getAccount());
1331 }
1332 databaseBackend.updateConversation(conversation);
1333 joinMuc(conversation);
1334 }
1335 }
1336
1337 public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1338 final MucOptions options = conversation.getMucOptions();
1339 final Jid joinJid = options.createJoinJid(nick);
1340 if (options.online()) {
1341 Account account = conversation.getAccount();
1342 options.setOnRenameListener(new OnRenameListener() {
1343
1344 @Override
1345 public void onSuccess() {
1346 conversation.setContactJid(joinJid);
1347 databaseBackend.updateConversation(conversation);
1348 Bookmark bookmark = conversation.getBookmark();
1349 if (bookmark != null) {
1350 bookmark.setNick(nick);
1351 pushBookmarks(bookmark.getAccount());
1352 }
1353 callback.success(conversation);
1354 }
1355
1356 @Override
1357 public void onFailure() {
1358 callback.error(R.string.nick_in_use, conversation);
1359 }
1360 });
1361
1362 PresencePacket packet = new PresencePacket();
1363 packet.setTo(joinJid);
1364 packet.setFrom(conversation.getAccount().getJid());
1365
1366 String sig = account.getPgpSignature();
1367 if (sig != null) {
1368 packet.addChild("status").setContent("online");
1369 packet.addChild("x", "jabber:x:signed").setContent(sig);
1370 }
1371 sendPresencePacket(account, packet);
1372 } else {
1373 conversation.setContactJid(joinJid);
1374 databaseBackend.updateConversation(conversation);
1375 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1376 Bookmark bookmark = conversation.getBookmark();
1377 if (bookmark != null) {
1378 bookmark.setNick(nick);
1379 pushBookmarks(bookmark.getAccount());
1380 }
1381 joinMuc(conversation);
1382 }
1383 }
1384 }
1385
1386 public void leaveMuc(Conversation conversation) {
1387 Account account = conversation.getAccount();
1388 account.pendingConferenceJoins.remove(conversation);
1389 account.pendingConferenceLeaves.remove(conversation);
1390 if (account.getStatus() == Account.State.ONLINE) {
1391 PresencePacket packet = new PresencePacket();
1392 packet.setTo(conversation.getJid());
1393 packet.setFrom(conversation.getAccount().getJid());
1394 packet.setAttribute("type", "unavailable");
1395 sendPresencePacket(conversation.getAccount(), packet);
1396 conversation.getMucOptions().setOffline();
1397 conversation.deregisterWithBookmark();
1398 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1399 + ": leaving muc " + conversation.getJid());
1400 } else {
1401 account.pendingConferenceLeaves.add(conversation);
1402 }
1403 }
1404
1405 private String findConferenceServer(final Account account) {
1406 String server;
1407 if (account.getXmppConnection() != null) {
1408 server = account.getXmppConnection().getMucServer();
1409 if (server != null) {
1410 return server;
1411 }
1412 }
1413 for (Account other : getAccounts()) {
1414 if (other != account && other.getXmppConnection() != null) {
1415 server = other.getXmppConnection().getMucServer();
1416 if (server != null) {
1417 return server;
1418 }
1419 }
1420 }
1421 return null;
1422 }
1423
1424 public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1425 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1426 if (account.getStatus() == Account.State.ONLINE) {
1427 try {
1428 String server = findConferenceServer(account);
1429 if (server == null) {
1430 if (callback != null) {
1431 callback.error(R.string.no_conference_server_found, null);
1432 }
1433 return;
1434 }
1435 String name = new BigInteger(75, getRNG()).toString(32);
1436 Jid jid = Jid.fromParts(name, server, null);
1437 final Conversation conversation = findOrCreateConversation(account, jid, true);
1438 joinMuc(conversation);
1439 Bundle options = new Bundle();
1440 options.putString("muc#roomconfig_persistentroom", "1");
1441 options.putString("muc#roomconfig_membersonly", "1");
1442 options.putString("muc#roomconfig_publicroom", "0");
1443 options.putString("muc#roomconfig_whois", "anyone");
1444 pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1445 @Override
1446 public void onPushSucceeded() {
1447 for (Jid invite : jids) {
1448 invite(conversation, invite);
1449 }
1450 if (callback != null) {
1451 callback.success(conversation);
1452 }
1453 }
1454
1455 @Override
1456 public void onPushFailed() {
1457 if (callback != null) {
1458 callback.error(R.string.conference_creation_failed, conversation);
1459 }
1460 }
1461 });
1462
1463 } catch (InvalidJidException e) {
1464 if (callback != null) {
1465 callback.error(R.string.conference_creation_failed, null);
1466 }
1467 }
1468 } else {
1469 if (callback != null) {
1470 callback.error(R.string.not_connected_try_again, null);
1471 }
1472 }
1473 }
1474
1475 public void fetchConferenceConfiguration(final Conversation conversation) {
1476 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1477 request.setTo(conversation.getJid().toBareJid());
1478 request.query("http://jabber.org/protocol/disco#info");
1479 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1480 @Override
1481 public void onIqPacketReceived(Account account, IqPacket packet) {
1482 if (packet.getType() != IqPacket.TYPE.ERROR) {
1483 ArrayList<String> features = new ArrayList<>();
1484 for (Element child : packet.query().getChildren()) {
1485 if (child != null && child.getName().equals("feature")) {
1486 String var = child.getAttribute("var");
1487 if (var != null) {
1488 features.add(var);
1489 }
1490 }
1491 }
1492 conversation.getMucOptions().updateFeatures(features);
1493 updateConversationUi();
1494 }
1495 }
1496 });
1497 }
1498
1499 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1500 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1501 request.setTo(conversation.getJid().toBareJid());
1502 request.query("http://jabber.org/protocol/muc#owner");
1503 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1504 @Override
1505 public void onIqPacketReceived(Account account, IqPacket packet) {
1506 if (packet.getType() != IqPacket.TYPE.ERROR) {
1507 Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1508 for (Field field : data.getFields()) {
1509 if (options.containsKey(field.getName())) {
1510 field.setValue(options.getString(field.getName()));
1511 }
1512 }
1513 data.submit();
1514 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1515 set.setTo(conversation.getJid().toBareJid());
1516 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1517 sendIqPacket(account, set, new OnIqPacketReceived() {
1518 @Override
1519 public void onIqPacketReceived(Account account, IqPacket packet) {
1520 if (packet.getType() == IqPacket.TYPE.RESULT) {
1521 if (callback != null) {
1522 callback.onPushSucceeded();
1523 }
1524 } else {
1525 if (callback != null) {
1526 callback.onPushFailed();
1527 }
1528 }
1529 }
1530 });
1531 } else {
1532 if (callback != null) {
1533 callback.onPushFailed();
1534 }
1535 }
1536 }
1537 });
1538 }
1539
1540 public void pushSubjectToConference(final Conversation conference, final String subject) {
1541 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1542 this.sendMessagePacket(conference.getAccount(), packet);
1543 final MucOptions mucOptions = conference.getMucOptions();
1544 final MucOptions.User self = mucOptions.getSelf();
1545 if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1546 Bundle options = new Bundle();
1547 options.putString("muc#roomconfig_persistentroom", "1");
1548 this.pushConferenceConfiguration(conference, options, null);
1549 }
1550 }
1551
1552 public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1553 final Jid jid = user.toBareJid();
1554 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1555 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1556 @Override
1557 public void onIqPacketReceived(Account account, IqPacket packet) {
1558 if (packet.getType() == IqPacket.TYPE.RESULT) {
1559 callback.onAffiliationChangedSuccessful(jid);
1560 } else {
1561 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1562 }
1563 }
1564 });
1565 }
1566
1567 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1568 List<Jid> jids = new ArrayList<>();
1569 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1570 if (user.getAffiliation() == before) {
1571 jids.add(user.getJid());
1572 }
1573 }
1574 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1575 sendIqPacket(conference.getAccount(), request, null);
1576 }
1577
1578 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1579 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1580 Log.d(Config.LOGTAG, request.toString());
1581 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1582 @Override
1583 public void onIqPacketReceived(Account account, IqPacket packet) {
1584 Log.d(Config.LOGTAG, packet.toString());
1585 if (packet.getType() == IqPacket.TYPE.RESULT) {
1586 callback.onRoleChangedSuccessful(nick);
1587 } else {
1588 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1589 }
1590 }
1591 });
1592 }
1593
1594 public void disconnect(Account account, boolean force) {
1595 if ((account.getStatus() == Account.State.ONLINE)
1596 || (account.getStatus() == Account.State.DISABLED)) {
1597 if (!force) {
1598 List<Conversation> conversations = getConversations();
1599 for (Conversation conversation : conversations) {
1600 if (conversation.getAccount() == account) {
1601 if (conversation.getMode() == Conversation.MODE_MULTI) {
1602 leaveMuc(conversation);
1603 } else {
1604 if (conversation.endOtrIfNeeded()) {
1605 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1606 + ": ended otr session with "
1607 + conversation.getJid());
1608 }
1609 }
1610 }
1611 }
1612 }
1613 account.getXmppConnection().disconnect(force);
1614 }
1615 }
1616
1617 @Override
1618 public IBinder onBind(Intent intent) {
1619 return mBinder;
1620 }
1621
1622 public void updateMessage(Message message) {
1623 databaseBackend.updateMessage(message);
1624 updateConversationUi();
1625 }
1626
1627 protected void syncDirtyContacts(Account account) {
1628 for (Contact contact : account.getRoster().getContacts()) {
1629 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1630 pushContactToServer(contact);
1631 }
1632 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1633 deleteContactOnServer(contact);
1634 }
1635 }
1636 }
1637
1638 public void createContact(Contact contact) {
1639 SharedPreferences sharedPref = getPreferences();
1640 boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1641 if (autoGrant) {
1642 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1643 contact.setOption(Contact.Options.ASKING);
1644 }
1645 pushContactToServer(contact);
1646 }
1647
1648 public void onOtrSessionEstablished(Conversation conversation) {
1649 final Account account = conversation.getAccount();
1650 final Session otrSession = conversation.getOtrSession();
1651 Log.d(Config.LOGTAG,
1652 account.getJid().toBareJid() + " otr session established with "
1653 + conversation.getJid() + "/"
1654 + otrSession.getSessionID().getUserID());
1655 conversation.findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
1656
1657 @Override
1658 public void onMessageFound(Message message) {
1659 SessionID id = otrSession.getSessionID();
1660 try {
1661 message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1662 } catch (InvalidJidException e) {
1663 return;
1664 }
1665 if (message.getType() == Message.TYPE_TEXT) {
1666 MessagePacket outPacket = mMessageGenerator.generateOtrChat(message, true);
1667 if (outPacket != null) {
1668 message.setStatus(Message.STATUS_SEND);
1669 databaseBackend.updateMessage(message);
1670 sendMessagePacket(account, outPacket);
1671 }
1672 } else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
1673 mJingleConnectionManager.createNewConnection(message);
1674 }
1675 updateConversationUi();
1676 }
1677 });
1678 }
1679
1680 public boolean renewSymmetricKey(Conversation conversation) {
1681 Account account = conversation.getAccount();
1682 byte[] symmetricKey = new byte[32];
1683 this.mRandom.nextBytes(symmetricKey);
1684 Session otrSession = conversation.getOtrSession();
1685 if (otrSession != null) {
1686 MessagePacket packet = new MessagePacket();
1687 packet.setType(MessagePacket.TYPE_CHAT);
1688 packet.setFrom(account.getJid());
1689 packet.addChild("private", "urn:xmpp:carbons:2");
1690 packet.addChild("no-copy", "urn:xmpp:hints");
1691 packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1692 + otrSession.getSessionID().getUserID());
1693 try {
1694 packet.setBody(otrSession
1695 .transformSending(CryptoHelper.FILETRANSFER
1696 + CryptoHelper.bytesToHex(symmetricKey))[0]);
1697 sendMessagePacket(account, packet);
1698 conversation.setSymmetricKey(symmetricKey);
1699 return true;
1700 } catch (OtrException e) {
1701 return false;
1702 }
1703 }
1704 return false;
1705 }
1706
1707 public void pushContactToServer(final Contact contact) {
1708 contact.resetOption(Contact.Options.DIRTY_DELETE);
1709 contact.setOption(Contact.Options.DIRTY_PUSH);
1710 final Account account = contact.getAccount();
1711 if (account.getStatus() == Account.State.ONLINE) {
1712 final boolean ask = contact.getOption(Contact.Options.ASKING);
1713 final boolean sendUpdates = contact
1714 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1715 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1716 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1717 iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1718 account.getXmppConnection().sendIqPacket(iq, null);
1719 if (sendUpdates) {
1720 sendPresencePacket(account,
1721 mPresenceGenerator.sendPresenceUpdatesTo(contact));
1722 }
1723 if (ask) {
1724 sendPresencePacket(account,
1725 mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1726 }
1727 }
1728 }
1729
1730 public void publishAvatar(final Account account,
1731 final Uri image,
1732 final UiCallback<Avatar> callback) {
1733 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1734 final int size = Config.AVATAR_SIZE;
1735 final Avatar avatar = getFileBackend()
1736 .getPepAvatar(image, size, format);
1737 if (avatar != null) {
1738 avatar.height = size;
1739 avatar.width = size;
1740 if (format.equals(Bitmap.CompressFormat.WEBP)) {
1741 avatar.type = "image/webp";
1742 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1743 avatar.type = "image/jpeg";
1744 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1745 avatar.type = "image/png";
1746 }
1747 if (!getFileBackend().save(avatar)) {
1748 callback.error(R.string.error_saving_avatar, avatar);
1749 return;
1750 }
1751 final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1752 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1753
1754 @Override
1755 public void onIqPacketReceived(Account account, IqPacket result) {
1756 if (result.getType() == IqPacket.TYPE.RESULT) {
1757 final IqPacket packet = XmppConnectionService.this.mIqGenerator
1758 .publishAvatarMetadata(avatar);
1759 sendIqPacket(account, packet, new OnIqPacketReceived() {
1760
1761 @Override
1762 public void onIqPacketReceived(Account account,
1763 IqPacket result) {
1764 if (result.getType() == IqPacket.TYPE.RESULT) {
1765 if (account.setAvatar(avatar.getFilename())) {
1766 databaseBackend.updateAccount(account);
1767 }
1768 callback.success(avatar);
1769 } else {
1770 callback.error(
1771 R.string.error_publish_avatar_server_reject,
1772 avatar);
1773 }
1774 }
1775 });
1776 } else {
1777 callback.error(
1778 R.string.error_publish_avatar_server_reject,
1779 avatar);
1780 }
1781 }
1782 });
1783 } else {
1784 callback.error(R.string.error_publish_avatar_converting, null);
1785 }
1786 }
1787
1788 public void fetchAvatar(Account account, Avatar avatar) {
1789 fetchAvatar(account, avatar, null);
1790 }
1791
1792 public void fetchAvatar(Account account, final Avatar avatar,
1793 final UiCallback<Avatar> callback) {
1794 IqPacket packet = this.mIqGenerator.retrieveAvatar(avatar);
1795 sendIqPacket(account, packet, new OnIqPacketReceived() {
1796
1797 @Override
1798 public void onIqPacketReceived(Account account, IqPacket result) {
1799 final String ERROR = account.getJid().toBareJid()
1800 + ": fetching avatar for " + avatar.owner + " failed ";
1801 if (result.getType() == IqPacket.TYPE.RESULT) {
1802 avatar.image = mIqParser.avatarData(result);
1803 if (avatar.image != null) {
1804 if (getFileBackend().save(avatar)) {
1805 if (account.getJid().toBareJid().equals(avatar.owner)) {
1806 if (account.setAvatar(avatar.getFilename())) {
1807 databaseBackend.updateAccount(account);
1808 }
1809 getAvatarService().clear(account);
1810 updateConversationUi();
1811 updateAccountUi();
1812 } else {
1813 Contact contact = account.getRoster()
1814 .getContact(avatar.owner);
1815 contact.setAvatar(avatar.getFilename());
1816 getAvatarService().clear(contact);
1817 updateConversationUi();
1818 updateRosterUi();
1819 }
1820 if (callback != null) {
1821 callback.success(avatar);
1822 }
1823 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1824 + ": succesfully fetched avatar for "
1825 + avatar.owner);
1826 return;
1827 }
1828 } else {
1829
1830 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
1831 }
1832 } else {
1833 Element error = result.findChild("error");
1834 if (error == null) {
1835 Log.d(Config.LOGTAG, ERROR + "(server error)");
1836 } else {
1837 Log.d(Config.LOGTAG, ERROR + error.toString());
1838 }
1839 }
1840 if (callback != null) {
1841 callback.error(0, null);
1842 }
1843
1844 }
1845 });
1846 }
1847
1848 public void checkForAvatar(Account account,
1849 final UiCallback<Avatar> callback) {
1850 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
1851 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1852
1853 @Override
1854 public void onIqPacketReceived(Account account, IqPacket packet) {
1855 if (packet.getType() == IqPacket.TYPE.RESULT) {
1856 Element pubsub = packet.findChild("pubsub",
1857 "http://jabber.org/protocol/pubsub");
1858 if (pubsub != null) {
1859 Element items = pubsub.findChild("items");
1860 if (items != null) {
1861 Avatar avatar = Avatar.parseMetadata(items);
1862 if (avatar != null) {
1863 avatar.owner = account.getJid().toBareJid();
1864 if (fileBackend.isAvatarCached(avatar)) {
1865 if (account.setAvatar(avatar.getFilename())) {
1866 databaseBackend.updateAccount(account);
1867 }
1868 getAvatarService().clear(account);
1869 callback.success(avatar);
1870 } else {
1871 fetchAvatar(account, avatar, callback);
1872 }
1873 return;
1874 }
1875 }
1876 }
1877 }
1878 callback.error(0, null);
1879 }
1880 });
1881 }
1882
1883 public void deleteContactOnServer(Contact contact) {
1884 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
1885 contact.resetOption(Contact.Options.DIRTY_PUSH);
1886 contact.setOption(Contact.Options.DIRTY_DELETE);
1887 Account account = contact.getAccount();
1888 if (account.getStatus() == Account.State.ONLINE) {
1889 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1890 Element item = iq.query(Xmlns.ROSTER).addChild("item");
1891 item.setAttribute("jid", contact.getJid().toString());
1892 item.setAttribute("subscription", "remove");
1893 account.getXmppConnection().sendIqPacket(iq, null);
1894 }
1895 }
1896
1897 public void updateConversation(Conversation conversation) {
1898 this.databaseBackend.updateConversation(conversation);
1899 }
1900
1901 public void reconnectAccount(final Account account, final boolean force) {
1902 new Thread(new Runnable() {
1903
1904 @Override
1905 public void run() {
1906 if (account.getXmppConnection() != null) {
1907 disconnect(account, force);
1908 }
1909 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1910 if (account.getXmppConnection() == null) {
1911 account.setXmppConnection(createConnection(account));
1912 }
1913 Thread thread = new Thread(account.getXmppConnection());
1914 thread.start();
1915 scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
1916 } else {
1917 account.getRoster().clearPresences();
1918 account.setXmppConnection(null);
1919 }
1920 }
1921 }).start();
1922 }
1923
1924 public void invite(Conversation conversation, Jid contact) {
1925 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
1926 sendMessagePacket(conversation.getAccount(), packet);
1927 }
1928
1929 public void resetSendingToWaiting(Account account) {
1930 for (Conversation conversation : getConversations()) {
1931 if (conversation.getAccount() == account) {
1932 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
1933
1934 @Override
1935 public void onMessageFound(Message message) {
1936 markMessage(message, Message.STATUS_WAITING);
1937 }
1938 });
1939 }
1940 }
1941 }
1942
1943 public boolean markMessage(final Account account, final Jid recipient, final String uuid,
1944 final int status) {
1945 if (uuid == null) {
1946 return false;
1947 } else {
1948 for (Conversation conversation : getConversations()) {
1949 if (conversation.getJid().equals(recipient)
1950 && conversation.getAccount().equals(account)) {
1951 return markMessage(conversation, uuid, status);
1952 }
1953 }
1954 return false;
1955 }
1956 }
1957
1958 public boolean markMessage(Conversation conversation, String uuid,
1959 int status) {
1960 if (uuid == null) {
1961 return false;
1962 } else {
1963 Message message = conversation.findSentMessageWithUuid(uuid);
1964 if (message != null) {
1965 markMessage(message, status);
1966 return true;
1967 } else {
1968 return false;
1969 }
1970 }
1971 }
1972
1973 public void markMessage(Message message, int status) {
1974 if (status == Message.STATUS_SEND_FAILED
1975 && (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
1976 .getStatus() == Message.STATUS_SEND_DISPLAYED)) {
1977 return;
1978 }
1979 message.setStatus(status);
1980 databaseBackend.updateMessage(message);
1981 updateConversationUi();
1982 }
1983
1984 public SharedPreferences getPreferences() {
1985 return PreferenceManager
1986 .getDefaultSharedPreferences(getApplicationContext());
1987 }
1988
1989 public boolean forceEncryption() {
1990 return getPreferences().getBoolean("force_encryption", false);
1991 }
1992
1993 public boolean confirmMessages() {
1994 return getPreferences().getBoolean("confirm_messages", true);
1995 }
1996
1997 public boolean saveEncryptedMessages() {
1998 return !getPreferences().getBoolean("dont_save_encrypted", false);
1999 }
2000
2001 public boolean indicateReceived() {
2002 return getPreferences().getBoolean("indicate_received", false);
2003 }
2004
2005 public void updateConversationUi() {
2006 if (mOnConversationUpdate != null) {
2007 mOnConversationUpdate.onConversationUpdate();
2008 }
2009 }
2010
2011 public void updateAccountUi() {
2012 if (mOnAccountUpdate != null) {
2013 mOnAccountUpdate.onAccountUpdate();
2014 }
2015 }
2016
2017 public void updateRosterUi() {
2018 if (mOnRosterUpdate != null) {
2019 mOnRosterUpdate.onRosterUpdate();
2020 }
2021 }
2022
2023 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2024 if (mOnUpdateBlocklist != null) {
2025 mOnUpdateBlocklist.OnUpdateBlocklist(status);
2026 }
2027 }
2028
2029 public void updateMucRosterUi() {
2030 if (mOnMucRosterUpdate != null) {
2031 mOnMucRosterUpdate.onMucRosterUpdate();
2032 }
2033 }
2034
2035 public Account findAccountByJid(final Jid accountJid) {
2036 for (Account account : this.accounts) {
2037 if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2038 return account;
2039 }
2040 }
2041 return null;
2042 }
2043
2044 public Conversation findConversationByUuid(String uuid) {
2045 for (Conversation conversation : getConversations()) {
2046 if (conversation.getUuid().equals(uuid)) {
2047 return conversation;
2048 }
2049 }
2050 return null;
2051 }
2052
2053 public void markRead(final Conversation conversation) {
2054 mNotificationService.clear(conversation);
2055 conversation.markRead();
2056 }
2057
2058 public void sendReadMarker(final Conversation conversation) {
2059 final Message markable = conversation.getLatestMarkableMessage();
2060 this.markRead(conversation);
2061 if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2062 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2063 Account account = conversation.getAccount();
2064 final Jid to = markable.getCounterpart();
2065 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2066 this.sendMessagePacket(conversation.getAccount(), packet);
2067 }
2068 updateConversationUi();
2069 }
2070
2071 public SecureRandom getRNG() {
2072 return this.mRandom;
2073 }
2074
2075 public MemorizingTrustManager getMemorizingTrustManager() {
2076 return this.mMemorizingTrustManager;
2077 }
2078
2079 public PowerManager getPowerManager() {
2080 return this.pm;
2081 }
2082
2083 public LruCache<String, Bitmap> getBitmapCache() {
2084 return this.mBitmapCache;
2085 }
2086
2087 public void syncRosterToDisk(final Account account) {
2088 new Thread(new Runnable() {
2089
2090 @Override
2091 public void run() {
2092 databaseBackend.writeRoster(account.getRoster());
2093 }
2094 }).start();
2095
2096 }
2097
2098 public List<String> getKnownHosts() {
2099 final List<String> hosts = new ArrayList<>();
2100 for (final Account account : getAccounts()) {
2101 if (!hosts.contains(account.getServer().toString())) {
2102 hosts.add(account.getServer().toString());
2103 }
2104 for (final Contact contact : account.getRoster().getContacts()) {
2105 if (contact.showInRoster()) {
2106 final String server = contact.getServer().toString();
2107 if (server != null && !hosts.contains(server)) {
2108 hosts.add(server);
2109 }
2110 }
2111 }
2112 }
2113 return hosts;
2114 }
2115
2116 public List<String> getKnownConferenceHosts() {
2117 final ArrayList<String> mucServers = new ArrayList<>();
2118 for (final Account account : accounts) {
2119 if (account.getXmppConnection() != null) {
2120 final String server = account.getXmppConnection().getMucServer();
2121 if (server != null && !mucServers.contains(server)) {
2122 mucServers.add(server);
2123 }
2124 }
2125 }
2126 return mucServers;
2127 }
2128
2129 public void sendMessagePacket(Account account, MessagePacket packet) {
2130 XmppConnection connection = account.getXmppConnection();
2131 if (connection != null) {
2132 connection.sendMessagePacket(packet);
2133 }
2134 }
2135
2136 public void sendPresencePacket(Account account, PresencePacket packet) {
2137 XmppConnection connection = account.getXmppConnection();
2138 if (connection != null) {
2139 connection.sendPresencePacket(packet);
2140 }
2141 }
2142
2143 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2144 final XmppConnection connection = account.getXmppConnection();
2145 if (connection != null) {
2146 connection.sendIqPacket(packet, callback);
2147 }
2148 }
2149
2150 public MessageGenerator getMessageGenerator() {
2151 return this.mMessageGenerator;
2152 }
2153
2154 public PresenceGenerator getPresenceGenerator() {
2155 return this.mPresenceGenerator;
2156 }
2157
2158 public IqGenerator getIqGenerator() {
2159 return this.mIqGenerator;
2160 }
2161
2162 public IqParser getIqParser() {
2163 return this.mIqParser;
2164 }
2165
2166 public JingleConnectionManager getJingleConnectionManager() {
2167 return this.mJingleConnectionManager;
2168 }
2169
2170 public MessageArchiveService getMessageArchiveService() {
2171 return this.mMessageArchiveService;
2172 }
2173
2174 public List<Contact> findContacts(Jid jid) {
2175 ArrayList<Contact> contacts = new ArrayList<>();
2176 for (Account account : getAccounts()) {
2177 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2178 Contact contact = account.getRoster().getContactFromRoster(jid);
2179 if (contact != null) {
2180 contacts.add(contact);
2181 }
2182 }
2183 }
2184 return contacts;
2185 }
2186
2187 public NotificationService getNotificationService() {
2188 return this.mNotificationService;
2189 }
2190
2191 public HttpConnectionManager getHttpConnectionManager() {
2192 return this.mHttpConnectionManager;
2193 }
2194
2195 public void resendFailedMessages(final Message message) {
2196 final Collection<Message> messages = new ArrayList<>();
2197 Message current = message;
2198 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2199 messages.add(current);
2200 if (current.mergeable(current.next())) {
2201 current = current.next();
2202 } else {
2203 break;
2204 }
2205 }
2206 for (final Message msg : messages) {
2207 markMessage(msg, Message.STATUS_WAITING);
2208 this.resendMessage(msg);
2209 }
2210 }
2211
2212 public void clearConversationHistory(final Conversation conversation) {
2213 conversation.clearMessages();
2214 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2215 new Thread(new Runnable() {
2216 @Override
2217 public void run() {
2218 databaseBackend.deleteMessagesInConversation(conversation);
2219 }
2220 }).start();
2221 }
2222
2223 public void sendBlockRequest(final Blockable blockable) {
2224 if (blockable != null && blockable.getBlockedJid() != null) {
2225 final Jid jid = blockable.getBlockedJid();
2226 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2227
2228 @Override
2229 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2230 if (packet.getType() == IqPacket.TYPE.RESULT) {
2231 account.getBlocklist().add(jid);
2232 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2233 }
2234 }
2235 });
2236 }
2237 }
2238
2239 public void sendUnblockRequest(final Blockable blockable) {
2240 if (blockable != null && blockable.getJid() != null) {
2241 final Jid jid = blockable.getBlockedJid();
2242 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2243 @Override
2244 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2245 if (packet.getType() == IqPacket.TYPE.RESULT) {
2246 account.getBlocklist().remove(jid);
2247 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2248 }
2249 }
2250 });
2251 }
2252 }
2253
2254 public interface OnMoreMessagesLoaded {
2255 public void onMoreMessagesLoaded(int count, Conversation conversation);
2256
2257 public void informUser(int r);
2258 }
2259
2260 public interface OnAccountPasswordChanged {
2261 public void onPasswordChangeSucceeded();
2262
2263 public void onPasswordChangeFailed();
2264 }
2265
2266 public interface OnAffiliationChanged {
2267 public void onAffiliationChangedSuccessful(Jid jid);
2268
2269 public void onAffiliationChangeFailed(Jid jid, int resId);
2270 }
2271
2272 public interface OnRoleChanged {
2273 public void onRoleChangedSuccessful(String nick);
2274
2275 public void onRoleChangeFailed(String nick, int resid);
2276 }
2277
2278 public interface OnConversationUpdate {
2279 public void onConversationUpdate();
2280 }
2281
2282 public interface OnAccountUpdate {
2283 public void onAccountUpdate();
2284 }
2285
2286 public interface OnRosterUpdate {
2287 public void onRosterUpdate();
2288 }
2289
2290 public interface OnMucRosterUpdate {
2291 public void onMucRosterUpdate();
2292 }
2293
2294 public interface OnConferenceOptionsPushed {
2295 public void onPushSucceeded();
2296
2297 public void onPushFailed();
2298 }
2299
2300 public class XmppConnectionBinder extends Binder {
2301 public XmppConnectionService getService() {
2302 return XmppConnectionService.this;
2303 }
2304 }
2305}