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