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