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