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