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