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