ConversationActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.annotation.SuppressLint;
   4import android.app.ActionBar;
   5import android.app.AlertDialog;
   6import android.app.FragmentTransaction;
   7import android.app.PendingIntent;
   8import android.content.ActivityNotFoundException;
   9import android.content.ClipData;
  10import android.content.DialogInterface;
  11import android.content.DialogInterface.OnClickListener;
  12import android.content.Intent;
  13import android.content.IntentSender.SendIntentException;
  14import android.content.pm.PackageManager;
  15import android.net.Uri;
  16import android.os.Build;
  17import android.os.Bundle;
  18import android.os.Handler;
  19import android.provider.MediaStore;
  20import android.provider.Settings;
  21import android.support.v4.widget.SlidingPaneLayout;
  22import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
  23import android.util.Log;
  24import android.util.Pair;
  25import android.view.Gravity;
  26import android.view.KeyEvent;
  27import android.view.Menu;
  28import android.view.MenuItem;
  29import android.view.Surface;
  30import android.view.View;
  31import android.widget.AdapterView;
  32import android.widget.AdapterView.OnItemClickListener;
  33import android.widget.ArrayAdapter;
  34import android.widget.CheckBox;
  35import android.widget.PopupMenu;
  36import android.widget.PopupMenu.OnMenuItemClickListener;
  37import android.widget.Toast;
  38
  39import net.java.otr4j.session.SessionStatus;
  40
  41import org.openintents.openpgp.util.OpenPgpApi;
  42
  43import java.util.ArrayList;
  44import java.util.Iterator;
  45import java.util.List;
  46import java.util.concurrent.atomic.AtomicBoolean;
  47
  48import de.timroes.android.listview.EnhancedListView;
  49import eu.siacs.conversations.Config;
  50import eu.siacs.conversations.R;
  51import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  52import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  53import eu.siacs.conversations.entities.Account;
  54import eu.siacs.conversations.entities.Blockable;
  55import eu.siacs.conversations.entities.Contact;
  56import eu.siacs.conversations.entities.Conversation;
  57import eu.siacs.conversations.entities.Message;
  58import eu.siacs.conversations.entities.Transferable;
  59import eu.siacs.conversations.persistance.FileBackend;
  60import eu.siacs.conversations.services.XmppConnectionService;
  61import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
  62import eu.siacs.conversations.services.XmppConnectionService.OnConversationUpdate;
  63import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
  64import eu.siacs.conversations.ui.adapter.ConversationAdapter;
  65import eu.siacs.conversations.utils.ExceptionHelper;
  66import eu.siacs.conversations.utils.UIHelper;
  67import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  68import eu.siacs.conversations.xmpp.XmppConnection;
  69import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  70import eu.siacs.conversations.xmpp.jid.Jid;
  71
  72public class ConversationActivity extends XmppActivity
  73	implements OnAccountUpdate, OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast {
  74
  75	public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
  76	public static final String CONVERSATION = "conversationUuid";
  77	public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
  78	public static final String TEXT = "text";
  79	public static final String NICK = "nick";
  80	public static final String PRIVATE_MESSAGE = "pm";
  81
  82	public static final int REQUEST_SEND_MESSAGE = 0x0201;
  83	public static final int REQUEST_DECRYPT_PGP = 0x0202;
  84	public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
  85	public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
  86	public static final int REQUEST_TRUST_KEYS_MENU = 0x0209;
  87	public static final int REQUEST_START_DOWNLOAD = 0x0210;
  88	public static final int REQUEST_ADD_EDITOR_CONTENT = 0x0211;
  89	public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
  90	public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
  91	public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
  92	public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
  93	public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
  94	public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
  95	private static final String STATE_OPEN_CONVERSATION = "state_open_conversation";
  96	private static final String STATE_PANEL_OPEN = "state_panel_open";
  97	private static final String STATE_PENDING_URI = "state_pending_uri";
  98	private static final String STATE_FIRST_VISIBLE = "first_visible";
  99	private static final String STATE_OFFSET_FROM_TOP = "offset_from_top";
 100
 101	private String mOpenConversation = null;
 102	private boolean mPanelOpen = true;
 103	private AtomicBoolean mShouldPanelBeOpen = new AtomicBoolean(false);
 104	private Pair<Integer,Integer> mScrollPosition = null;
 105	final private List<Uri> mPendingImageUris = new ArrayList<>();
 106	final private List<Uri> mPendingFileUris = new ArrayList<>();
 107	private Uri mPendingGeoUri = null;
 108	private boolean forbidProcessingPendings = false;
 109	private Message mPendingDownloadableMessage = null;
 110
 111	private boolean conversationWasSelectedByKeyboard = false;
 112
 113	private View mContentView;
 114
 115	private List<Conversation> conversationList = new ArrayList<>();
 116	private Conversation swipedConversation = null;
 117	private Conversation mSelectedConversation = null;
 118	private EnhancedListView listView;
 119	private ConversationFragment mConversationFragment;
 120
 121	private ArrayAdapter<Conversation> listAdapter;
 122
 123	private boolean mActivityPaused = false;
 124	private AtomicBoolean mRedirected = new AtomicBoolean(false);
 125	private Pair<Integer, Intent> mPostponedActivityResult;
 126	private boolean mUnprocessedNewIntent = false;
 127	public Uri mPendingEditorContent = null;
 128
 129	public Conversation getSelectedConversation() {
 130		return this.mSelectedConversation;
 131	}
 132
 133	public void setSelectedConversation(Conversation conversation) {
 134		this.mSelectedConversation = conversation;
 135	}
 136
 137	public void showConversationsOverview() {
 138		if (mContentView instanceof SlidingPaneLayout) {
 139			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 140			mShouldPanelBeOpen.set(true);
 141			mSlidingPaneLayout.openPane();
 142		}
 143	}
 144
 145	@Override
 146	protected String getShareableUri() {
 147		Conversation conversation = getSelectedConversation();
 148		if (conversation != null) {
 149			return conversation.getAccount().getShareableUri();
 150		} else {
 151			return "";
 152		}
 153	}
 154
 155	public void hideConversationsOverview() {
 156		if (mContentView instanceof SlidingPaneLayout) {
 157			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 158			mShouldPanelBeOpen.set(false);
 159			mSlidingPaneLayout.closePane();
 160		}
 161	}
 162
 163	public boolean isConversationsOverviewHideable() {
 164		return mContentView instanceof SlidingPaneLayout;
 165	}
 166
 167	public boolean isConversationsOverviewVisable() {
 168		if (mContentView instanceof SlidingPaneLayout) {
 169			return mShouldPanelBeOpen.get();
 170		} else {
 171			return true;
 172		}
 173	}
 174
 175	@Override
 176	protected void onCreate(final Bundle savedInstanceState) {
 177		super.onCreate(savedInstanceState);
 178		if (savedInstanceState != null) {
 179			mOpenConversation = savedInstanceState.getString(STATE_OPEN_CONVERSATION, null);
 180			mPanelOpen = savedInstanceState.getBoolean(STATE_PANEL_OPEN, true);
 181			int pos = savedInstanceState.getInt(STATE_FIRST_VISIBLE, -1);
 182			int offset = savedInstanceState.getInt(STATE_OFFSET_FROM_TOP, 1);
 183			if (pos >= 0 && offset <= 0) {
 184				Log.d(Config.LOGTAG,"retrieved scroll position from instanceState "+pos+":"+offset);
 185				mScrollPosition = new Pair<>(pos,offset);
 186			} else {
 187				mScrollPosition = null;
 188			}
 189			String pending = savedInstanceState.getString(STATE_PENDING_URI, null);
 190			if (pending != null) {
 191				Log.d(Config.LOGTAG,"ConversationsActivity.onCreate() - restoring pending image uri");
 192				mPendingImageUris.clear();
 193				mPendingImageUris.add(Uri.parse(pending));
 194			}
 195		}
 196
 197		setContentView(R.layout.fragment_conversations_overview);
 198
 199		this.mConversationFragment = new ConversationFragment();
 200		FragmentTransaction transaction = getFragmentManager().beginTransaction();
 201		transaction.replace(R.id.selected_conversation, this.mConversationFragment, "conversation");
 202		transaction.commit();
 203
 204		listView = (EnhancedListView) findViewById(R.id.list);
 205		this.listAdapter = new ConversationAdapter(this, conversationList);
 206		listView.setAdapter(this.listAdapter);
 207
 208		final ActionBar actionBar = getActionBar();
 209		if (actionBar != null) {
 210			actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
 211		}
 212
 213		listView.setOnItemClickListener(new OnItemClickListener() {
 214
 215			@Override
 216			public void onItemClick(AdapterView<?> arg0, View clickedView,
 217									int position, long arg3) {
 218				if (getSelectedConversation() != conversationList.get(position)) {
 219					setSelectedConversation(conversationList.get(position));
 220					ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 221					conversationWasSelectedByKeyboard = false;
 222				}
 223				hideConversationsOverview();
 224				openConversation();
 225			}
 226		});
 227
 228		listView.setDismissCallback(new EnhancedListView.OnDismissCallback() {
 229
 230			@Override
 231			public EnhancedListView.Undoable onDismiss(final EnhancedListView enhancedListView, final int position) {
 232
 233				final int index = listView.getFirstVisiblePosition();
 234				View v = listView.getChildAt(0);
 235				final int top = (v == null) ? 0 : (v.getTop() - listView.getPaddingTop());
 236
 237				try {
 238					swipedConversation = listAdapter.getItem(position);
 239				} catch (IndexOutOfBoundsException e) {
 240					return null;
 241				}
 242				listAdapter.remove(swipedConversation);
 243				xmppConnectionService.markRead(swipedConversation);
 244
 245				final boolean formerlySelected = (getSelectedConversation() == swipedConversation);
 246				if (position == 0 && listAdapter.getCount() == 0) {
 247					endConversation(swipedConversation, false, true);
 248					return null;
 249				} else if (formerlySelected) {
 250					setSelectedConversation(listAdapter.getItem(0));
 251					ConversationActivity.this.mConversationFragment
 252							.reInit(getSelectedConversation());
 253				}
 254
 255				return new EnhancedListView.Undoable() {
 256
 257					@Override
 258					public void undo() {
 259						listAdapter.insert(swipedConversation, position);
 260						if (formerlySelected) {
 261							setSelectedConversation(swipedConversation);
 262							ConversationActivity.this.mConversationFragment
 263									.reInit(getSelectedConversation());
 264						}
 265						swipedConversation = null;
 266						listView.setSelectionFromTop(index + (listView.getChildCount() < position ? 1 : 0), top);
 267					}
 268
 269					@Override
 270					public void discard() {
 271						if (!swipedConversation.isRead()
 272								&& swipedConversation.getMode() == Conversation.MODE_SINGLE) {
 273							swipedConversation = null;
 274							return;
 275						}
 276						endConversation(swipedConversation, false, false);
 277						swipedConversation = null;
 278					}
 279
 280					@Override
 281					public String getTitle() {
 282						if (swipedConversation.getMode() == Conversation.MODE_MULTI) {
 283							return getResources().getString(R.string.title_undo_swipe_out_muc);
 284						} else {
 285							return getResources().getString(R.string.title_undo_swipe_out_conversation);
 286						}
 287					}
 288				};
 289			}
 290		});
 291		listView.enableSwipeToDismiss();
 292		listView.setSwipingLayout(R.id.swipeable_item);
 293		listView.setUndoStyle(EnhancedListView.UndoStyle.SINGLE_POPUP);
 294		listView.setUndoHideDelay(5000);
 295		listView.setRequireTouchBeforeDismiss(false);
 296
 297		mContentView = findViewById(R.id.content_view_spl);
 298		if (mContentView == null) {
 299			mContentView = findViewById(R.id.content_view_ll);
 300		}
 301		if (mContentView instanceof SlidingPaneLayout) {
 302			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 303			mSlidingPaneLayout.setShadowResource(R.drawable.es_slidingpane_shadow);
 304			mSlidingPaneLayout.setSliderFadeColor(0);
 305			mSlidingPaneLayout.setPanelSlideListener(new PanelSlideListener() {
 306
 307				@Override
 308				public void onPanelOpened(View arg0) {
 309					mShouldPanelBeOpen.set(true);
 310					updateActionBarTitle();
 311					invalidateOptionsMenu();
 312					hideKeyboard();
 313					if (xmppConnectionServiceBound) {
 314						xmppConnectionService.getNotificationService().setOpenConversation(null);
 315					}
 316					closeContextMenu();
 317				}
 318
 319				@Override
 320				public void onPanelClosed(View arg0) {
 321					mShouldPanelBeOpen.set(false);
 322					listView.discardUndo();
 323					openConversation();
 324				}
 325
 326				@Override
 327				public void onPanelSlide(View arg0, float arg1) {
 328					// TODO Auto-generated method stub
 329
 330				}
 331			});
 332		}
 333	}
 334
 335	@Override
 336	public void switchToConversation(Conversation conversation) {
 337		setSelectedConversation(conversation);
 338		runOnUiThread(new Runnable() {
 339			@Override
 340			public void run() {
 341				ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 342				openConversation();
 343			}
 344		});
 345	}
 346
 347	private void updateActionBarTitle() {
 348		updateActionBarTitle(isConversationsOverviewHideable() && !isConversationsOverviewVisable());
 349	}
 350
 351	private void updateActionBarTitle(boolean titleShouldBeName) {
 352		final ActionBar ab = getActionBar();
 353		final Conversation conversation = getSelectedConversation();
 354		if (ab != null) {
 355			if (titleShouldBeName && conversation != null) {
 356				if ((ab.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != ActionBar.DISPLAY_HOME_AS_UP) {
 357					ab.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE);
 358				}
 359				if (conversation.getMode() == Conversation.MODE_SINGLE || useSubjectToIdentifyConference()) {
 360					ab.setTitle(conversation.getName());
 361				} else {
 362					ab.setTitle(conversation.getJid().toBareJid().toString());
 363				}
 364			} else {
 365				if ((ab.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) == ActionBar.DISPLAY_HOME_AS_UP) {
 366					ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
 367				}
 368				ab.setTitle(R.string.app_name);
 369			}
 370		}
 371	}
 372
 373	private void openConversation() {
 374		this.updateActionBarTitle();
 375		this.invalidateOptionsMenu();
 376		if (xmppConnectionServiceBound) {
 377			final Conversation conversation = getSelectedConversation();
 378			xmppConnectionService.getNotificationService().setOpenConversation(conversation);
 379			sendReadMarkerIfNecessary(conversation);
 380		}
 381		listAdapter.notifyDataSetChanged();
 382	}
 383
 384	public void sendReadMarkerIfNecessary(final Conversation conversation) {
 385		if (!mActivityPaused && !mUnprocessedNewIntent && conversation != null) {
 386			xmppConnectionService.sendReadMarker(conversation);
 387		}
 388	}
 389
 390	@Override
 391	public boolean onCreateOptionsMenu(Menu menu) {
 392		getMenuInflater().inflate(R.menu.conversations, menu);
 393		final MenuItem menuSecure = menu.findItem(R.id.action_security);
 394		final MenuItem menuArchive = menu.findItem(R.id.action_archive);
 395		final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
 396		final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
 397		final MenuItem menuAttach = menu.findItem(R.id.action_attach_file);
 398		final MenuItem menuClearHistory = menu.findItem(R.id.action_clear_history);
 399		final MenuItem menuAdd = menu.findItem(R.id.action_add);
 400		final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
 401		final MenuItem menuMute = menu.findItem(R.id.action_mute);
 402		final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
 403
 404		if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
 405			menuArchive.setVisible(false);
 406			menuMucDetails.setVisible(false);
 407			menuContactDetails.setVisible(false);
 408			menuSecure.setVisible(false);
 409			menuInviteContact.setVisible(false);
 410			menuAttach.setVisible(false);
 411			menuClearHistory.setVisible(false);
 412			menuMute.setVisible(false);
 413			menuUnmute.setVisible(false);
 414		} else {
 415			menuAdd.setVisible(!isConversationsOverviewHideable());
 416			if (this.getSelectedConversation() != null) {
 417				if (this.getSelectedConversation().getNextEncryption() != Message.ENCRYPTION_NONE) {
 418					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 419						menuSecure.setIcon(R.drawable.ic_lock_white_24dp);
 420					} else {
 421						menuSecure.setIcon(R.drawable.ic_action_secure);
 422					}
 423				}
 424				if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
 425					menuContactDetails.setVisible(false);
 426					menuAttach.setVisible(getSelectedConversation().getAccount().httpUploadAvailable() && getSelectedConversation().getMucOptions().participating());
 427					menuInviteContact.setVisible(getSelectedConversation().getMucOptions().canInvite());
 428					menuSecure.setVisible((Config.supportOpenPgp() || Config.supportOmemo()) && Config.multipleEncryptionChoices()); //only if pgp is supported we have a choice
 429				} else {
 430					menuContactDetails.setVisible(!this.getSelectedConversation().withSelf());
 431					menuMucDetails.setVisible(false);
 432					menuSecure.setVisible(Config.multipleEncryptionChoices());
 433					menuInviteContact.setVisible(xmppConnectionService != null && xmppConnectionService.findConferenceServer(getSelectedConversation().getAccount()) != null);
 434				}
 435				if (this.getSelectedConversation().isMuted()) {
 436					menuMute.setVisible(false);
 437				} else {
 438					menuUnmute.setVisible(false);
 439				}
 440			}
 441		}
 442		if (Config.supportOmemo()) {
 443			new Handler().post(new Runnable() {
 444				@Override
 445				public void run() {
 446					View view = findViewById(R.id.action_security);
 447					if (view != null) {
 448						view.setOnLongClickListener(new View.OnLongClickListener() {
 449							@Override
 450							public boolean onLongClick(View v) {
 451								return quickOmemoDebugger(getSelectedConversation());
 452							}
 453						});
 454					}
 455				}
 456			});
 457		}
 458		return super.onCreateOptionsMenu(menu);
 459	}
 460
 461	private boolean quickOmemoDebugger(Conversation c) {
 462		if (c != null) {
 463			boolean single = c.getMode() == Conversation.MODE_SINGLE;
 464			AxolotlService axolotlService = c.getAccount().getAxolotlService();
 465			Pair<AxolotlService.AxolotlCapability,Jid> capabilityJidPair = axolotlService.isConversationAxolotlCapableDetailed(c);
 466			switch (capabilityJidPair.first) {
 467				case MISSING_PRESENCE:
 468					Toast.makeText(ConversationActivity.this,single ? getString(R.string.missing_presence_subscription) : getString(R.string.missing_presence_subscription_with_x,capabilityJidPair.second.toBareJid().toString()),Toast.LENGTH_SHORT).show();
 469					return true;
 470				case MISSING_KEYS:
 471					Toast.makeText(ConversationActivity.this,single ? getString(R.string.missing_omemo_keys) : getString(R.string.missing_keys_from_x,capabilityJidPair.second.toBareJid().toString()),Toast.LENGTH_SHORT).show();
 472					return true;
 473				case WRONG_CONFIGURATION:
 474					Toast.makeText(ConversationActivity.this,R.string.wrong_conference_configuration, Toast.LENGTH_SHORT).show();
 475					return true;
 476				case NO_MEMBERS:
 477					Toast.makeText(ConversationActivity.this,R.string.this_conference_has_no_members, Toast.LENGTH_SHORT).show();
 478					return true;
 479			}
 480		}
 481		return false;
 482	}
 483
 484	protected void selectPresenceToAttachFile(final int attachmentChoice, final int encryption) {
 485		final Conversation conversation = getSelectedConversation();
 486		final Account account = conversation.getAccount();
 487		final OnPresenceSelected callback = new OnPresenceSelected() {
 488
 489			@Override
 490			public void onPresenceSelected() {
 491				Intent intent = new Intent();
 492				boolean chooser = false;
 493				String fallbackPackageId = null;
 494				switch (attachmentChoice) {
 495					case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 496						intent.setAction(Intent.ACTION_GET_CONTENT);
 497						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
 498							intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
 499						}
 500						intent.setType("image/*");
 501						chooser = true;
 502						break;
 503					case ATTACHMENT_CHOICE_TAKE_PHOTO:
 504						Uri uri = xmppConnectionService.getFileBackend().getTakePhotoUri();
 505						intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
 506						intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 507						intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
 508						intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
 509						mPendingImageUris.clear();
 510						mPendingImageUris.add(uri);
 511						break;
 512					case ATTACHMENT_CHOICE_CHOOSE_FILE:
 513						chooser = true;
 514						intent.setType("*/*");
 515						intent.addCategory(Intent.CATEGORY_OPENABLE);
 516						intent.setAction(Intent.ACTION_GET_CONTENT);
 517						break;
 518					case ATTACHMENT_CHOICE_RECORD_VOICE:
 519						intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
 520						fallbackPackageId = "eu.siacs.conversations.voicerecorder";
 521						break;
 522					case ATTACHMENT_CHOICE_LOCATION:
 523						intent.setAction("eu.siacs.conversations.location.request");
 524						fallbackPackageId = "eu.siacs.conversations.sharelocation";
 525						break;
 526				}
 527				if (intent.resolveActivity(getPackageManager()) != null) {
 528					if (chooser) {
 529						startActivityForResult(
 530								Intent.createChooser(intent, getString(R.string.perform_action_with)),
 531								attachmentChoice);
 532					} else {
 533						startActivityForResult(intent, attachmentChoice);
 534					}
 535				} else if (fallbackPackageId != null) {
 536					startActivity(getInstallApkIntent(fallbackPackageId));
 537				}
 538			}
 539		};
 540		if ((account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) && encryption != Message.ENCRYPTION_OTR) {
 541			conversation.setNextCounterpart(null);
 542			callback.onPresenceSelected();
 543		} else {
 544			selectPresence(conversation, callback);
 545		}
 546	}
 547
 548	private Intent getInstallApkIntent(final String packageId) {
 549		Intent intent = new Intent(Intent.ACTION_VIEW);
 550		intent.setData(Uri.parse("market://details?id=" + packageId));
 551		if (intent.resolveActivity(getPackageManager()) != null) {
 552			return intent;
 553		} else {
 554			intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
 555			return intent;
 556		}
 557	}
 558
 559	public void attachFile(final int attachmentChoice) {
 560		if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
 561			if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(attachmentChoice)) {
 562				return;
 563			}
 564		}
 565		switch (attachmentChoice) {
 566			case ATTACHMENT_CHOICE_LOCATION:
 567				getPreferences().edit().putString("recently_used_quick_action", "location").apply();
 568				break;
 569			case ATTACHMENT_CHOICE_RECORD_VOICE:
 570				getPreferences().edit().putString("recently_used_quick_action", "voice").apply();
 571				break;
 572			case ATTACHMENT_CHOICE_TAKE_PHOTO:
 573				getPreferences().edit().putString("recently_used_quick_action", "photo").apply();
 574				break;
 575			case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 576				getPreferences().edit().putString("recently_used_quick_action", "picture").apply();
 577				break;
 578		}
 579		final Conversation conversation = getSelectedConversation();
 580		final int encryption = conversation.getNextEncryption();
 581		final int mode = conversation.getMode();
 582		if (encryption == Message.ENCRYPTION_PGP) {
 583			if (hasPgp()) {
 584				if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
 585					xmppConnectionService.getPgpEngine().hasKey(
 586							conversation.getContact(),
 587							new UiCallback<Contact>() {
 588
 589								@Override
 590								public void userInputRequried(PendingIntent pi, Contact contact) {
 591									ConversationActivity.this.runIntent(pi, attachmentChoice);
 592								}
 593
 594								@Override
 595								public void success(Contact contact) {
 596									selectPresenceToAttachFile(attachmentChoice, encryption);
 597								}
 598
 599								@Override
 600								public void error(int error, Contact contact) {
 601									replaceToast(getString(error));
 602								}
 603							});
 604				} else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
 605					if (!conversation.getMucOptions().everybodyHasKeys()) {
 606						Toast warning = Toast
 607								.makeText(this,
 608										R.string.missing_public_keys,
 609										Toast.LENGTH_LONG);
 610						warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
 611						warning.show();
 612					}
 613					selectPresenceToAttachFile(attachmentChoice, encryption);
 614				} else {
 615					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 616							.findFragmentByTag("conversation");
 617					if (fragment != null) {
 618						fragment.showNoPGPKeyDialog(false,
 619								new OnClickListener() {
 620
 621									@Override
 622									public void onClick(DialogInterface dialog,
 623														int which) {
 624										conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 625										xmppConnectionService.updateConversation(conversation);
 626										selectPresenceToAttachFile(attachmentChoice, Message.ENCRYPTION_NONE);
 627									}
 628								});
 629					}
 630				}
 631			} else {
 632				showInstallPgpDialog();
 633			}
 634		} else {
 635			if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
 636				selectPresenceToAttachFile(attachmentChoice, encryption);
 637			}
 638		}
 639	}
 640
 641	@Override
 642	public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
 643		if (grantResults.length > 0)
 644			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 645				if (requestCode == REQUEST_START_DOWNLOAD) {
 646					if (this.mPendingDownloadableMessage != null) {
 647						startDownloadable(this.mPendingDownloadableMessage);
 648					}
 649				} else if (requestCode == REQUEST_ADD_EDITOR_CONTENT) {
 650					if (this.mPendingEditorContent != null) {
 651						attachImageToConversation(this.mPendingEditorContent);
 652					}
 653				} else {
 654					attachFile(requestCode);
 655				}
 656			} else {
 657				Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
 658			}
 659	}
 660
 661	public void startDownloadable(Message message) {
 662		if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(ConversationActivity.REQUEST_START_DOWNLOAD)) {
 663			this.mPendingDownloadableMessage = message;
 664			return;
 665		}
 666		Transferable transferable = message.getTransferable();
 667		if (transferable != null) {
 668			if (!transferable.start()) {
 669				Toast.makeText(this, R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
 670			}
 671		} else if (message.treatAsDownloadable()) {
 672			xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
 673		}
 674	}
 675
 676	@Override
 677	public boolean onOptionsItemSelected(final MenuItem item) {
 678		if (item.getItemId() == android.R.id.home) {
 679			showConversationsOverview();
 680			return true;
 681		} else if (item.getItemId() == R.id.action_add) {
 682			startActivity(new Intent(this, StartConversationActivity.class));
 683			return true;
 684		} else if (getSelectedConversation() != null) {
 685			switch (item.getItemId()) {
 686				case R.id.action_attach_file:
 687					attachFileDialog();
 688					break;
 689				case R.id.action_archive:
 690					this.endConversation(getSelectedConversation());
 691					break;
 692				case R.id.action_contact_details:
 693					switchToContactDetails(getSelectedConversation().getContact());
 694					break;
 695				case R.id.action_muc_details:
 696					Intent intent = new Intent(this,
 697							ConferenceDetailsActivity.class);
 698					intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 699					intent.putExtra("uuid", getSelectedConversation().getUuid());
 700					startActivity(intent);
 701					break;
 702				case R.id.action_invite:
 703					inviteToConversation(getSelectedConversation());
 704					break;
 705				case R.id.action_security:
 706					selectEncryptionDialog(getSelectedConversation());
 707					break;
 708				case R.id.action_clear_history:
 709					clearHistoryDialog(getSelectedConversation());
 710					break;
 711				case R.id.action_mute:
 712					muteConversationDialog(getSelectedConversation());
 713					break;
 714				case R.id.action_unmute:
 715					unmuteConversation(getSelectedConversation());
 716					break;
 717				case R.id.action_block:
 718					BlockContactDialog.show(this, getSelectedConversation());
 719					break;
 720				case R.id.action_unblock:
 721					BlockContactDialog.show(this, getSelectedConversation());
 722					break;
 723				default:
 724					break;
 725			}
 726			return super.onOptionsItemSelected(item);
 727		} else {
 728			return super.onOptionsItemSelected(item);
 729		}
 730	}
 731
 732	public void endConversation(Conversation conversation) {
 733		endConversation(conversation, true, true);
 734	}
 735
 736	public void endConversation(Conversation conversation, boolean showOverview, boolean reinit) {
 737		if (showOverview) {
 738			showConversationsOverview();
 739		}
 740		xmppConnectionService.archiveConversation(conversation);
 741		if (reinit) {
 742			if (conversationList.size() > 0) {
 743				setSelectedConversation(conversationList.get(0));
 744				this.mConversationFragment.reInit(getSelectedConversation());
 745			} else {
 746				setSelectedConversation(null);
 747				if (mRedirected.compareAndSet(false, true)) {
 748					Intent intent = new Intent(this, StartConversationActivity.class);
 749					intent.putExtra("init", true);
 750					startActivity(intent);
 751					finish();
 752				}
 753			}
 754		}
 755	}
 756
 757	@SuppressLint("InflateParams")
 758	protected void clearHistoryDialog(final Conversation conversation) {
 759		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 760		builder.setTitle(getString(R.string.clear_conversation_history));
 761		View dialogView = getLayoutInflater().inflate(
 762				R.layout.dialog_clear_history, null);
 763		final CheckBox endConversationCheckBox = (CheckBox) dialogView
 764				.findViewById(R.id.end_conversation_checkbox);
 765		builder.setView(dialogView);
 766		builder.setNegativeButton(getString(R.string.cancel), null);
 767		builder.setPositiveButton(getString(R.string.delete_messages),
 768				new OnClickListener() {
 769
 770					@Override
 771					public void onClick(DialogInterface dialog, int which) {
 772						ConversationActivity.this.xmppConnectionService.clearConversationHistory(conversation);
 773						if (endConversationCheckBox.isChecked()) {
 774							endConversation(conversation);
 775						} else {
 776							updateConversationList();
 777							ConversationActivity.this.mConversationFragment.updateMessages();
 778						}
 779					}
 780				});
 781		builder.create().show();
 782	}
 783
 784	protected void attachFileDialog() {
 785		View menuAttachFile = findViewById(R.id.action_attach_file);
 786		if (menuAttachFile == null) {
 787			return;
 788		}
 789		PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
 790		attachFilePopup.inflate(R.menu.attachment_choices);
 791		if (new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION).resolveActivity(getPackageManager()) == null) {
 792			attachFilePopup.getMenu().findItem(R.id.attach_record_voice).setVisible(false);
 793		}
 794		if (new Intent("eu.siacs.conversations.location.request").resolveActivity(getPackageManager()) == null) {
 795			attachFilePopup.getMenu().findItem(R.id.attach_location).setVisible(false);
 796		}
 797		attachFilePopup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 798
 799			@Override
 800			public boolean onMenuItemClick(MenuItem item) {
 801				switch (item.getItemId()) {
 802					case R.id.attach_choose_picture:
 803						attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 804						break;
 805					case R.id.attach_take_picture:
 806						attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
 807						break;
 808					case R.id.attach_choose_file:
 809						attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
 810						break;
 811					case R.id.attach_record_voice:
 812						attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
 813						break;
 814					case R.id.attach_location:
 815						attachFile(ATTACHMENT_CHOICE_LOCATION);
 816						break;
 817				}
 818				return false;
 819			}
 820		});
 821		UIHelper.showIconsInPopup(attachFilePopup);
 822		attachFilePopup.show();
 823	}
 824
 825	public void verifyOtrSessionDialog(final Conversation conversation, View view) {
 826		if (!conversation.hasValidOtrSession() || conversation.getOtrSession().getSessionStatus() != SessionStatus.ENCRYPTED) {
 827			Toast.makeText(this, R.string.otr_session_not_started, Toast.LENGTH_LONG).show();
 828			return;
 829		}
 830		if (view == null) {
 831			return;
 832		}
 833		PopupMenu popup = new PopupMenu(this, view);
 834		popup.inflate(R.menu.verification_choices);
 835		popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 836			@Override
 837			public boolean onMenuItemClick(MenuItem menuItem) {
 838				Intent intent = new Intent(ConversationActivity.this, VerifyOTRActivity.class);
 839				intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
 840				intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
 841				intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
 842				switch (menuItem.getItemId()) {
 843					case R.id.scan_fingerprint:
 844						intent.putExtra("mode", VerifyOTRActivity.MODE_SCAN_FINGERPRINT);
 845						break;
 846					case R.id.ask_question:
 847						intent.putExtra("mode", VerifyOTRActivity.MODE_ASK_QUESTION);
 848						break;
 849					case R.id.manual_verification:
 850						intent.putExtra("mode", VerifyOTRActivity.MODE_MANUAL_VERIFICATION);
 851						break;
 852				}
 853				startActivity(intent);
 854				return true;
 855			}
 856		});
 857		popup.show();
 858	}
 859
 860	protected void selectEncryptionDialog(final Conversation conversation) {
 861		View menuItemView = findViewById(R.id.action_security);
 862		if (menuItemView == null) {
 863			return;
 864		}
 865		PopupMenu popup = new PopupMenu(this, menuItemView);
 866		final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 867				.findFragmentByTag("conversation");
 868		if (fragment != null) {
 869			popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 870
 871				@Override
 872				public boolean onMenuItemClick(MenuItem item) {
 873					switch (item.getItemId()) {
 874						case R.id.encryption_choice_none:
 875							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 876							item.setChecked(true);
 877							break;
 878						case R.id.encryption_choice_otr:
 879							conversation.setNextEncryption(Message.ENCRYPTION_OTR);
 880							item.setChecked(true);
 881							break;
 882						case R.id.encryption_choice_pgp:
 883							if (hasPgp()) {
 884								if (conversation.getAccount().getPgpSignature() != null) {
 885									conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 886									item.setChecked(true);
 887								} else {
 888									announcePgp(conversation.getAccount(), conversation, onOpenPGPKeyPublished);
 889								}
 890							} else {
 891								showInstallPgpDialog();
 892							}
 893							break;
 894						case R.id.encryption_choice_axolotl:
 895							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
 896									+ "Enabled axolotl for Contact " + conversation.getContact().getJid());
 897							conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
 898							item.setChecked(true);
 899							break;
 900						default:
 901							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 902							break;
 903					}
 904					xmppConnectionService.updateConversation(conversation);
 905					fragment.updateChatMsgHint();
 906					invalidateOptionsMenu();
 907					refreshUi();
 908					return true;
 909				}
 910			});
 911			popup.inflate(R.menu.encryption_choices);
 912			MenuItem otr = popup.getMenu().findItem(R.id.encryption_choice_otr);
 913			MenuItem none = popup.getMenu().findItem(R.id.encryption_choice_none);
 914			MenuItem pgp = popup.getMenu().findItem(R.id.encryption_choice_pgp);
 915			MenuItem axolotl = popup.getMenu().findItem(R.id.encryption_choice_axolotl);
 916			pgp.setVisible(Config.supportOpenPgp());
 917			none.setVisible(Config.supportUnencrypted() || conversation.getMode() == Conversation.MODE_MULTI);
 918			otr.setVisible(Config.supportOtr());
 919			axolotl.setVisible(Config.supportOmemo());
 920			if (conversation.getMode() == Conversation.MODE_MULTI) {
 921				otr.setVisible(false);
 922			}
 923			if (!conversation.getAccount().getAxolotlService().isConversationAxolotlCapable(conversation)) {
 924				axolotl.setEnabled(false);
 925			}
 926			switch (conversation.getNextEncryption()) {
 927				case Message.ENCRYPTION_NONE:
 928					none.setChecked(true);
 929					break;
 930				case Message.ENCRYPTION_OTR:
 931					otr.setChecked(true);
 932					break;
 933				case Message.ENCRYPTION_PGP:
 934					pgp.setChecked(true);
 935					break;
 936				case Message.ENCRYPTION_AXOLOTL:
 937					axolotl.setChecked(true);
 938					break;
 939				default:
 940					none.setChecked(true);
 941					break;
 942			}
 943			popup.show();
 944		}
 945	}
 946
 947	protected void muteConversationDialog(final Conversation conversation) {
 948		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 949		builder.setTitle(R.string.disable_notifications);
 950		final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
 951		builder.setItems(R.array.mute_options_descriptions,
 952				new OnClickListener() {
 953
 954					@Override
 955					public void onClick(final DialogInterface dialog, final int which) {
 956						final long till;
 957						if (durations[which] == -1) {
 958							till = Long.MAX_VALUE;
 959						} else {
 960							till = System.currentTimeMillis() + (durations[which] * 1000);
 961						}
 962						conversation.setMutedTill(till);
 963						ConversationActivity.this.xmppConnectionService.updateConversation(conversation);
 964						updateConversationList();
 965						ConversationActivity.this.mConversationFragment.updateMessages();
 966						invalidateOptionsMenu();
 967					}
 968				});
 969		builder.create().show();
 970	}
 971
 972	public void unmuteConversation(final Conversation conversation) {
 973		conversation.setMutedTill(0);
 974		this.xmppConnectionService.updateConversation(conversation);
 975		updateConversationList();
 976		ConversationActivity.this.mConversationFragment.updateMessages();
 977		invalidateOptionsMenu();
 978	}
 979
 980	@Override
 981	public void onBackPressed() {
 982		if (!isConversationsOverviewVisable()) {
 983			showConversationsOverview();
 984		} else {
 985			super.onBackPressed();
 986		}
 987	}
 988
 989	@Override
 990	public boolean onKeyUp(int key, KeyEvent event) {
 991		int rotation = getWindowManager().getDefaultDisplay().getRotation();
 992		final int upKey;
 993		final int downKey;
 994		switch (rotation) {
 995			case Surface.ROTATION_90:
 996				upKey = KeyEvent.KEYCODE_DPAD_LEFT;
 997				downKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 998				break;
 999			case Surface.ROTATION_180:
1000				upKey = KeyEvent.KEYCODE_DPAD_DOWN;
1001				downKey = KeyEvent.KEYCODE_DPAD_UP;
1002				break;
1003			case Surface.ROTATION_270:
1004				upKey = KeyEvent.KEYCODE_DPAD_RIGHT;
1005				downKey = KeyEvent.KEYCODE_DPAD_LEFT;
1006				break;
1007			case Surface.ROTATION_0:
1008			default:
1009				upKey = KeyEvent.KEYCODE_DPAD_UP;
1010				downKey = KeyEvent.KEYCODE_DPAD_DOWN;
1011		}
1012		final boolean modifier = event.isCtrlPressed() || (event.getMetaState() & KeyEvent.META_ALT_LEFT_ON) != 0;
1013		if (modifier && key == KeyEvent.KEYCODE_TAB && isConversationsOverviewHideable()) {
1014			toggleConversationsOverview();
1015			return true;
1016		} else if (modifier && key == KeyEvent.KEYCODE_SPACE) {
1017			startActivity(new Intent(this, StartConversationActivity.class));
1018			return true;
1019		} else if (modifier && key == downKey) {
1020			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1021				showConversationsOverview();
1022				;
1023			}
1024			return selectDownConversation();
1025		} else if (modifier && key == upKey) {
1026			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1027				showConversationsOverview();
1028			}
1029			return selectUpConversation();
1030		} else if (modifier && key == KeyEvent.KEYCODE_1) {
1031			return openConversationByIndex(0);
1032		} else if (modifier && key == KeyEvent.KEYCODE_2) {
1033			return openConversationByIndex(1);
1034		} else if (modifier && key == KeyEvent.KEYCODE_3) {
1035			return openConversationByIndex(2);
1036		} else if (modifier && key == KeyEvent.KEYCODE_4) {
1037			return openConversationByIndex(3);
1038		} else if (modifier && key == KeyEvent.KEYCODE_5) {
1039			return openConversationByIndex(4);
1040		} else if (modifier && key == KeyEvent.KEYCODE_6) {
1041			return openConversationByIndex(5);
1042		} else if (modifier && key == KeyEvent.KEYCODE_7) {
1043			return openConversationByIndex(6);
1044		} else if (modifier && key == KeyEvent.KEYCODE_8) {
1045			return openConversationByIndex(7);
1046		} else if (modifier && key == KeyEvent.KEYCODE_9) {
1047			return openConversationByIndex(8);
1048		} else if (modifier && key == KeyEvent.KEYCODE_0) {
1049			return openConversationByIndex(9);
1050		} else {
1051			return super.onKeyUp(key, event);
1052		}
1053	}
1054
1055	private void toggleConversationsOverview() {
1056		if (isConversationsOverviewVisable()) {
1057			hideConversationsOverview();
1058			if (mConversationFragment != null) {
1059				mConversationFragment.setFocusOnInputField();
1060			}
1061		} else {
1062			showConversationsOverview();
1063		}
1064	}
1065
1066	private boolean selectUpConversation() {
1067		if (this.mSelectedConversation != null) {
1068			int index = this.conversationList.indexOf(this.mSelectedConversation);
1069			if (index > 0) {
1070				return openConversationByIndex(index - 1);
1071			}
1072		}
1073		return false;
1074	}
1075
1076	private boolean selectDownConversation() {
1077		if (this.mSelectedConversation != null) {
1078			int index = this.conversationList.indexOf(this.mSelectedConversation);
1079			if (index != -1 && index < this.conversationList.size() - 1) {
1080				return openConversationByIndex(index + 1);
1081			}
1082		}
1083		return false;
1084	}
1085
1086	private boolean openConversationByIndex(int index) {
1087		try {
1088			this.conversationWasSelectedByKeyboard = true;
1089			setSelectedConversation(this.conversationList.get(index));
1090			this.mConversationFragment.reInit(getSelectedConversation());
1091			if (index > listView.getLastVisiblePosition() - 1 || index < listView.getFirstVisiblePosition() + 1) {
1092				this.listView.setSelection(index);
1093			}
1094			openConversation();
1095			return true;
1096		} catch (IndexOutOfBoundsException e) {
1097			return false;
1098		}
1099	}
1100
1101	@Override
1102	protected void onNewIntent(final Intent intent) {
1103		if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1104			mOpenConversation = null;
1105			mUnprocessedNewIntent = true;
1106			if (xmppConnectionServiceBound) {
1107				handleViewConversationIntent(intent);
1108				intent.setAction(Intent.ACTION_MAIN);
1109			} else {
1110				setIntent(intent);
1111			}
1112		}
1113	}
1114
1115	@Override
1116	public void onStart() {
1117		super.onStart();
1118		this.mRedirected.set(false);
1119		if (this.xmppConnectionServiceBound) {
1120			this.onBackendConnected();
1121		}
1122		if (conversationList.size() >= 1) {
1123			this.onConversationUpdate();
1124		}
1125	}
1126
1127	@Override
1128	public void onPause() {
1129		listView.discardUndo();
1130		super.onPause();
1131		this.mActivityPaused = true;
1132	}
1133
1134	@Override
1135	public void onResume() {
1136		super.onResume();
1137		final int theme = findTheme();
1138		final boolean usingEnterKey = usingEnterKey();
1139		if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
1140			recreate();
1141		}
1142		this.mActivityPaused = false;
1143
1144
1145		if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
1146			sendReadMarkerIfNecessary(getSelectedConversation());
1147		}
1148
1149	}
1150
1151	@Override
1152	public void onSaveInstanceState(final Bundle savedInstanceState) {
1153		Conversation conversation = getSelectedConversation();
1154		if (conversation != null) {
1155			savedInstanceState.putString(STATE_OPEN_CONVERSATION, conversation.getUuid());
1156			Pair<Integer,Integer> scrollPosition = mConversationFragment.getScrollPosition();
1157			if (scrollPosition != null) {
1158				savedInstanceState.putInt(STATE_FIRST_VISIBLE, scrollPosition.first);
1159				savedInstanceState.putInt(STATE_OFFSET_FROM_TOP, scrollPosition.second);
1160			}
1161		} else {
1162			savedInstanceState.remove(STATE_OPEN_CONVERSATION);
1163		}
1164		savedInstanceState.putBoolean(STATE_PANEL_OPEN, isConversationsOverviewVisable());
1165		if (this.mPendingImageUris.size() >= 1) {
1166			Log.d(Config.LOGTAG,"ConversationsActivity.onSaveInstanceState() - saving pending image uri");
1167			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1168		} else {
1169			savedInstanceState.remove(STATE_PENDING_URI);
1170		}
1171		super.onSaveInstanceState(savedInstanceState);
1172	}
1173
1174	private void clearPending() {
1175		mPendingImageUris.clear();
1176		mPendingFileUris.clear();
1177		mPendingGeoUri = null;
1178		mPostponedActivityResult = null;
1179	}
1180
1181	private void redirectToStartConversationActivity() {
1182		Account pendingAccount = xmppConnectionService.getPendingAccount();
1183		if (pendingAccount == null) {
1184			Intent startConversationActivity = new Intent(this, StartConversationActivity.class);
1185			startConversationActivity.putExtra("init", true);
1186			startActivity(startConversationActivity);
1187		} else {
1188			switchToAccount(pendingAccount, true);
1189		}
1190		finish();
1191	}
1192
1193	@Override
1194	void onBackendConnected() {
1195		this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1196		updateConversationList();
1197
1198		if (mPendingConferenceInvite != null) {
1199			if (mPendingConferenceInvite.execute(this)) {
1200				mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
1201				mToast.show();
1202			}
1203			mPendingConferenceInvite = null;
1204		}
1205
1206		final Intent intent = getIntent();
1207
1208		if (xmppConnectionService.getAccounts().size() == 0) {
1209			if (mRedirected.compareAndSet(false, true)) {
1210				if (Config.X509_VERIFICATION) {
1211					startActivity(new Intent(this, ManageAccountActivity.class));
1212				} else if (Config.MAGIC_CREATE_DOMAIN != null) {
1213					startActivity(new Intent(this, WelcomeActivity.class));
1214				} else {
1215					Intent editAccount = new Intent(this, EditAccountActivity.class);
1216					editAccount.putExtra("init",true);
1217					startActivity(editAccount);
1218				}
1219				finish();
1220			}
1221		} else if (conversationList.size() <= 0) {
1222			if (mRedirected.compareAndSet(false, true)) {
1223				redirectToStartConversationActivity();
1224			}
1225		} else if (selectConversationByUuid(mOpenConversation)) {
1226			if (mPanelOpen) {
1227				showConversationsOverview();
1228			} else {
1229				if (isConversationsOverviewHideable()) {
1230					openConversation();
1231					updateActionBarTitle(true);
1232				}
1233			}
1234			if (this.mConversationFragment.reInit(getSelectedConversation())) {
1235				Log.d(Config.LOGTAG,"setting scroll position on fragment");
1236				this.mConversationFragment.setScrollPosition(mScrollPosition);
1237			}
1238			mOpenConversation = null;
1239		} else if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1240			clearPending();
1241			handleViewConversationIntent(intent);
1242			intent.setAction(Intent.ACTION_MAIN);
1243		} else if (getSelectedConversation() == null) {
1244			reInitLatestConversation();
1245		} else {
1246			this.mConversationFragment.messageListAdapter.updatePreferences();
1247			this.mConversationFragment.messagesView.invalidateViews();
1248			this.mConversationFragment.setupIme();
1249		}
1250
1251		if (this.mPostponedActivityResult != null) {
1252			this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1253		}
1254
1255		final boolean stopping = isStopping();
1256
1257		if (!forbidProcessingPendings) {
1258			for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1259				Uri foo = i.next();
1260				Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching image to conversations. stopping="+Boolean.toString(stopping));
1261				attachImageToConversation(getSelectedConversation(), foo);
1262			}
1263
1264			for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1265				Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching file to conversations. stopping="+Boolean.toString(stopping));
1266				attachFileToConversation(getSelectedConversation(), i.next());
1267			}
1268
1269			if (mPendingGeoUri != null) {
1270				attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1271				mPendingGeoUri = null;
1272			}
1273		}
1274		forbidProcessingPendings = false;
1275
1276		if (!ExceptionHelper.checkForCrash(this, this.xmppConnectionService) && !mRedirected.get()) {
1277			openBatteryOptimizationDialogIfNeeded();
1278		}
1279		if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
1280			xmppConnectionService.getNotificationService().setOpenConversation(null);
1281		} else {
1282			xmppConnectionService.getNotificationService().setOpenConversation(getSelectedConversation());
1283		}
1284	}
1285
1286	private boolean isStopping() {
1287		if (Build.VERSION.SDK_INT >= 17) {
1288			return isFinishing() || isDestroyed();
1289		} else {
1290			return isFinishing();
1291		}
1292	}
1293
1294	private void reInitLatestConversation() {
1295		showConversationsOverview();
1296		clearPending();
1297		setSelectedConversation(conversationList.get(0));
1298		this.mConversationFragment.reInit(getSelectedConversation());
1299	}
1300
1301	private void handleViewConversationIntent(final Intent intent) {
1302		final String uuid = intent.getStringExtra(CONVERSATION);
1303		final String downloadUuid = intent.getStringExtra(EXTRA_DOWNLOAD_UUID);
1304		final String text = intent.getStringExtra(TEXT);
1305		final String nick = intent.getStringExtra(NICK);
1306		final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1307		if (selectConversationByUuid(uuid)) {
1308			this.mConversationFragment.reInit(getSelectedConversation());
1309			if (nick != null) {
1310				if (pm) {
1311					Jid jid = getSelectedConversation().getJid();
1312					try {
1313						Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1314						this.mConversationFragment.privateMessageWith(next);
1315					} catch (final InvalidJidException ignored) {
1316						//do nothing
1317					}
1318				} else {
1319					this.mConversationFragment.highlightInConference(nick);
1320				}
1321			} else {
1322				this.mConversationFragment.appendText(text);
1323			}
1324			hideConversationsOverview();
1325			mUnprocessedNewIntent = false;
1326			openConversation();
1327			if (mContentView instanceof SlidingPaneLayout) {
1328				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1329			}
1330			if (downloadUuid != null) {
1331				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1332				if (message != null) {
1333					startDownloadable(message);
1334				}
1335			}
1336		} else {
1337			mUnprocessedNewIntent = false;
1338		}
1339	}
1340
1341	private boolean selectConversationByUuid(String uuid) {
1342		if (uuid == null) {
1343			return false;
1344		}
1345		for (Conversation aConversationList : conversationList) {
1346			if (aConversationList.getUuid().equals(uuid)) {
1347				setSelectedConversation(aConversationList);
1348				return true;
1349			}
1350		}
1351		return false;
1352	}
1353
1354	@Override
1355	protected void unregisterListeners() {
1356		super.unregisterListeners();
1357		xmppConnectionService.getNotificationService().setOpenConversation(null);
1358	}
1359
1360	@SuppressLint("NewApi")
1361	private static List<Uri> extractUriFromIntent(final Intent intent) {
1362		List<Uri> uris = new ArrayList<>();
1363		if (intent == null) {
1364			return uris;
1365		}
1366		Uri uri = intent.getData();
1367		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1368			final ClipData clipData = intent.getClipData();
1369			if (clipData != null) {
1370				for (int i = 0; i < clipData.getItemCount(); ++i) {
1371					uris.add(clipData.getItemAt(i).getUri());
1372				}
1373			}
1374		} else {
1375			uris.add(uri);
1376		}
1377		return uris;
1378	}
1379
1380	@Override
1381	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1382		super.onActivityResult(requestCode, resultCode, data);
1383		if (resultCode == RESULT_OK) {
1384			if (requestCode == REQUEST_DECRYPT_PGP) {
1385				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1386			} else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1387				// the user chose OpenPGP for encryption and selected his key in the PGP provider
1388				if (xmppConnectionServiceBound) {
1389					if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1390						// associate selected PGP keyId with the account
1391						mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1392						// we need to announce the key as described in XEP-027
1393						announcePgp(mSelectedConversation.getAccount(), null, onOpenPGPKeyPublished);
1394					} else {
1395						choosePgpSignId(mSelectedConversation.getAccount());
1396					}
1397					this.mPostponedActivityResult = null;
1398				} else {
1399					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1400				}
1401			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1402				if (xmppConnectionServiceBound) {
1403					announcePgp(mSelectedConversation.getAccount(), mSelectedConversation, onOpenPGPKeyPublished);
1404					this.mPostponedActivityResult = null;
1405				} else {
1406					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1407				}
1408			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1409				mPendingImageUris.clear();
1410				mPendingImageUris.addAll(extractUriFromIntent(data));
1411				if (xmppConnectionServiceBound) {
1412					for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1413						Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. CHOOSE_IMAGE");
1414						attachImageToConversation(getSelectedConversation(), i.next());
1415					}
1416				}
1417			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1418				final List<Uri> uris = extractUriFromIntent(data);
1419				final Conversation c = getSelectedConversation();
1420				final OnPresenceSelected callback = new OnPresenceSelected() {
1421					@Override
1422					public void onPresenceSelected() {
1423						mPendingFileUris.clear();
1424						mPendingFileUris.addAll(uris);
1425						if (xmppConnectionServiceBound) {
1426							for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1427								Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE");
1428								attachFileToConversation(c, i.next());
1429							}
1430						}
1431					}
1432				};
1433				if (c == null || c.getMode() == Conversation.MODE_MULTI
1434						|| FileBackend.allFilesUnderSize(this, uris, getMaxHttpUploadSize(c))
1435						|| c.getNextEncryption() == Message.ENCRYPTION_OTR) {
1436					callback.onPresenceSelected();
1437				} else {
1438					selectPresence(c, callback);
1439				}
1440			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1441				if (mPendingImageUris.size() == 1) {
1442					Uri uri = FileBackend.getIndexableTakePhotoUri(mPendingImageUris.get(0));
1443					mPendingImageUris.set(0, uri);
1444					if (xmppConnectionServiceBound) {
1445						Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. TAKE_PHOTO");
1446						attachImageToConversation(getSelectedConversation(), uri);
1447						mPendingImageUris.clear();
1448					}
1449					if (!Config.ONLY_INTERNAL_STORAGE) {
1450						Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1451						intent.setData(uri);
1452						sendBroadcast(intent);
1453					}
1454				} else {
1455					mPendingImageUris.clear();
1456				}
1457			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1458				double latitude = data.getDoubleExtra("latitude", 0);
1459				double longitude = data.getDoubleExtra("longitude", 0);
1460				this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1461				if (xmppConnectionServiceBound) {
1462					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1463					this.mPendingGeoUri = null;
1464				}
1465			} else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1466				this.forbidProcessingPendings = !xmppConnectionServiceBound;
1467				if (xmppConnectionServiceBound) {
1468					mConversationFragment.onActivityResult(requestCode, resultCode, data);
1469					this.mPostponedActivityResult = null;
1470				} else {
1471					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1472				}
1473
1474			}
1475		} else {
1476			mPendingImageUris.clear();
1477			mPendingFileUris.clear();
1478			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1479				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1480			}
1481			if (requestCode == REQUEST_BATTERY_OP) {
1482				setNeverAskForBatteryOptimizationsAgain();
1483			}
1484		}
1485	}
1486
1487	private long getMaxHttpUploadSize(Conversation conversation) {
1488		final XmppConnection connection = conversation.getAccount().getXmppConnection();
1489		return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
1490	}
1491
1492	private void setNeverAskForBatteryOptimizationsAgain() {
1493		getPreferences().edit().putBoolean("show_battery_optimization", false).apply();
1494	}
1495
1496	private void openBatteryOptimizationDialogIfNeeded() {
1497		if (hasAccountWithoutPush()
1498				&& isOptimizingBattery()
1499				&& getPreferences().getBoolean("show_battery_optimization", true)) {
1500			AlertDialog.Builder builder = new AlertDialog.Builder(this);
1501			builder.setTitle(R.string.battery_optimizations_enabled);
1502			builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1503			builder.setPositiveButton(R.string.next, new OnClickListener() {
1504				@Override
1505				public void onClick(DialogInterface dialog, int which) {
1506					Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1507					Uri uri = Uri.parse("package:" + getPackageName());
1508					intent.setData(uri);
1509					try {
1510						startActivityForResult(intent, REQUEST_BATTERY_OP);
1511					} catch (ActivityNotFoundException e) {
1512						Toast.makeText(ConversationActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1513					}
1514				}
1515			});
1516			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1517				builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1518					@Override
1519					public void onDismiss(DialogInterface dialog) {
1520						setNeverAskForBatteryOptimizationsAgain();
1521					}
1522				});
1523			}
1524			AlertDialog dialog = builder.create();
1525			dialog.setCanceledOnTouchOutside(false);
1526			dialog.show();
1527		}
1528	}
1529
1530	private boolean hasAccountWithoutPush() {
1531		for(Account account : xmppConnectionService.getAccounts()) {
1532			if (account.getStatus() != Account.State.DISABLED
1533					&& !xmppConnectionService.getPushManagementService().availableAndUseful(account)) {
1534				return true;
1535			}
1536		}
1537		return false;
1538	}
1539
1540	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1541		if (conversation == null) {
1542			return;
1543		}
1544		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1545
1546			@Override
1547			public void success(Message message) {
1548				xmppConnectionService.sendMessage(message);
1549			}
1550
1551			@Override
1552			public void error(int errorCode, Message object) {
1553
1554			}
1555
1556			@Override
1557			public void userInputRequried(PendingIntent pi, Message object) {
1558
1559			}
1560		});
1561	}
1562
1563	private void attachFileToConversation(Conversation conversation, Uri uri) {
1564		if (conversation == null) {
1565			return;
1566		}
1567		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1568		prepareFileToast.show();
1569		xmppConnectionService.attachFileToConversation(conversation, uri, new UiInformableCallback<Message>() {
1570			@Override
1571			public void inform(final String text) {
1572				hidePrepareFileToast(prepareFileToast);
1573				runOnUiThread(new Runnable() {
1574					@Override
1575					public void run() {
1576						replaceToast(text);
1577					}
1578				});
1579			}
1580
1581			@Override
1582			public void success(Message message) {
1583				runOnUiThread(new Runnable() {
1584					@Override
1585					public void run() {
1586						hideToast();
1587					}
1588				});
1589				hidePrepareFileToast(prepareFileToast);
1590				xmppConnectionService.sendMessage(message);
1591			}
1592
1593			@Override
1594			public void error(final int errorCode, Message message) {
1595				hidePrepareFileToast(prepareFileToast);
1596				runOnUiThread(new Runnable() {
1597					@Override
1598					public void run() {
1599						replaceToast(getString(errorCode));
1600					}
1601				});
1602
1603			}
1604
1605			@Override
1606			public void userInputRequried(PendingIntent pi, Message message) {
1607				hidePrepareFileToast(prepareFileToast);
1608			}
1609		});
1610	}
1611
1612	public void attachImageToConversation(Uri uri) {
1613		this.attachImageToConversation(getSelectedConversation(), uri);
1614	}
1615
1616	private void attachImageToConversation(Conversation conversation, Uri uri) {
1617		if (conversation == null) {
1618			return;
1619		}
1620		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1621		prepareFileToast.show();
1622		xmppConnectionService.attachImageToConversation(conversation, uri,
1623				new UiCallback<Message>() {
1624
1625					@Override
1626					public void userInputRequried(PendingIntent pi, Message object) {
1627						hidePrepareFileToast(prepareFileToast);
1628					}
1629
1630					@Override
1631					public void success(Message message) {
1632						hidePrepareFileToast(prepareFileToast);
1633						xmppConnectionService.sendMessage(message);
1634					}
1635
1636					@Override
1637					public void error(final int error, Message message) {
1638						hidePrepareFileToast(prepareFileToast);
1639						runOnUiThread(new Runnable() {
1640							@Override
1641							public void run() {
1642								replaceToast(getString(error));
1643							}
1644						});
1645					}
1646				});
1647	}
1648
1649	private void hidePrepareFileToast(final Toast prepareFileToast) {
1650		if (prepareFileToast != null) {
1651			runOnUiThread(new Runnable() {
1652
1653				@Override
1654				public void run() {
1655					prepareFileToast.cancel();
1656				}
1657			});
1658		}
1659	}
1660
1661	public void updateConversationList() {
1662		xmppConnectionService.populateWithOrderedConversations(conversationList);
1663		if (!conversationList.contains(mSelectedConversation)) {
1664			mSelectedConversation = null;
1665		}
1666		if (swipedConversation != null) {
1667			if (swipedConversation.isRead()) {
1668				conversationList.remove(swipedConversation);
1669			} else {
1670				listView.discardUndo();
1671			}
1672		}
1673		listAdapter.notifyDataSetChanged();
1674	}
1675
1676	public void runIntent(PendingIntent pi, int requestCode) {
1677		try {
1678			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1679					null, 0, 0, 0);
1680		} catch (final SendIntentException ignored) {
1681		}
1682	}
1683
1684	public void encryptTextMessage(Message message) {
1685		xmppConnectionService.getPgpEngine().encrypt(message,
1686				new UiCallback<Message>() {
1687
1688					@Override
1689					public void userInputRequried(PendingIntent pi,Message message) {
1690						ConversationActivity.this.runIntent(pi,ConversationActivity.REQUEST_SEND_MESSAGE);
1691					}
1692
1693					@Override
1694					public void success(Message message) {
1695						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1696						xmppConnectionService.sendMessage(message);
1697						runOnUiThread(new Runnable() {
1698							@Override
1699							public void run() {
1700								mConversationFragment.messageSent();
1701							}
1702						});
1703					}
1704
1705					@Override
1706					public void error(final int error, Message message) {
1707						runOnUiThread(new Runnable() {
1708							@Override
1709							public void run() {
1710								mConversationFragment.doneSendingPgpMessage();
1711								Toast.makeText(ConversationActivity.this,
1712										R.string.unable_to_connect_to_keychain,
1713										Toast.LENGTH_SHORT
1714								).show();
1715							}
1716						});
1717
1718					}
1719				});
1720	}
1721
1722	public boolean useSendButtonToIndicateStatus() {
1723		return getPreferences().getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
1724	}
1725
1726	public boolean indicateReceived() {
1727		return getPreferences().getBoolean("indicate_received", getResources().getBoolean(R.bool.indicate_received));
1728	}
1729
1730	public boolean useGreenBackground() {
1731		return getPreferences().getBoolean("use_green_background",getResources().getBoolean(R.bool.use_green_background));
1732	}
1733
1734	protected boolean trustKeysIfNeeded(int requestCode) {
1735		return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1736	}
1737
1738	protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1739		AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1740		final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1741		boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1742		boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided()).isEmpty();
1743		boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets).isEmpty();
1744		boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1745		boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1746		if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1747			axolotlService.createSessionsIfNeeded(mSelectedConversation);
1748			Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1749			String[] contacts = new String[targets.size()];
1750			for(int i = 0; i < contacts.length; ++i) {
1751				contacts[i] = targets.get(i).toString();
1752			}
1753			intent.putExtra("contacts", contacts);
1754			intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1755			intent.putExtra("choice", attachmentChoice);
1756			intent.putExtra("conversation",mSelectedConversation.getUuid());
1757			startActivityForResult(intent, requestCode);
1758			return true;
1759		} else {
1760			return false;
1761		}
1762	}
1763
1764	@Override
1765	protected void refreshUiReal() {
1766		updateConversationList();
1767		if (conversationList.size() > 0) {
1768			if (!this.mConversationFragment.isAdded()) {
1769				Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1770			}
1771			if (getSelectedConversation() == null) {
1772				reInitLatestConversation();
1773			} else {
1774				ConversationActivity.this.mConversationFragment.updateMessages();
1775				updateActionBarTitle();
1776				invalidateOptionsMenu();
1777			}
1778		} else {
1779			if (!isStopping() && mRedirected.compareAndSet(false, true)) {
1780				redirectToStartConversationActivity();
1781			}
1782			Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1783		}
1784	}
1785
1786	@Override
1787	public void onAccountUpdate() {
1788		this.refreshUi();
1789	}
1790
1791	@Override
1792	public void onConversationUpdate() {
1793		this.refreshUi();
1794	}
1795
1796	@Override
1797	public void onRosterUpdate() {
1798		this.refreshUi();
1799	}
1800
1801	@Override
1802	public void OnUpdateBlocklist(Status status) {
1803		this.refreshUi();
1804	}
1805
1806	public void unblockConversation(final Blockable conversation) {
1807		xmppConnectionService.sendUnblockRequest(conversation);
1808	}
1809
1810	public boolean enterIsSend() {
1811		return getPreferences().getBoolean("enter_is_send",getResources().getBoolean(R.bool.enter_is_send));
1812	}
1813
1814	@Override
1815	public void onShowErrorToast(final int resId) {
1816		runOnUiThread(new Runnable() {
1817			@Override
1818			public void run() {
1819				Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1820			}
1821		});
1822	}
1823
1824	public boolean highlightSelectedConversations() {
1825		return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1826	}
1827}