XmppConnectionService.java

   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					message.setStatus(Message.STATUS_WAITING);
 759					packet = account.getAxolotlService().fetchPacketFromCache(message);
 760					if (packet == null && account.isOnlineAndConnected()) {
 761						account.getAxolotlService().prepareMessage(message);
 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			}
 793		}
 794
 795		if (resend) {
 796			if (packet != null) {
 797				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 798					markMessage(message,Message.STATUS_UNSEND);
 799				} else {
 800					markMessage(message,Message.STATUS_SEND);
 801				}
 802			}
 803		} else {
 804			conversation.add(message);
 805			if (saveInDb && (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages())) {
 806				databaseBackend.createMessage(message);
 807			}
 808			updateConversationUi();
 809		}
 810		if (packet != null) {
 811			if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 812				if (this.sendChatStates()) {
 813					packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
 814				}
 815			}
 816			sendMessagePacket(account, packet);
 817		}
 818	}
 819
 820	private void sendUnsentMessages(final Conversation conversation) {
 821		conversation.findWaitingMessages(new Conversation.OnMessageFound() {
 822
 823			@Override
 824			public void onMessageFound(Message message) {
 825				resendMessage(message);
 826			}
 827		});
 828	}
 829
 830	public void resendMessage(final Message message) {
 831		sendMessage(message, true);
 832	}
 833
 834	public void fetchRosterFromServer(final Account account) {
 835		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 836		if (!"".equals(account.getRosterVersion())) {
 837			Log.d(Config.LOGTAG, account.getJid().toBareJid()
 838					+ ": fetching roster version " + account.getRosterVersion());
 839		} else {
 840			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
 841		}
 842		iqPacket.query(Xmlns.ROSTER).setAttribute("ver",account.getRosterVersion());
 843		sendIqPacket(account,iqPacket,mIqParser);
 844	}
 845
 846	public void fetchBookmarks(final Account account) {
 847		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 848		final Element query = iqPacket.query("jabber:iq:private");
 849		query.addChild("storage", "storage:bookmarks");
 850		final OnIqPacketReceived callback = new OnIqPacketReceived() {
 851
 852			@Override
 853			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 854				final Element query = packet.query();
 855				final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
 856				final Element storage = query.findChild("storage",
 857						"storage:bookmarks");
 858				if (storage != null) {
 859					for (final Element item : storage.getChildren()) {
 860						if (item.getName().equals("conference")) {
 861							final Bookmark bookmark = Bookmark.parse(item, account);
 862							bookmarks.add(bookmark);
 863							Conversation conversation = find(bookmark);
 864							if (conversation != null) {
 865								conversation.setBookmark(bookmark);
 866							} else if (bookmark.autojoin() && bookmark.getJid() != null) {
 867								conversation = findOrCreateConversation(
 868										account, bookmark.getJid(), true);
 869								conversation.setBookmark(bookmark);
 870								joinMuc(conversation);
 871							}
 872						}
 873					}
 874				}
 875				account.setBookmarks(bookmarks);
 876			}
 877		};
 878		sendIqPacket(account, iqPacket, callback);
 879	}
 880
 881	public void pushBookmarks(Account account) {
 882		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
 883		Element query = iqPacket.query("jabber:iq:private");
 884		Element storage = query.addChild("storage", "storage:bookmarks");
 885		for (Bookmark bookmark : account.getBookmarks()) {
 886			storage.addChild(bookmark);
 887		}
 888		sendIqPacket(account, iqPacket, mDefaultIqHandler);
 889	}
 890
 891	public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
 892		if (mPhoneContactMergerThread != null) {
 893			mPhoneContactMergerThread.interrupt();
 894		}
 895		mPhoneContactMergerThread = new Thread(new Runnable() {
 896			@Override
 897			public void run() {
 898				Log.d(Config.LOGTAG,"start merging phone contacts with roster");
 899				for (Account account : accounts) {
 900					List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
 901					for (Bundle phoneContact : phoneContacts) {
 902						if (Thread.interrupted()) {
 903							Log.d(Config.LOGTAG,"interrupted merging phone contacts");
 904							return;
 905						}
 906						Jid jid;
 907						try {
 908							jid = Jid.fromString(phoneContact.getString("jid"));
 909						} catch (final InvalidJidException e) {
 910							continue;
 911						}
 912						final Contact contact = account.getRoster().getContact(jid);
 913						String systemAccount = phoneContact.getInt("phoneid")
 914							+ "#"
 915							+ phoneContact.getString("lookup");
 916						contact.setSystemAccount(systemAccount);
 917						if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
 918							getAvatarService().clear(contact);
 919						}
 920						contact.setSystemName(phoneContact.getString("displayname"));
 921						withSystemAccounts.remove(contact);
 922					}
 923					for(Contact contact : withSystemAccounts) {
 924						contact.setSystemAccount(null);
 925						contact.setSystemName(null);
 926						if (contact.setPhotoUri(null)) {
 927							getAvatarService().clear(contact);
 928						}
 929					}
 930				}
 931				Log.d(Config.LOGTAG,"finished merging phone contacts");
 932				updateAccountUi();
 933			}
 934		});
 935		mPhoneContactMergerThread.start();
 936	}
 937
 938	private void restoreFromDatabase() {
 939		synchronized (this.conversations) {
 940			final Map<String, Account> accountLookupTable = new Hashtable<>();
 941			for (Account account : this.accounts) {
 942				accountLookupTable.put(account.getUuid(), account);
 943			}
 944			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
 945			for (Conversation conversation : this.conversations) {
 946				Account account = accountLookupTable.get(conversation.getAccountUuid());
 947				conversation.setAccount(account);
 948			}
 949			Runnable runnable =new Runnable() {
 950				@Override
 951				public void run() {
 952					Log.d(Config.LOGTAG,"restoring roster");
 953					for(Account account : accounts) {
 954						databaseBackend.readRoster(account.getRoster());
 955						account.initAccountServices(XmppConnectionService.this);
 956					}
 957					getBitmapCache().evictAll();
 958					Looper.prepare();
 959					PhoneHelper.loadPhoneContacts(getApplicationContext(),
 960							new CopyOnWriteArrayList<Bundle>(),
 961							XmppConnectionService.this);
 962					Log.d(Config.LOGTAG,"restoring messages");
 963					for (Conversation conversation : conversations) {
 964						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
 965						checkDeletedFiles(conversation);
 966					}
 967					mRestoredFromDatabase = true;
 968					Log.d(Config.LOGTAG,"restored all messages");
 969					updateConversationUi();
 970				}
 971			};
 972			mDatabaseExecutor.execute(runnable);
 973		}
 974	}
 975
 976	public List<Conversation> getConversations() {
 977		return this.conversations;
 978	}
 979
 980	private void checkDeletedFiles(Conversation conversation) {
 981		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
 982
 983			@Override
 984			public void onMessageFound(Message message) {
 985				if (!getFileBackend().isFileAvailable(message)) {
 986					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
 987				}
 988			}
 989		});
 990	}
 991
 992	private void markFileDeleted(String uuid) {
 993		for (Conversation conversation : getConversations()) {
 994			Message message = conversation.findMessageWithFileAndUuid(uuid);
 995			if (message != null) {
 996				if (!getFileBackend().isFileAvailable(message)) {
 997					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
 998					updateConversationUi();
 999				}
1000				return;
1001			}
1002		}
1003	}
1004
1005	public void populateWithOrderedConversations(final List<Conversation> list) {
1006		populateWithOrderedConversations(list, true);
1007	}
1008
1009	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1010		list.clear();
1011		if (includeNoFileUpload) {
1012			list.addAll(getConversations());
1013		} else {
1014			for (Conversation conversation : getConversations()) {
1015				if (conversation.getMode() == Conversation.MODE_SINGLE
1016						|| conversation.getAccount().httpUploadAvailable()) {
1017					list.add(conversation);
1018				}
1019			}
1020		}
1021		Collections.sort(list, new Comparator<Conversation>() {
1022			@Override
1023			public int compare(Conversation lhs, Conversation rhs) {
1024				Message left = lhs.getLatestMessage();
1025				Message right = rhs.getLatestMessage();
1026				if (left.getTimeSent() > right.getTimeSent()) {
1027					return -1;
1028				} else if (left.getTimeSent() < right.getTimeSent()) {
1029					return 1;
1030				} else {
1031					return 0;
1032				}
1033			}
1034		});
1035	}
1036
1037	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1038		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1039		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
1040			return;
1041		}
1042		Runnable runnable = new Runnable() {
1043			@Override
1044			public void run() {
1045				final Account account = conversation.getAccount();
1046				List<Message> messages = databaseBackend.getMessages(conversation, 50,timestamp);
1047				if (messages.size() > 0) {
1048					conversation.addAll(0, messages);
1049					checkDeletedFiles(conversation);
1050					callback.onMoreMessagesLoaded(messages.size(), conversation);
1051				} else if (conversation.hasMessagesLeftOnServer()
1052						&& account.isOnlineAndConnected()
1053						&& account.getXmppConnection().getFeatures().mam()) {
1054					MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1);
1055					if (query != null) {
1056						query.setCallback(callback);
1057					}
1058					callback.informUser(R.string.fetching_history_from_server);
1059				}
1060			}
1061		};
1062		mDatabaseExecutor.execute(runnable);
1063	}
1064
1065	public List<Account> getAccounts() {
1066		return this.accounts;
1067	}
1068
1069	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1070		for (final Conversation conversation : haystack) {
1071			if (conversation.getContact() == contact) {
1072				return conversation;
1073			}
1074		}
1075		return null;
1076	}
1077
1078	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1079		if (jid == null) {
1080			return null;
1081		}
1082		for (final Conversation conversation : haystack) {
1083			if ((account == null || conversation.getAccount() == account)
1084					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1085				return conversation;
1086			}
1087		}
1088		return null;
1089	}
1090
1091	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1092		return this.findOrCreateConversation(account, jid, muc, null);
1093	}
1094
1095	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1096		synchronized (this.conversations) {
1097			Conversation conversation = find(account, jid);
1098			if (conversation != null) {
1099				return conversation;
1100			}
1101			conversation = databaseBackend.findConversation(account, jid);
1102			if (conversation != null) {
1103				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1104				conversation.setAccount(account);
1105				if (muc) {
1106					conversation.setMode(Conversation.MODE_MULTI);
1107					conversation.setContactJid(jid);
1108				} else {
1109					conversation.setMode(Conversation.MODE_SINGLE);
1110					conversation.setContactJid(jid.toBareJid());
1111				}
1112				conversation.setNextEncryption(-1);
1113				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1114				this.databaseBackend.updateConversation(conversation);
1115			} else {
1116				String conversationName;
1117				Contact contact = account.getRoster().getContact(jid);
1118				if (contact != null) {
1119					conversationName = contact.getDisplayName();
1120				} else {
1121					conversationName = jid.getLocalpart();
1122				}
1123				if (muc) {
1124					conversation = new Conversation(conversationName, account, jid,
1125							Conversation.MODE_MULTI);
1126				} else {
1127					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1128							Conversation.MODE_SINGLE);
1129				}
1130				this.databaseBackend.createConversation(conversation);
1131			}
1132			if (account.getXmppConnection() != null
1133					&& account.getXmppConnection().getFeatures().mam()
1134					&& !muc) {
1135				if (query == null) {
1136					this.mMessageArchiveService.query(conversation);
1137				} else {
1138					if (query.getConversation() == null) {
1139						this.mMessageArchiveService.query(conversation, query.getStart());
1140					}
1141				}
1142			}
1143			checkDeletedFiles(conversation);
1144			this.conversations.add(conversation);
1145			updateConversationUi();
1146			return conversation;
1147		}
1148	}
1149
1150	public void archiveConversation(Conversation conversation) {
1151		getNotificationService().clear(conversation);
1152		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1153		conversation.setNextEncryption(-1);
1154		synchronized (this.conversations) {
1155			if (conversation.getMode() == Conversation.MODE_MULTI) {
1156				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1157					Bookmark bookmark = conversation.getBookmark();
1158					if (bookmark != null && bookmark.autojoin()) {
1159						bookmark.setAutojoin(false);
1160						pushBookmarks(bookmark.getAccount());
1161					}
1162				}
1163				leaveMuc(conversation);
1164			} else {
1165				conversation.endOtrIfNeeded();
1166			}
1167			this.databaseBackend.updateConversation(conversation);
1168			this.conversations.remove(conversation);
1169			updateConversationUi();
1170		}
1171	}
1172
1173	public void createAccount(final Account account) {
1174		account.initAccountServices(this);
1175		databaseBackend.createAccount(account);
1176		this.accounts.add(account);
1177		this.reconnectAccountInBackground(account);
1178		updateAccountUi();
1179	}
1180
1181	public void updateAccount(final Account account) {
1182		this.statusListener.onStatusChanged(account);
1183		databaseBackend.updateAccount(account);
1184		reconnectAccount(account, false);
1185		updateAccountUi();
1186		getNotificationService().updateErrorNotification();
1187	}
1188
1189	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1190		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1191		sendIqPacket(account, iq, new OnIqPacketReceived() {
1192			@Override
1193			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1194				if (packet.getType() == IqPacket.TYPE.RESULT) {
1195					account.setPassword(newPassword);
1196					databaseBackend.updateAccount(account);
1197					callback.onPasswordChangeSucceeded();
1198				} else {
1199					callback.onPasswordChangeFailed();
1200				}
1201			}
1202		});
1203	}
1204
1205	public void deleteAccount(final Account account) {
1206		synchronized (this.conversations) {
1207			for (final Conversation conversation : conversations) {
1208				if (conversation.getAccount() == account) {
1209					if (conversation.getMode() == Conversation.MODE_MULTI) {
1210						leaveMuc(conversation);
1211					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1212						conversation.endOtrIfNeeded();
1213					}
1214					conversations.remove(conversation);
1215				}
1216			}
1217			if (account.getXmppConnection() != null) {
1218				this.disconnect(account, true);
1219			}
1220			databaseBackend.deleteAccount(account);
1221			this.accounts.remove(account);
1222			updateAccountUi();
1223			getNotificationService().updateErrorNotification();
1224		}
1225	}
1226
1227	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1228		synchronized (this) {
1229			if (checkListeners()) {
1230				switchToForeground();
1231			}
1232			this.mOnConversationUpdate = listener;
1233			this.mNotificationService.setIsInForeground(true);
1234			if (this.convChangedListenerCount < 2) {
1235				this.convChangedListenerCount++;
1236			}
1237		}
1238	}
1239
1240	public void removeOnConversationListChangedListener() {
1241		synchronized (this) {
1242			this.convChangedListenerCount--;
1243			if (this.convChangedListenerCount <= 0) {
1244				this.convChangedListenerCount = 0;
1245				this.mOnConversationUpdate = null;
1246				this.mNotificationService.setIsInForeground(false);
1247				if (checkListeners()) {
1248					switchToBackground();
1249				}
1250			}
1251		}
1252	}
1253
1254	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1255		synchronized (this) {
1256			if (checkListeners()) {
1257				switchToForeground();
1258			}
1259			this.mOnShowErrorToast = onShowErrorToast;
1260			if (this.showErrorToastListenerCount < 2) {
1261				this.showErrorToastListenerCount++;
1262			}
1263		}
1264		this.mOnShowErrorToast = onShowErrorToast;
1265	}
1266
1267	public void removeOnShowErrorToastListener() {
1268		synchronized (this) {
1269			this.showErrorToastListenerCount--;
1270			if (this.showErrorToastListenerCount <= 0) {
1271				this.showErrorToastListenerCount = 0;
1272				this.mOnShowErrorToast = null;
1273				if (checkListeners()) {
1274					switchToBackground();
1275				}
1276			}
1277		}
1278	}
1279
1280	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1281		synchronized (this) {
1282			if (checkListeners()) {
1283				switchToForeground();
1284			}
1285			this.mOnAccountUpdate = listener;
1286			if (this.accountChangedListenerCount < 2) {
1287				this.accountChangedListenerCount++;
1288			}
1289		}
1290	}
1291
1292	public void removeOnAccountListChangedListener() {
1293		synchronized (this) {
1294			this.accountChangedListenerCount--;
1295			if (this.accountChangedListenerCount <= 0) {
1296				this.mOnAccountUpdate = null;
1297				this.accountChangedListenerCount = 0;
1298				if (checkListeners()) {
1299					switchToBackground();
1300				}
1301			}
1302		}
1303	}
1304
1305	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1306		synchronized (this) {
1307			if (checkListeners()) {
1308				switchToForeground();
1309			}
1310			this.mOnRosterUpdate = listener;
1311			if (this.rosterChangedListenerCount < 2) {
1312				this.rosterChangedListenerCount++;
1313			}
1314		}
1315	}
1316
1317	public void removeOnRosterUpdateListener() {
1318		synchronized (this) {
1319			this.rosterChangedListenerCount--;
1320			if (this.rosterChangedListenerCount <= 0) {
1321				this.rosterChangedListenerCount = 0;
1322				this.mOnRosterUpdate = null;
1323				if (checkListeners()) {
1324					switchToBackground();
1325				}
1326			}
1327		}
1328	}
1329
1330	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1331		synchronized (this) {
1332			if (checkListeners()) {
1333				switchToForeground();
1334			}
1335			this.mOnUpdateBlocklist = listener;
1336			if (this.updateBlocklistListenerCount < 2) {
1337				this.updateBlocklistListenerCount++;
1338			}
1339		}
1340	}
1341
1342	public void removeOnUpdateBlocklistListener() {
1343		synchronized (this) {
1344			this.updateBlocklistListenerCount--;
1345			if (this.updateBlocklistListenerCount <= 0) {
1346				this.updateBlocklistListenerCount = 0;
1347				this.mOnUpdateBlocklist = null;
1348				if (checkListeners()) {
1349					switchToBackground();
1350				}
1351			}
1352		}
1353	}
1354
1355	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1356		synchronized (this) {
1357			if (checkListeners()) {
1358				switchToForeground();
1359			}
1360			this.mOnMucRosterUpdate = listener;
1361			if (this.mucRosterChangedListenerCount < 2) {
1362				this.mucRosterChangedListenerCount++;
1363			}
1364		}
1365	}
1366
1367	public void removeOnMucRosterUpdateListener() {
1368		synchronized (this) {
1369			this.mucRosterChangedListenerCount--;
1370			if (this.mucRosterChangedListenerCount <= 0) {
1371				this.mucRosterChangedListenerCount = 0;
1372				this.mOnMucRosterUpdate = null;
1373				if (checkListeners()) {
1374					switchToBackground();
1375				}
1376			}
1377		}
1378	}
1379
1380	private boolean checkListeners() {
1381		return (this.mOnAccountUpdate == null
1382				&& this.mOnConversationUpdate == null
1383				&& this.mOnRosterUpdate == null
1384				&& this.mOnUpdateBlocklist == null
1385				&& this.mOnShowErrorToast == null);
1386	}
1387
1388	private void switchToForeground() {
1389		for (Account account : getAccounts()) {
1390			if (account.getStatus() == Account.State.ONLINE) {
1391				XmppConnection connection = account.getXmppConnection();
1392				if (connection != null && connection.getFeatures().csi()) {
1393					connection.sendActive();
1394				}
1395			}
1396		}
1397		Log.d(Config.LOGTAG, "app switched into foreground");
1398	}
1399
1400	private void switchToBackground() {
1401		for (Account account : getAccounts()) {
1402			if (account.getStatus() == Account.State.ONLINE) {
1403				XmppConnection connection = account.getXmppConnection();
1404				if (connection != null && connection.getFeatures().csi()) {
1405					connection.sendInactive();
1406				}
1407			}
1408		}
1409		for(Conversation conversation : getConversations()) {
1410			conversation.setIncomingChatState(ChatState.ACTIVE);
1411		}
1412		this.mNotificationService.setIsInForeground(false);
1413		Log.d(Config.LOGTAG, "app switched into background");
1414	}
1415
1416	private void connectMultiModeConversations(Account account) {
1417		List<Conversation> conversations = getConversations();
1418		for (Conversation conversation : conversations) {
1419			if ((conversation.getMode() == Conversation.MODE_MULTI)
1420					&& (conversation.getAccount() == account)) {
1421				conversation.resetMucOptions();
1422				joinMuc(conversation);
1423			}
1424		}
1425	}
1426
1427	public void joinMuc(Conversation conversation) {
1428		Account account = conversation.getAccount();
1429		account.pendingConferenceJoins.remove(conversation);
1430		account.pendingConferenceLeaves.remove(conversation);
1431		if (account.getStatus() == Account.State.ONLINE) {
1432			final String nick = conversation.getMucOptions().getProposedNick();
1433			final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1434			if (joinJid == null) {
1435				return; //safety net
1436			}
1437			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1438			PresencePacket packet = new PresencePacket();
1439			packet.setFrom(conversation.getAccount().getJid());
1440			packet.setTo(joinJid);
1441			Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1442			if (conversation.getMucOptions().getPassword() != null) {
1443				x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1444			}
1445			x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1446			String sig = account.getPgpSignature();
1447			if (sig != null) {
1448				packet.addChild("status").setContent("online");
1449				packet.addChild("x", "jabber:x:signed").setContent(sig);
1450			}
1451			sendPresencePacket(account, packet);
1452			fetchConferenceConfiguration(conversation);
1453			if (!joinJid.equals(conversation.getJid())) {
1454				conversation.setContactJid(joinJid);
1455				databaseBackend.updateConversation(conversation);
1456			}
1457			conversation.setHasMessagesLeftOnServer(false);
1458		} else {
1459			account.pendingConferenceJoins.add(conversation);
1460		}
1461	}
1462
1463	public void providePasswordForMuc(Conversation conversation, String password) {
1464		if (conversation.getMode() == Conversation.MODE_MULTI) {
1465			conversation.getMucOptions().setPassword(password);
1466			if (conversation.getBookmark() != null) {
1467				conversation.getBookmark().setAutojoin(true);
1468				pushBookmarks(conversation.getAccount());
1469			}
1470			databaseBackend.updateConversation(conversation);
1471			joinMuc(conversation);
1472		}
1473	}
1474
1475	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1476		final MucOptions options = conversation.getMucOptions();
1477		final Jid joinJid = options.createJoinJid(nick);
1478		if (options.online()) {
1479			Account account = conversation.getAccount();
1480			options.setOnRenameListener(new OnRenameListener() {
1481
1482				@Override
1483				public void onSuccess() {
1484					conversation.setContactJid(joinJid);
1485					databaseBackend.updateConversation(conversation);
1486					Bookmark bookmark = conversation.getBookmark();
1487					if (bookmark != null) {
1488						bookmark.setNick(nick);
1489						pushBookmarks(bookmark.getAccount());
1490					}
1491					callback.success(conversation);
1492				}
1493
1494				@Override
1495				public void onFailure() {
1496					callback.error(R.string.nick_in_use, conversation);
1497				}
1498			});
1499
1500			PresencePacket packet = new PresencePacket();
1501			packet.setTo(joinJid);
1502			packet.setFrom(conversation.getAccount().getJid());
1503
1504			String sig = account.getPgpSignature();
1505			if (sig != null) {
1506				packet.addChild("status").setContent("online");
1507				packet.addChild("x", "jabber:x:signed").setContent(sig);
1508			}
1509			sendPresencePacket(account, packet);
1510		} else {
1511			conversation.setContactJid(joinJid);
1512			databaseBackend.updateConversation(conversation);
1513			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1514				Bookmark bookmark = conversation.getBookmark();
1515				if (bookmark != null) {
1516					bookmark.setNick(nick);
1517					pushBookmarks(bookmark.getAccount());
1518				}
1519				joinMuc(conversation);
1520			}
1521		}
1522	}
1523
1524	public void leaveMuc(Conversation conversation) {
1525		Account account = conversation.getAccount();
1526		account.pendingConferenceJoins.remove(conversation);
1527		account.pendingConferenceLeaves.remove(conversation);
1528		if (account.getStatus() == Account.State.ONLINE) {
1529			PresencePacket packet = new PresencePacket();
1530			packet.setTo(conversation.getJid());
1531			packet.setFrom(conversation.getAccount().getJid());
1532			packet.setAttribute("type", "unavailable");
1533			sendPresencePacket(conversation.getAccount(), packet);
1534			conversation.getMucOptions().setOffline();
1535			conversation.deregisterWithBookmark();
1536			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1537					+ ": leaving muc " + conversation.getJid());
1538		} else {
1539			account.pendingConferenceLeaves.add(conversation);
1540		}
1541	}
1542
1543	private String findConferenceServer(final Account account) {
1544		String server;
1545		if (account.getXmppConnection() != null) {
1546			server = account.getXmppConnection().getMucServer();
1547			if (server != null) {
1548				return server;
1549			}
1550		}
1551		for (Account other : getAccounts()) {
1552			if (other != account && other.getXmppConnection() != null) {
1553				server = other.getXmppConnection().getMucServer();
1554				if (server != null) {
1555					return server;
1556				}
1557			}
1558		}
1559		return null;
1560	}
1561
1562	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1563		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1564		if (account.getStatus() == Account.State.ONLINE) {
1565			try {
1566				String server = findConferenceServer(account);
1567				if (server == null) {
1568					if (callback != null) {
1569						callback.error(R.string.no_conference_server_found, null);
1570					}
1571					return;
1572				}
1573				String name = new BigInteger(75, getRNG()).toString(32);
1574				Jid jid = Jid.fromParts(name, server, null);
1575				final Conversation conversation = findOrCreateConversation(account, jid, true);
1576				joinMuc(conversation);
1577				Bundle options = new Bundle();
1578				options.putString("muc#roomconfig_persistentroom", "1");
1579				options.putString("muc#roomconfig_membersonly", "1");
1580				options.putString("muc#roomconfig_publicroom", "0");
1581				options.putString("muc#roomconfig_whois", "anyone");
1582				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1583					@Override
1584					public void onPushSucceeded() {
1585						for (Jid invite : jids) {
1586							invite(conversation, invite);
1587						}
1588						if (account.countPresences() > 1) {
1589							directInvite(conversation, account.getJid().toBareJid());
1590						}
1591						if (callback != null) {
1592							callback.success(conversation);
1593						}
1594					}
1595
1596					@Override
1597					public void onPushFailed() {
1598						if (callback != null) {
1599							callback.error(R.string.conference_creation_failed, conversation);
1600						}
1601					}
1602				});
1603
1604			} catch (InvalidJidException e) {
1605				if (callback != null) {
1606					callback.error(R.string.conference_creation_failed, null);
1607				}
1608			}
1609		} else {
1610			if (callback != null) {
1611				callback.error(R.string.not_connected_try_again, null);
1612			}
1613		}
1614	}
1615
1616	public void fetchConferenceConfiguration(final Conversation conversation) {
1617		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1618		request.setTo(conversation.getJid().toBareJid());
1619		request.query("http://jabber.org/protocol/disco#info");
1620		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1621			@Override
1622			public void onIqPacketReceived(Account account, IqPacket packet) {
1623				if (packet.getType() != IqPacket.TYPE.ERROR) {
1624					ArrayList<String> features = new ArrayList<>();
1625					for (Element child : packet.query().getChildren()) {
1626						if (child != null && child.getName().equals("feature")) {
1627							String var = child.getAttribute("var");
1628							if (var != null) {
1629								features.add(var);
1630							}
1631						}
1632					}
1633					conversation.getMucOptions().updateFeatures(features);
1634					updateConversationUi();
1635				}
1636			}
1637		});
1638	}
1639
1640	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1641		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1642		request.setTo(conversation.getJid().toBareJid());
1643		request.query("http://jabber.org/protocol/muc#owner");
1644		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1645			@Override
1646			public void onIqPacketReceived(Account account, IqPacket packet) {
1647				if (packet.getType() != IqPacket.TYPE.ERROR) {
1648					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1649					for (Field field : data.getFields()) {
1650						if (options.containsKey(field.getName())) {
1651							field.setValue(options.getString(field.getName()));
1652						}
1653					}
1654					data.submit();
1655					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1656					set.setTo(conversation.getJid().toBareJid());
1657					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1658					sendIqPacket(account, set, new OnIqPacketReceived() {
1659						@Override
1660						public void onIqPacketReceived(Account account, IqPacket packet) {
1661							if (packet.getType() == IqPacket.TYPE.RESULT) {
1662								if (callback != null) {
1663									callback.onPushSucceeded();
1664								}
1665							} else {
1666								if (callback != null) {
1667									callback.onPushFailed();
1668								}
1669							}
1670						}
1671					});
1672				} else {
1673					if (callback != null) {
1674						callback.onPushFailed();
1675					}
1676				}
1677			}
1678		});
1679	}
1680
1681	public void pushSubjectToConference(final Conversation conference, final String subject) {
1682		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1683		this.sendMessagePacket(conference.getAccount(), packet);
1684		final MucOptions mucOptions = conference.getMucOptions();
1685		final MucOptions.User self = mucOptions.getSelf();
1686		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1687			Bundle options = new Bundle();
1688			options.putString("muc#roomconfig_persistentroom", "1");
1689			this.pushConferenceConfiguration(conference, options, null);
1690		}
1691	}
1692
1693	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1694		final Jid jid = user.toBareJid();
1695		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1696		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1697			@Override
1698			public void onIqPacketReceived(Account account, IqPacket packet) {
1699				if (packet.getType() == IqPacket.TYPE.RESULT) {
1700					callback.onAffiliationChangedSuccessful(jid);
1701				} else {
1702					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1703				}
1704			}
1705		});
1706	}
1707
1708	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1709		List<Jid> jids = new ArrayList<>();
1710		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1711			if (user.getAffiliation() == before && user.getJid() != null) {
1712				jids.add(user.getJid());
1713			}
1714		}
1715		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1716		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1717	}
1718
1719	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1720		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1721		Log.d(Config.LOGTAG, request.toString());
1722		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1723			@Override
1724			public void onIqPacketReceived(Account account, IqPacket packet) {
1725				Log.d(Config.LOGTAG, packet.toString());
1726				if (packet.getType() == IqPacket.TYPE.RESULT) {
1727					callback.onRoleChangedSuccessful(nick);
1728				} else {
1729					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1730				}
1731			}
1732		});
1733	}
1734
1735	public void disconnect(Account account, boolean force) {
1736		if ((account.getStatus() == Account.State.ONLINE)
1737				|| (account.getStatus() == Account.State.DISABLED)) {
1738			if (!force) {
1739				List<Conversation> conversations = getConversations();
1740				for (Conversation conversation : conversations) {
1741					if (conversation.getAccount() == account) {
1742						if (conversation.getMode() == Conversation.MODE_MULTI) {
1743							leaveMuc(conversation);
1744						} else {
1745							if (conversation.endOtrIfNeeded()) {
1746								Log.d(Config.LOGTAG, account.getJid().toBareJid()
1747										+ ": ended otr session with "
1748										+ conversation.getJid());
1749							}
1750						}
1751					}
1752				}
1753				sendOfflinePresence(account);
1754			}
1755			account.getXmppConnection().disconnect(force);
1756		}
1757	}
1758
1759	@Override
1760	public IBinder onBind(Intent intent) {
1761		return mBinder;
1762	}
1763
1764	public void updateMessage(Message message) {
1765		databaseBackend.updateMessage(message);
1766		updateConversationUi();
1767	}
1768
1769	protected void syncDirtyContacts(Account account) {
1770		for (Contact contact : account.getRoster().getContacts()) {
1771			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1772				pushContactToServer(contact);
1773			}
1774			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1775				deleteContactOnServer(contact);
1776			}
1777		}
1778	}
1779
1780	public void createContact(Contact contact) {
1781		SharedPreferences sharedPref = getPreferences();
1782		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1783		if (autoGrant) {
1784			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1785			contact.setOption(Contact.Options.ASKING);
1786		}
1787		pushContactToServer(contact);
1788	}
1789
1790	public void onOtrSessionEstablished(Conversation conversation) {
1791		final Account account = conversation.getAccount();
1792		final Session otrSession = conversation.getOtrSession();
1793		Log.d(Config.LOGTAG,
1794				account.getJid().toBareJid() + " otr session established with "
1795						+ conversation.getJid() + "/"
1796						+ otrSession.getSessionID().getUserID());
1797		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
1798
1799			@Override
1800			public void onMessageFound(Message message) {
1801				SessionID id = otrSession.getSessionID();
1802				try {
1803					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1804				} catch (InvalidJidException e) {
1805					return;
1806				}
1807				if (message.needsUploading()) {
1808					mJingleConnectionManager.createNewConnection(message);
1809				} else {
1810					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message, true);
1811					if (outPacket != null) {
1812						message.setStatus(Message.STATUS_SEND);
1813						databaseBackend.updateMessage(message);
1814						sendMessagePacket(account, outPacket);
1815					}
1816				}
1817				updateConversationUi();
1818			}
1819		});
1820	}
1821
1822	public boolean renewSymmetricKey(Conversation conversation) {
1823		Account account = conversation.getAccount();
1824		byte[] symmetricKey = new byte[32];
1825		this.mRandom.nextBytes(symmetricKey);
1826		Session otrSession = conversation.getOtrSession();
1827		if (otrSession != null) {
1828			MessagePacket packet = new MessagePacket();
1829			packet.setType(MessagePacket.TYPE_CHAT);
1830			packet.setFrom(account.getJid());
1831			packet.addChild("private", "urn:xmpp:carbons:2");
1832			packet.addChild("no-copy", "urn:xmpp:hints");
1833			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1834					+ otrSession.getSessionID().getUserID());
1835			try {
1836				packet.setBody(otrSession
1837						.transformSending(CryptoHelper.FILETRANSFER
1838								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
1839				sendMessagePacket(account, packet);
1840				conversation.setSymmetricKey(symmetricKey);
1841				return true;
1842			} catch (OtrException e) {
1843				return false;
1844			}
1845		}
1846		return false;
1847	}
1848
1849	public void pushContactToServer(final Contact contact) {
1850		contact.resetOption(Contact.Options.DIRTY_DELETE);
1851		contact.setOption(Contact.Options.DIRTY_PUSH);
1852		final Account account = contact.getAccount();
1853		if (account.getStatus() == Account.State.ONLINE) {
1854			final boolean ask = contact.getOption(Contact.Options.ASKING);
1855			final boolean sendUpdates = contact
1856					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1857					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1858			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1859			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1860			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
1861			if (sendUpdates) {
1862				sendPresencePacket(account,
1863						mPresenceGenerator.sendPresenceUpdatesTo(contact));
1864			}
1865			if (ask) {
1866				sendPresencePacket(account,
1867						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1868			}
1869		}
1870	}
1871
1872	public void publishAvatar(final Account account,
1873							  final Uri image,
1874							  final UiCallback<Avatar> callback) {
1875		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1876		final int size = Config.AVATAR_SIZE;
1877		final Avatar avatar = getFileBackend()
1878				.getPepAvatar(image, size, format);
1879		if (avatar != null) {
1880			avatar.height = size;
1881			avatar.width = size;
1882			if (format.equals(Bitmap.CompressFormat.WEBP)) {
1883				avatar.type = "image/webp";
1884			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1885				avatar.type = "image/jpeg";
1886			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
1887				avatar.type = "image/png";
1888			}
1889			if (!getFileBackend().save(avatar)) {
1890				callback.error(R.string.error_saving_avatar, avatar);
1891				return;
1892			}
1893			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1894			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1895
1896				@Override
1897				public void onIqPacketReceived(Account account, IqPacket result) {
1898					if (result.getType() == IqPacket.TYPE.RESULT) {
1899						final IqPacket packet = XmppConnectionService.this.mIqGenerator
1900								.publishAvatarMetadata(avatar);
1901						sendIqPacket(account, packet, new OnIqPacketReceived() {
1902
1903							@Override
1904							public void onIqPacketReceived(Account account,
1905														   IqPacket result) {
1906								if (result.getType() == IqPacket.TYPE.RESULT) {
1907									if (account.setAvatar(avatar.getFilename())) {
1908										getAvatarService().clear(account);
1909										databaseBackend.updateAccount(account);
1910									}
1911									callback.success(avatar);
1912								} else {
1913									callback.error(
1914											R.string.error_publish_avatar_server_reject,
1915											avatar);
1916								}
1917							}
1918						});
1919					} else {
1920						callback.error(
1921								R.string.error_publish_avatar_server_reject,
1922								avatar);
1923					}
1924				}
1925			});
1926		} else {
1927			callback.error(R.string.error_publish_avatar_converting, null);
1928		}
1929	}
1930
1931	public void fetchAvatar(Account account, Avatar avatar) {
1932		fetchAvatar(account, avatar, null);
1933	}
1934
1935	private static String generateFetchKey(Account account, final Avatar avatar) {
1936		return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum;
1937	}
1938
1939	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1940		final String KEY = generateFetchKey(account, avatar);
1941		synchronized(this.mInProgressAvatarFetches) {
1942			if (this.mInProgressAvatarFetches.contains(KEY)) {
1943				return;
1944			} else {
1945				switch (avatar.origin) {
1946					case PEP:
1947						this.mInProgressAvatarFetches.add(KEY);
1948						fetchAvatarPep(account, avatar, callback);
1949						break;
1950					case VCARD:
1951						this.mInProgressAvatarFetches.add(KEY);
1952						fetchAvatarVcard(account, avatar, callback);
1953						break;
1954				}
1955			}
1956		}
1957	}
1958
1959	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1960		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
1961		sendIqPacket(account, packet, new OnIqPacketReceived() {
1962
1963			@Override
1964			public void onIqPacketReceived(Account account, IqPacket result) {
1965				synchronized (mInProgressAvatarFetches) {
1966					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
1967				}
1968				final String ERROR = account.getJid().toBareJid()
1969						+ ": fetching avatar for " + avatar.owner + " failed ";
1970				if (result.getType() == IqPacket.TYPE.RESULT) {
1971					avatar.image = mIqParser.avatarData(result);
1972					if (avatar.image != null) {
1973						if (getFileBackend().save(avatar)) {
1974							if (account.getJid().toBareJid().equals(avatar.owner)) {
1975								if (account.setAvatar(avatar.getFilename())) {
1976									databaseBackend.updateAccount(account);
1977								}
1978								getAvatarService().clear(account);
1979								updateConversationUi();
1980								updateAccountUi();
1981							} else {
1982								Contact contact = account.getRoster()
1983										.getContact(avatar.owner);
1984								contact.setAvatar(avatar);
1985								getAvatarService().clear(contact);
1986								updateConversationUi();
1987								updateRosterUi();
1988							}
1989							if (callback != null) {
1990								callback.success(avatar);
1991							}
1992							Log.d(Config.LOGTAG, account.getJid().toBareJid()
1993									+ ": succesfuly fetched pep avatar for " + avatar.owner);
1994							return;
1995						}
1996					} else {
1997
1998						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
1999					}
2000				} else {
2001					Element error = result.findChild("error");
2002					if (error == null) {
2003						Log.d(Config.LOGTAG, ERROR + "(server error)");
2004					} else {
2005						Log.d(Config.LOGTAG, ERROR + error.toString());
2006					}
2007				}
2008				if (callback != null) {
2009					callback.error(0, null);
2010				}
2011
2012			}
2013		});
2014	}
2015
2016	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2017		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2018		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2019			@Override
2020			public void onIqPacketReceived(Account account, IqPacket packet) {
2021				synchronized (mInProgressAvatarFetches) {
2022					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2023				}
2024				if (packet.getType() == IqPacket.TYPE.RESULT) {
2025					Element vCard = packet.findChild("vCard", "vcard-temp");
2026					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2027					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2028					if (image != null) {
2029						avatar.image = image;
2030						if (getFileBackend().save(avatar)) {
2031							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2032									+ ": successfully fetched vCard avatar for " + avatar.owner);
2033							Contact contact = account.getRoster()
2034									.getContact(avatar.owner);
2035							contact.setAvatar(avatar);
2036							getAvatarService().clear(contact);
2037							updateConversationUi();
2038							updateRosterUi();
2039						}
2040					}
2041				}
2042			}
2043		});
2044	}
2045
2046	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2047		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2048		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2049
2050			@Override
2051			public void onIqPacketReceived(Account account, IqPacket packet) {
2052				if (packet.getType() == IqPacket.TYPE.RESULT) {
2053					Element pubsub = packet.findChild("pubsub",
2054							"http://jabber.org/protocol/pubsub");
2055					if (pubsub != null) {
2056						Element items = pubsub.findChild("items");
2057						if (items != null) {
2058							Avatar avatar = Avatar.parseMetadata(items);
2059							if (avatar != null) {
2060								avatar.owner = account.getJid().toBareJid();
2061								if (fileBackend.isAvatarCached(avatar)) {
2062									if (account.setAvatar(avatar.getFilename())) {
2063										databaseBackend.updateAccount(account);
2064									}
2065									getAvatarService().clear(account);
2066									callback.success(avatar);
2067								} else {
2068									fetchAvatarPep(account, avatar, callback);
2069								}
2070								return;
2071							}
2072						}
2073					}
2074				}
2075				callback.error(0, null);
2076			}
2077		});
2078	}
2079
2080	public void deleteContactOnServer(Contact contact) {
2081		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2082		contact.resetOption(Contact.Options.DIRTY_PUSH);
2083		contact.setOption(Contact.Options.DIRTY_DELETE);
2084		Account account = contact.getAccount();
2085		if (account.getStatus() == Account.State.ONLINE) {
2086			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2087			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2088			item.setAttribute("jid", contact.getJid().toString());
2089			item.setAttribute("subscription", "remove");
2090			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2091		}
2092	}
2093
2094	public void updateConversation(Conversation conversation) {
2095		this.databaseBackend.updateConversation(conversation);
2096	}
2097
2098	public void reconnectAccount(final Account account, final boolean force) {
2099		synchronized (account) {
2100			if (account.getXmppConnection() != null) {
2101				disconnect(account, force);
2102			}
2103			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2104
2105				synchronized (this.mInProgressAvatarFetches) {
2106					for(Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) {
2107						final String KEY = iterator.next();
2108						if (KEY.startsWith(account.getJid().toBareJid()+"_")) {
2109							iterator.remove();
2110						}
2111					}
2112				}
2113
2114				if (account.getXmppConnection() == null) {
2115					account.setXmppConnection(createConnection(account));
2116				}
2117				Thread thread = new Thread(account.getXmppConnection());
2118				thread.start();
2119				scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2120			} else {
2121				account.getRoster().clearPresences();
2122				account.setXmppConnection(null);
2123			}
2124		}
2125	}
2126
2127	public void reconnectAccountInBackground(final Account account) {
2128		new Thread(new Runnable() {
2129			@Override
2130			public void run() {
2131				reconnectAccount(account,false);
2132			}
2133		}).start();
2134	}
2135
2136	public void invite(Conversation conversation, Jid contact) {
2137		Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid());
2138		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2139		sendMessagePacket(conversation.getAccount(), packet);
2140	}
2141
2142	public void directInvite(Conversation conversation, Jid jid) {
2143		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2144		sendMessagePacket(conversation.getAccount(),packet);
2145	}
2146
2147	public void resetSendingToWaiting(Account account) {
2148		for (Conversation conversation : getConversations()) {
2149			if (conversation.getAccount() == account) {
2150				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2151
2152					@Override
2153					public void onMessageFound(Message message) {
2154						markMessage(message, Message.STATUS_WAITING);
2155					}
2156				});
2157			}
2158		}
2159	}
2160
2161	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2162		if (uuid == null) {
2163			return null;
2164		}
2165		for (Conversation conversation : getConversations()) {
2166			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2167				final Message message = conversation.findSentMessageWithUuid(uuid);
2168				if (message != null) {
2169					markMessage(message, status);
2170				}
2171				return message;
2172			}
2173		}
2174		return null;
2175	}
2176
2177	public boolean markMessage(Conversation conversation, String uuid,
2178							   int status) {
2179		if (uuid == null) {
2180			return false;
2181		} else {
2182			Message message = conversation.findSentMessageWithUuid(uuid);
2183			if (message != null) {
2184				markMessage(message, status);
2185				return true;
2186			} else {
2187				return false;
2188			}
2189		}
2190	}
2191
2192	public void markMessage(Message message, int status) {
2193		if (status == Message.STATUS_SEND_FAILED
2194				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2195				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2196			return;
2197		}
2198		message.setStatus(status);
2199		databaseBackend.updateMessage(message);
2200		updateConversationUi();
2201	}
2202
2203	public SharedPreferences getPreferences() {
2204		return PreferenceManager
2205				.getDefaultSharedPreferences(getApplicationContext());
2206	}
2207
2208	public boolean forceEncryption() {
2209		return getPreferences().getBoolean("force_encryption", false);
2210	}
2211
2212	public boolean confirmMessages() {
2213		return getPreferences().getBoolean("confirm_messages", true);
2214	}
2215
2216	public boolean sendChatStates() {
2217		return getPreferences().getBoolean("chat_states", false);
2218	}
2219
2220	public boolean saveEncryptedMessages() {
2221		return !getPreferences().getBoolean("dont_save_encrypted", false);
2222	}
2223
2224	public boolean indicateReceived() {
2225		return getPreferences().getBoolean("indicate_received", false);
2226	}
2227
2228	public int unreadCount() {
2229		int count = 0;
2230		for(Conversation conversation : getConversations()) {
2231			count += conversation.unreadCount();
2232		}
2233		return count;
2234	}
2235
2236
2237	public void showErrorToastInUi(int resId) {
2238		if (mOnShowErrorToast != null) {
2239			mOnShowErrorToast.onShowErrorToast(resId);
2240		}
2241	}
2242
2243	public void updateConversationUi() {
2244		if (mOnConversationUpdate != null) {
2245			mOnConversationUpdate.onConversationUpdate();
2246		}
2247	}
2248
2249	public void updateAccountUi() {
2250		if (mOnAccountUpdate != null) {
2251			mOnAccountUpdate.onAccountUpdate();
2252		}
2253	}
2254
2255	public void updateRosterUi() {
2256		if (mOnRosterUpdate != null) {
2257			mOnRosterUpdate.onRosterUpdate();
2258		}
2259	}
2260
2261	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2262		if (mOnUpdateBlocklist != null) {
2263			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2264		}
2265	}
2266
2267	public void updateMucRosterUi() {
2268		if (mOnMucRosterUpdate != null) {
2269			mOnMucRosterUpdate.onMucRosterUpdate();
2270		}
2271	}
2272
2273	public Account findAccountByJid(final Jid accountJid) {
2274		for (Account account : this.accounts) {
2275			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2276				return account;
2277			}
2278		}
2279		return null;
2280	}
2281
2282	public Conversation findConversationByUuid(String uuid) {
2283		for (Conversation conversation : getConversations()) {
2284			if (conversation.getUuid().equals(uuid)) {
2285				return conversation;
2286			}
2287		}
2288		return null;
2289	}
2290
2291	public void markRead(final Conversation conversation) {
2292		mNotificationService.clear(conversation);
2293		conversation.markRead();
2294		updateUnreadCountBadge();
2295	}
2296
2297	public synchronized void updateUnreadCountBadge() {
2298		int count = unreadCount();
2299		if (unreadCount != count) {
2300			Log.d(Config.LOGTAG, "update unread count to " + count);
2301			if (count > 0) {
2302				ShortcutBadger.with(getApplicationContext()).count(count);
2303			} else {
2304				ShortcutBadger.with(getApplicationContext()).remove();
2305			}
2306			unreadCount = count;
2307		}
2308	}
2309
2310	public void sendReadMarker(final Conversation conversation) {
2311		final Message markable = conversation.getLatestMarkableMessage();
2312		this.markRead(conversation);
2313		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2314			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2315			Account account = conversation.getAccount();
2316			final Jid to = markable.getCounterpart();
2317			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2318			this.sendMessagePacket(conversation.getAccount(), packet);
2319		}
2320		updateConversationUi();
2321	}
2322
2323	public SecureRandom getRNG() {
2324		return this.mRandom;
2325	}
2326
2327	public MemorizingTrustManager getMemorizingTrustManager() {
2328		return this.mMemorizingTrustManager;
2329	}
2330
2331	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2332		this.mMemorizingTrustManager = trustManager;
2333	}
2334
2335	public void updateMemorizingTrustmanager() {
2336		final MemorizingTrustManager tm;
2337		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2338		if (dontTrustSystemCAs) {
2339			 tm = new MemorizingTrustManager(getApplicationContext(), null);
2340		} else {
2341			tm = new MemorizingTrustManager(getApplicationContext());
2342		}
2343		setMemorizingTrustManager(tm);
2344	}
2345
2346	public PowerManager getPowerManager() {
2347		return this.pm;
2348	}
2349
2350	public LruCache<String, Bitmap> getBitmapCache() {
2351		return this.mBitmapCache;
2352	}
2353
2354	public void syncRosterToDisk(final Account account) {
2355		Runnable runnable = new Runnable() {
2356
2357			@Override
2358			public void run() {
2359				databaseBackend.writeRoster(account.getRoster());
2360			}
2361		};
2362		mDatabaseExecutor.execute(runnable);
2363
2364	}
2365
2366	public List<String> getKnownHosts() {
2367		final List<String> hosts = new ArrayList<>();
2368		for (final Account account : getAccounts()) {
2369			if (!hosts.contains(account.getServer().toString())) {
2370				hosts.add(account.getServer().toString());
2371			}
2372			for (final Contact contact : account.getRoster().getContacts()) {
2373				if (contact.showInRoster()) {
2374					final String server = contact.getServer().toString();
2375					if (server != null && !hosts.contains(server)) {
2376						hosts.add(server);
2377					}
2378				}
2379			}
2380		}
2381		return hosts;
2382	}
2383
2384	public List<String> getKnownConferenceHosts() {
2385		final ArrayList<String> mucServers = new ArrayList<>();
2386		for (final Account account : accounts) {
2387			if (account.getXmppConnection() != null) {
2388				final String server = account.getXmppConnection().getMucServer();
2389				if (server != null && !mucServers.contains(server)) {
2390					mucServers.add(server);
2391				}
2392			}
2393		}
2394		return mucServers;
2395	}
2396
2397	public void sendMessagePacket(Account account, MessagePacket packet) {
2398		XmppConnection connection = account.getXmppConnection();
2399		if (connection != null) {
2400			connection.sendMessagePacket(packet);
2401		}
2402	}
2403
2404	public void sendPresencePacket(Account account, PresencePacket packet) {
2405		XmppConnection connection = account.getXmppConnection();
2406		if (connection != null) {
2407			connection.sendPresencePacket(packet);
2408		}
2409	}
2410
2411	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2412		final XmppConnection connection = account.getXmppConnection();
2413		if (connection != null) {
2414			connection.sendIqPacket(packet, callback);
2415		}
2416	}
2417
2418	public void sendPresence(final Account account) {
2419		sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2420	}
2421
2422	public void sendOfflinePresence(final Account account) {
2423		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2424	}
2425
2426	public MessageGenerator getMessageGenerator() {
2427		return this.mMessageGenerator;
2428	}
2429
2430	public PresenceGenerator getPresenceGenerator() {
2431		return this.mPresenceGenerator;
2432	}
2433
2434	public IqGenerator getIqGenerator() {
2435		return this.mIqGenerator;
2436	}
2437
2438	public IqParser getIqParser() {
2439		return this.mIqParser;
2440	}
2441
2442	public JingleConnectionManager getJingleConnectionManager() {
2443		return this.mJingleConnectionManager;
2444	}
2445
2446	public MessageArchiveService getMessageArchiveService() {
2447		return this.mMessageArchiveService;
2448	}
2449
2450	public List<Contact> findContacts(Jid jid) {
2451		ArrayList<Contact> contacts = new ArrayList<>();
2452		for (Account account : getAccounts()) {
2453			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2454				Contact contact = account.getRoster().getContactFromRoster(jid);
2455				if (contact != null) {
2456					contacts.add(contact);
2457				}
2458			}
2459		}
2460		return contacts;
2461	}
2462
2463	public NotificationService getNotificationService() {
2464		return this.mNotificationService;
2465	}
2466
2467	public HttpConnectionManager getHttpConnectionManager() {
2468		return this.mHttpConnectionManager;
2469	}
2470
2471	public void resendFailedMessages(final Message message) {
2472		final Collection<Message> messages = new ArrayList<>();
2473		Message current = message;
2474		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2475			messages.add(current);
2476			if (current.mergeable(current.next())) {
2477				current = current.next();
2478			} else {
2479				break;
2480			}
2481		}
2482		for (final Message msg : messages) {
2483			markMessage(msg, Message.STATUS_WAITING);
2484			this.resendMessage(msg);
2485		}
2486	}
2487
2488	public void clearConversationHistory(final Conversation conversation) {
2489		conversation.clearMessages();
2490		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2491		new Thread(new Runnable() {
2492			@Override
2493			public void run() {
2494				databaseBackend.deleteMessagesInConversation(conversation);
2495			}
2496		}).start();
2497	}
2498
2499	public void sendBlockRequest(final Blockable blockable) {
2500		if (blockable != null && blockable.getBlockedJid() != null) {
2501			final Jid jid = blockable.getBlockedJid();
2502			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2503
2504				@Override
2505				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2506					if (packet.getType() == IqPacket.TYPE.RESULT) {
2507						account.getBlocklist().add(jid);
2508						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2509					}
2510				}
2511			});
2512		}
2513	}
2514
2515	public void sendUnblockRequest(final Blockable blockable) {
2516		if (blockable != null && blockable.getJid() != null) {
2517			final Jid jid = blockable.getBlockedJid();
2518			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2519				@Override
2520				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2521					if (packet.getType() == IqPacket.TYPE.RESULT) {
2522						account.getBlocklist().remove(jid);
2523						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2524					}
2525				}
2526			});
2527		}
2528	}
2529
2530	public interface OnMoreMessagesLoaded {
2531		public void onMoreMessagesLoaded(int count, Conversation conversation);
2532
2533		public void informUser(int r);
2534	}
2535
2536	public interface OnAccountPasswordChanged {
2537		public void onPasswordChangeSucceeded();
2538
2539		public void onPasswordChangeFailed();
2540	}
2541
2542	public interface OnAffiliationChanged {
2543		public void onAffiliationChangedSuccessful(Jid jid);
2544
2545		public void onAffiliationChangeFailed(Jid jid, int resId);
2546	}
2547
2548	public interface OnRoleChanged {
2549		public void onRoleChangedSuccessful(String nick);
2550
2551		public void onRoleChangeFailed(String nick, int resid);
2552	}
2553
2554	public interface OnConversationUpdate {
2555		public void onConversationUpdate();
2556	}
2557
2558	public interface OnAccountUpdate {
2559		public void onAccountUpdate();
2560	}
2561
2562	public interface OnRosterUpdate {
2563		public void onRosterUpdate();
2564	}
2565
2566	public interface OnMucRosterUpdate {
2567		public void onMucRosterUpdate();
2568	}
2569
2570	public interface OnConferenceOptionsPushed {
2571		public void onPushSucceeded();
2572
2573		public void onPushFailed();
2574	}
2575
2576	public interface OnShowErrorToast {
2577		void onShowErrorToast(int resId);
2578	}
2579
2580	public class XmppConnectionBinder extends Binder {
2581		public XmppConnectionService getService() {
2582			return XmppConnectionService.this;
2583		}
2584	}
2585}