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.ClipData;
   9import android.content.DialogInterface;
  10import android.content.DialogInterface.OnClickListener;
  11import android.content.Intent;
  12import android.content.IntentSender.SendIntentException;
  13import android.content.pm.PackageManager;
  14import android.net.Uri;
  15import android.os.Build;
  16import android.os.Bundle;
  17import android.provider.MediaStore;
  18import android.provider.Settings;
  19import android.support.v4.widget.SlidingPaneLayout;
  20import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
  21import android.util.Log;
  22import android.util.Pair;
  23import android.view.Gravity;
  24import android.view.KeyEvent;
  25import android.view.Menu;
  26import android.view.MenuItem;
  27import android.view.Surface;
  28import android.view.View;
  29import android.widget.AdapterView;
  30import android.widget.AdapterView.OnItemClickListener;
  31import android.widget.ArrayAdapter;
  32import android.widget.CheckBox;
  33import android.widget.PopupMenu;
  34import android.widget.PopupMenu.OnMenuItemClickListener;
  35import android.widget.Toast;
  36
  37import net.java.otr4j.session.SessionStatus;
  38
  39import org.openintents.openpgp.util.OpenPgpApi;
  40
  41import java.util.ArrayList;
  42import java.util.Iterator;
  43import java.util.List;
  44import java.util.concurrent.atomic.AtomicBoolean;
  45
  46import de.timroes.android.listview.EnhancedListView;
  47import eu.siacs.conversations.Config;
  48import eu.siacs.conversations.R;
  49import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  50import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
  51import eu.siacs.conversations.entities.Account;
  52import eu.siacs.conversations.entities.Blockable;
  53import eu.siacs.conversations.entities.Contact;
  54import eu.siacs.conversations.entities.Conversation;
  55import eu.siacs.conversations.entities.Message;
  56import eu.siacs.conversations.entities.Transferable;
  57import eu.siacs.conversations.persistance.FileBackend;
  58import eu.siacs.conversations.services.XmppConnectionService;
  59import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
  60import eu.siacs.conversations.services.XmppConnectionService.OnConversationUpdate;
  61import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
  62import eu.siacs.conversations.ui.adapter.ConversationAdapter;
  63import eu.siacs.conversations.utils.ExceptionHelper;
  64import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  65import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  66import eu.siacs.conversations.xmpp.jid.Jid;
  67
  68public class ConversationActivity extends XmppActivity
  69	implements OnAccountUpdate, OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast {
  70
  71	public static final String ACTION_DOWNLOAD = "eu.siacs.conversations.action.DOWNLOAD";
  72
  73	public static final String VIEW_CONVERSATION = "viewConversation";
  74	public static final String CONVERSATION = "conversationUuid";
  75	public static final String MESSAGE = "messageUuid";
  76	public static final String TEXT = "text";
  77	public static final String NICK = "nick";
  78	public static final String PRIVATE_MESSAGE = "pm";
  79
  80	public static final int REQUEST_SEND_MESSAGE = 0x0201;
  81	public static final int REQUEST_DECRYPT_PGP = 0x0202;
  82	public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
  83	public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
  84	public static final int REQUEST_TRUST_KEYS_MENU = 0x0209;
  85	public static final int REQUEST_START_DOWNLOAD = 0x0210;
  86	public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
  87	public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
  88	public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
  89	public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
  90	public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
  91	public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
  92	private static final String STATE_OPEN_CONVERSATION = "state_open_conversation";
  93	private static final String STATE_PANEL_OPEN = "state_panel_open";
  94	private static final String STATE_PENDING_URI = "state_pending_uri";
  95
  96	private String mOpenConverstaion = null;
  97	private boolean mPanelOpen = true;
  98	final private List<Uri> mPendingImageUris = new ArrayList<>();
  99	final private List<Uri> mPendingFileUris = new ArrayList<>();
 100	private Uri mPendingGeoUri = null;
 101	private boolean forbidProcessingPendings = false;
 102	private Message mPendingDownloadableMessage = null;
 103
 104	private boolean conversationWasSelectedByKeyboard = false;
 105
 106	private View mContentView;
 107
 108	private List<Conversation> conversationList = new ArrayList<>();
 109	private Conversation swipedConversation = null;
 110	private Conversation mSelectedConversation = null;
 111	private EnhancedListView listView;
 112	private ConversationFragment mConversationFragment;
 113
 114	private ArrayAdapter<Conversation> listAdapter;
 115
 116	private boolean mActivityPaused = false;
 117	private AtomicBoolean mRedirected = new AtomicBoolean(false);
 118	private Pair<Integer, Intent> mPostponedActivityResult;
 119
 120	public Conversation getSelectedConversation() {
 121		return this.mSelectedConversation;
 122	}
 123
 124	public void setSelectedConversation(Conversation conversation) {
 125		this.mSelectedConversation = conversation;
 126	}
 127
 128	public void showConversationsOverview() {
 129		if (mContentView instanceof SlidingPaneLayout) {
 130			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 131			mSlidingPaneLayout.openPane();
 132		}
 133	}
 134
 135	@Override
 136	protected String getShareableUri() {
 137		Conversation conversation = getSelectedConversation();
 138		if (conversation != null) {
 139			return conversation.getAccount().getShareableUri();
 140		} else {
 141			return "";
 142		}
 143	}
 144
 145	public void hideConversationsOverview() {
 146		if (mContentView instanceof SlidingPaneLayout) {
 147			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 148			mSlidingPaneLayout.closePane();
 149		}
 150	}
 151
 152	public boolean isConversationsOverviewHideable() {
 153		if (mContentView instanceof SlidingPaneLayout) {
 154			return true;
 155		} else {
 156			return false;
 157		}
 158	}
 159
 160	public boolean isConversationsOverviewVisable() {
 161		if (mContentView instanceof SlidingPaneLayout) {
 162			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 163			return mSlidingPaneLayout.isOpen();
 164		} else {
 165			return true;
 166		}
 167	}
 168
 169	@Override
 170	protected void onCreate(final Bundle savedInstanceState) {
 171		super.onCreate(savedInstanceState);
 172		if (savedInstanceState != null) {
 173			mOpenConverstaion = savedInstanceState.getString(STATE_OPEN_CONVERSATION, null);
 174			mPanelOpen = savedInstanceState.getBoolean(STATE_PANEL_OPEN, true);
 175			String pending = savedInstanceState.getString(STATE_PENDING_URI, null);
 176			if (pending != null) {
 177				mPendingImageUris.clear();
 178				mPendingImageUris.add(Uri.parse(pending));
 179			}
 180		}
 181
 182		setContentView(R.layout.fragment_conversations_overview);
 183
 184		this.mConversationFragment = new ConversationFragment();
 185		FragmentTransaction transaction = getFragmentManager().beginTransaction();
 186		transaction.replace(R.id.selected_conversation, this.mConversationFragment, "conversation");
 187		transaction.commit();
 188
 189		listView = (EnhancedListView) findViewById(R.id.list);
 190		this.listAdapter = new ConversationAdapter(this, conversationList);
 191		listView.setAdapter(this.listAdapter);
 192
 193		if (getActionBar() != null) {
 194			getActionBar().setDisplayHomeAsUpEnabled(false);
 195			getActionBar().setHomeButtonEnabled(false);
 196		}
 197
 198		listView.setOnItemClickListener(new OnItemClickListener() {
 199
 200			@Override
 201			public void onItemClick(AdapterView<?> arg0, View clickedView,
 202									int position, long arg3) {
 203				if (getSelectedConversation() != conversationList.get(position)) {
 204					setSelectedConversation(conversationList.get(position));
 205					ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 206					conversationWasSelectedByKeyboard = false;
 207				}
 208				hideConversationsOverview();
 209				openConversation();
 210			}
 211		});
 212
 213		listView.setDismissCallback(new EnhancedListView.OnDismissCallback() {
 214
 215			@Override
 216			public EnhancedListView.Undoable onDismiss(final EnhancedListView enhancedListView, final int position) {
 217
 218				final int index = listView.getFirstVisiblePosition();
 219				View v = listView.getChildAt(0);
 220				final int top = (v == null) ? 0 : (v.getTop() - listView.getPaddingTop());
 221
 222				try {
 223					swipedConversation = listAdapter.getItem(position);
 224				} catch (IndexOutOfBoundsException e) {
 225					return null;
 226				}
 227				listAdapter.remove(swipedConversation);
 228				xmppConnectionService.markRead(swipedConversation);
 229
 230				final boolean formerlySelected = (getSelectedConversation() == swipedConversation);
 231				if (position == 0 && listAdapter.getCount() == 0) {
 232					endConversation(swipedConversation, false, true);
 233					return null;
 234				} else if (formerlySelected) {
 235					setSelectedConversation(listAdapter.getItem(0));
 236					ConversationActivity.this.mConversationFragment
 237							.reInit(getSelectedConversation());
 238				}
 239
 240				return new EnhancedListView.Undoable() {
 241
 242					@Override
 243					public void undo() {
 244						listAdapter.insert(swipedConversation, position);
 245						if (formerlySelected) {
 246							setSelectedConversation(swipedConversation);
 247							ConversationActivity.this.mConversationFragment
 248									.reInit(getSelectedConversation());
 249						}
 250						swipedConversation = null;
 251						listView.setSelectionFromTop(index + (listView.getChildCount() < position ? 1 : 0), top);
 252					}
 253
 254					@Override
 255					public void discard() {
 256						if (!swipedConversation.isRead()
 257								&& swipedConversation.getMode() == Conversation.MODE_SINGLE) {
 258							swipedConversation = null;
 259							return;
 260						}
 261						endConversation(swipedConversation, false, false);
 262						swipedConversation = null;
 263					}
 264
 265					@Override
 266					public String getTitle() {
 267						if (swipedConversation.getMode() == Conversation.MODE_MULTI) {
 268							return getResources().getString(R.string.title_undo_swipe_out_muc);
 269						} else {
 270							return getResources().getString(R.string.title_undo_swipe_out_conversation);
 271						}
 272					}
 273				};
 274			}
 275		});
 276		listView.enableSwipeToDismiss();
 277		listView.setSwipingLayout(R.id.swipeable_item);
 278		listView.setUndoStyle(EnhancedListView.UndoStyle.SINGLE_POPUP);
 279		listView.setUndoHideDelay(5000);
 280		listView.setRequireTouchBeforeDismiss(false);
 281
 282		mContentView = findViewById(R.id.content_view_spl);
 283		if (mContentView == null) {
 284			mContentView = findViewById(R.id.content_view_ll);
 285		}
 286		if (mContentView instanceof SlidingPaneLayout) {
 287			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 288			mSlidingPaneLayout.setParallaxDistance(150);
 289			mSlidingPaneLayout
 290					.setShadowResource(R.drawable.es_slidingpane_shadow);
 291			mSlidingPaneLayout.setSliderFadeColor(0);
 292			mSlidingPaneLayout.setPanelSlideListener(new PanelSlideListener() {
 293
 294				@Override
 295				public void onPanelOpened(View arg0) {
 296					updateActionBarTitle();
 297					invalidateOptionsMenu();
 298					hideKeyboard();
 299					if (xmppConnectionServiceBound) {
 300						xmppConnectionService.getNotificationService()
 301								.setOpenConversation(null);
 302					}
 303					closeContextMenu();
 304				}
 305
 306				@Override
 307				public void onPanelClosed(View arg0) {
 308					listView.discardUndo();
 309					openConversation();
 310				}
 311
 312				@Override
 313				public void onPanelSlide(View arg0, float arg1) {
 314					// TODO Auto-generated method stub
 315
 316				}
 317			});
 318		}
 319	}
 320
 321	@Override
 322	public void switchToConversation(Conversation conversation) {
 323		setSelectedConversation(conversation);
 324		runOnUiThread(new Runnable() {
 325			@Override
 326			public void run() {
 327				ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 328				openConversation();
 329			}
 330		});
 331	}
 332
 333	private void updateActionBarTitle() {
 334		updateActionBarTitle(isConversationsOverviewHideable() && !isConversationsOverviewVisable());
 335	}
 336
 337	private void updateActionBarTitle(boolean titleShouldBeName) {
 338		final ActionBar ab = getActionBar();
 339		final Conversation conversation = getSelectedConversation();
 340		if (ab != null) {
 341			if (titleShouldBeName && conversation != null) {
 342				ab.setDisplayHomeAsUpEnabled(true);
 343				ab.setHomeButtonEnabled(true);
 344				if (conversation.getMode() == Conversation.MODE_SINGLE || useSubjectToIdentifyConference()) {
 345					ab.setTitle(conversation.getName());
 346				} else {
 347					ab.setTitle(conversation.getJid().toBareJid().toString());
 348				}
 349			} else {
 350				ab.setDisplayHomeAsUpEnabled(false);
 351				ab.setHomeButtonEnabled(false);
 352				ab.setTitle(R.string.app_name);
 353			}
 354		}
 355	}
 356
 357	private void openConversation() {
 358		this.updateActionBarTitle();
 359		this.invalidateOptionsMenu();
 360		if (xmppConnectionServiceBound) {
 361			final Conversation conversation = getSelectedConversation();
 362			xmppConnectionService.getNotificationService().setOpenConversation(conversation);
 363			sendReadMarkerIfNecessary(conversation);
 364		}
 365		listAdapter.notifyDataSetChanged();
 366	}
 367
 368	public void sendReadMarkerIfNecessary(final Conversation conversation) {
 369		if (!mActivityPaused && conversation != null) {
 370			xmppConnectionService.sendReadMarker(conversation);
 371		}
 372	}
 373
 374	@Override
 375	public boolean onCreateOptionsMenu(Menu menu) {
 376		getMenuInflater().inflate(R.menu.conversations, menu);
 377		final MenuItem menuSecure = menu.findItem(R.id.action_security);
 378		final MenuItem menuArchive = menu.findItem(R.id.action_archive);
 379		final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
 380		final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
 381		final MenuItem menuAttach = menu.findItem(R.id.action_attach_file);
 382		final MenuItem menuClearHistory = menu.findItem(R.id.action_clear_history);
 383		final MenuItem menuAdd = menu.findItem(R.id.action_add);
 384		final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
 385		final MenuItem menuMute = menu.findItem(R.id.action_mute);
 386		final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
 387
 388		if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
 389			menuArchive.setVisible(false);
 390			menuMucDetails.setVisible(false);
 391			menuContactDetails.setVisible(false);
 392			menuSecure.setVisible(false);
 393			menuInviteContact.setVisible(false);
 394			menuAttach.setVisible(false);
 395			menuClearHistory.setVisible(false);
 396			menuMute.setVisible(false);
 397			menuUnmute.setVisible(false);
 398		} else {
 399			menuAdd.setVisible(!isConversationsOverviewHideable());
 400			if (this.getSelectedConversation() != null) {
 401				if (this.getSelectedConversation().getNextEncryption() != Message.ENCRYPTION_NONE) {
 402					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 403						menuSecure.setIcon(R.drawable.ic_lock_white_24dp);
 404					} else {
 405						menuSecure.setIcon(R.drawable.ic_action_secure);
 406					}
 407				}
 408				if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
 409					menuContactDetails.setVisible(false);
 410					menuAttach.setVisible(getSelectedConversation().getAccount().httpUploadAvailable() && getSelectedConversation().getMucOptions().participating());
 411					menuInviteContact.setVisible(getSelectedConversation().getMucOptions().canInvite());
 412					menuSecure.setVisible((Config.supportOpenPgp() || Config.supportOmemo()) && Config.multipleEncryptionChoices()); //only if pgp is supported we have a choice
 413				} else {
 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									displayErrorDialog(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);
 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.isAltPressed();
 951		if (modifier && key == KeyEvent.KEYCODE_TAB && isConversationsOverviewHideable()) {
 952			toggleConversationsOverview();
 953			return true;
 954		} else if (modifier && key == downKey) {
 955			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
 956				showConversationsOverview();
 957				;
 958			}
 959			return selectDownConversation();
 960		} else if (modifier && key == upKey) {
 961			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
 962				showConversationsOverview();
 963			}
 964			return selectUpConversation();
 965		} else if (modifier && key == KeyEvent.KEYCODE_1) {
 966			return openConversationByIndex(0);
 967		} else if (modifier && key == KeyEvent.KEYCODE_2) {
 968			return openConversationByIndex(1);
 969		} else if (modifier && key == KeyEvent.KEYCODE_3) {
 970			return openConversationByIndex(2);
 971		} else if (modifier && key == KeyEvent.KEYCODE_4) {
 972			return openConversationByIndex(3);
 973		} else if (modifier && key == KeyEvent.KEYCODE_5) {
 974			return openConversationByIndex(4);
 975		} else if (modifier && key == KeyEvent.KEYCODE_6) {
 976			return openConversationByIndex(5);
 977		} else if (modifier && key == KeyEvent.KEYCODE_7) {
 978			return openConversationByIndex(6);
 979		} else if (modifier && key == KeyEvent.KEYCODE_8) {
 980			return openConversationByIndex(7);
 981		} else if (modifier && key == KeyEvent.KEYCODE_9) {
 982			return openConversationByIndex(8);
 983		} else if (modifier && key == KeyEvent.KEYCODE_0) {
 984			return openConversationByIndex(9);
 985		} else {
 986			return super.onKeyUp(key, event);
 987		}
 988	}
 989
 990	private void toggleConversationsOverview() {
 991		if (isConversationsOverviewVisable()) {
 992			hideConversationsOverview();
 993			if (mConversationFragment != null) {
 994				mConversationFragment.setFocusOnInputField();
 995			}
 996		} else {
 997			showConversationsOverview();
 998		}
 999	}
1000
1001	private boolean selectUpConversation() {
1002		if (this.mSelectedConversation != null) {
1003			int index = this.conversationList.indexOf(this.mSelectedConversation);
1004			if (index > 0) {
1005				return openConversationByIndex(index - 1);
1006			}
1007		}
1008		return false;
1009	}
1010
1011	private boolean selectDownConversation() {
1012		if (this.mSelectedConversation != null) {
1013			int index = this.conversationList.indexOf(this.mSelectedConversation);
1014			if (index != -1 && index < this.conversationList.size() - 1) {
1015				return openConversationByIndex(index + 1);
1016			}
1017		}
1018		return false;
1019	}
1020
1021	private boolean openConversationByIndex(int index) {
1022		try {
1023			this.conversationWasSelectedByKeyboard = true;
1024			setSelectedConversation(this.conversationList.get(index));
1025			this.mConversationFragment.reInit(getSelectedConversation());
1026			if (index > listView.getLastVisiblePosition() - 1 || index < listView.getFirstVisiblePosition() + 1) {
1027				this.listView.setSelection(index);
1028			}
1029			openConversation();
1030			return true;
1031		} catch (IndexOutOfBoundsException e) {
1032			return false;
1033		}
1034	}
1035
1036	@Override
1037	protected void onNewIntent(final Intent intent) {
1038		if (xmppConnectionServiceBound) {
1039			if (intent != null && VIEW_CONVERSATION.equals(intent.getType())) {
1040				handleViewConversationIntent(intent);
1041				setIntent(new Intent());
1042			}
1043		} else {
1044			setIntent(intent);
1045		}
1046	}
1047
1048	@Override
1049	public void onStart() {
1050		super.onStart();
1051		this.mRedirected.set(false);
1052		if (this.xmppConnectionServiceBound) {
1053			this.onBackendConnected();
1054		}
1055		if (conversationList.size() >= 1) {
1056			this.onConversationUpdate();
1057		}
1058	}
1059
1060	@Override
1061	public void onPause() {
1062		listView.discardUndo();
1063		super.onPause();
1064		this.mActivityPaused = true;
1065		if (this.xmppConnectionServiceBound) {
1066			this.xmppConnectionService.getNotificationService().setIsInForeground(false);
1067		}
1068	}
1069
1070	@Override
1071	public void onResume() {
1072		super.onResume();
1073		final int theme = findTheme();
1074		final boolean usingEnterKey = usingEnterKey();
1075		if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
1076			recreate();
1077		}
1078		this.mActivityPaused = false;
1079		if (this.xmppConnectionServiceBound) {
1080			this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1081		}
1082
1083		if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
1084			sendReadMarkerIfNecessary(getSelectedConversation());
1085		}
1086
1087	}
1088
1089	@Override
1090	public void onSaveInstanceState(final Bundle savedInstanceState) {
1091		Conversation conversation = getSelectedConversation();
1092		if (conversation != null) {
1093			savedInstanceState.putString(STATE_OPEN_CONVERSATION, conversation.getUuid());
1094		} else {
1095			savedInstanceState.remove(STATE_OPEN_CONVERSATION);
1096		}
1097		savedInstanceState.putBoolean(STATE_PANEL_OPEN, isConversationsOverviewVisable());
1098		if (this.mPendingImageUris.size() >= 1) {
1099			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1100		} else {
1101			savedInstanceState.remove(STATE_PENDING_URI);
1102		}
1103		super.onSaveInstanceState(savedInstanceState);
1104	}
1105
1106	private void clearPending() {
1107		mPendingImageUris.clear();
1108		mPendingFileUris.clear();
1109		mPendingGeoUri = null;
1110		mPostponedActivityResult = null;
1111	}
1112
1113	@Override
1114	void onBackendConnected() {
1115		this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1116		updateConversationList();
1117
1118		if (mPendingConferenceInvite != null) {
1119			mPendingConferenceInvite.execute(this);
1120			mPendingConferenceInvite = null;
1121		}
1122
1123		if (xmppConnectionService.getAccounts().size() == 0) {
1124			if (mRedirected.compareAndSet(false, true)) {
1125				if (Config.X509_VERIFICATION) {
1126					startActivity(new Intent(this, ManageAccountActivity.class));
1127				} else {
1128					startActivity(new Intent(this, EditAccountActivity.class));
1129				}
1130				finish();
1131			}
1132		} else if (conversationList.size() <= 0) {
1133			if (mRedirected.compareAndSet(false, true)) {
1134				Intent intent = new Intent(this, StartConversationActivity.class);
1135				intent.putExtra("init", true);
1136				startActivity(intent);
1137				finish();
1138			}
1139		} else if (getIntent() != null && VIEW_CONVERSATION.equals(getIntent().getType())) {
1140			clearPending();
1141			handleViewConversationIntent(getIntent());
1142		} else if (selectConversationByUuid(mOpenConverstaion)) {
1143			if (mPanelOpen) {
1144				showConversationsOverview();
1145			} else {
1146				if (isConversationsOverviewHideable()) {
1147					openConversation();
1148					updateActionBarTitle(true);
1149				}
1150			}
1151			this.mConversationFragment.reInit(getSelectedConversation());
1152			mOpenConverstaion = null;
1153		} else if (getSelectedConversation() == null) {
1154			showConversationsOverview();
1155			clearPending();
1156			setSelectedConversation(conversationList.get(0));
1157			this.mConversationFragment.reInit(getSelectedConversation());
1158		} else {
1159			this.mConversationFragment.messageListAdapter.updatePreferences();
1160			this.mConversationFragment.messagesView.invalidateViews();
1161			this.mConversationFragment.setupIme();
1162		}
1163
1164		if (this.mPostponedActivityResult != null) {
1165			this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1166		}
1167
1168		if (!forbidProcessingPendings) {
1169			for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1170				Uri foo = i.next();
1171				attachImageToConversation(getSelectedConversation(), foo);
1172			}
1173
1174			for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1175				attachFileToConversation(getSelectedConversation(), i.next());
1176			}
1177
1178			if (mPendingGeoUri != null) {
1179				attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1180				mPendingGeoUri = null;
1181			}
1182		}
1183		forbidProcessingPendings = false;
1184
1185		if (!ExceptionHelper.checkForCrash(this, this.xmppConnectionService)) {
1186			openBatteryOptimizationDialogIfNeeded();
1187		}
1188		setIntent(new Intent());
1189	}
1190
1191	private void handleViewConversationIntent(final Intent intent) {
1192		final String uuid = intent.getStringExtra(CONVERSATION);
1193		final String downloadUuid = intent.getStringExtra(MESSAGE);
1194		final String text = intent.getStringExtra(TEXT);
1195		final String nick = intent.getStringExtra(NICK);
1196		final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1197		if (selectConversationByUuid(uuid)) {
1198			this.mConversationFragment.reInit(getSelectedConversation());
1199			if (nick != null) {
1200				if (pm) {
1201					Jid jid = getSelectedConversation().getJid();
1202					try {
1203						Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1204						this.mConversationFragment.privateMessageWith(next);
1205					} catch (final InvalidJidException ignored) {
1206						//do nothing
1207					}
1208				} else {
1209					this.mConversationFragment.highlightInConference(nick);
1210				}
1211			} else {
1212				this.mConversationFragment.appendText(text);
1213			}
1214			hideConversationsOverview();
1215			openConversation();
1216			if (mContentView instanceof SlidingPaneLayout) {
1217				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1218			}
1219			if (downloadUuid != null) {
1220				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1221				if (message != null) {
1222					startDownloadable(message);
1223				}
1224			}
1225		}
1226	}
1227
1228	private boolean selectConversationByUuid(String uuid) {
1229		if (uuid == null) {
1230			return false;
1231		}
1232		for (Conversation aConversationList : conversationList) {
1233			if (aConversationList.getUuid().equals(uuid)) {
1234				setSelectedConversation(aConversationList);
1235				return true;
1236			}
1237		}
1238		return false;
1239	}
1240
1241	@Override
1242	protected void unregisterListeners() {
1243		super.unregisterListeners();
1244		xmppConnectionService.getNotificationService().setOpenConversation(null);
1245	}
1246
1247	@SuppressLint("NewApi")
1248	private static List<Uri> extractUriFromIntent(final Intent intent) {
1249		List<Uri> uris = new ArrayList<>();
1250		if (intent == null) {
1251			return uris;
1252		}
1253		Uri uri = intent.getData();
1254		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1255			ClipData clipData = intent.getClipData();
1256			for (int i = 0; i < clipData.getItemCount(); ++i) {
1257				uris.add(clipData.getItemAt(i).getUri());
1258			}
1259		} else {
1260			uris.add(uri);
1261		}
1262		return uris;
1263	}
1264
1265	@Override
1266	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1267		super.onActivityResult(requestCode, resultCode, data);
1268		if (resultCode == RESULT_OK) {
1269			if (requestCode == REQUEST_DECRYPT_PGP) {
1270				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1271			} else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1272				// the user chose OpenPGP for encryption and selected his key in the PGP provider
1273				if (xmppConnectionServiceBound) {
1274					if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1275						// associate selected PGP keyId with the account
1276						mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1277						// we need to announce the key as described in XEP-027
1278						announcePgp(mSelectedConversation.getAccount(), null);
1279					} else {
1280						choosePgpSignId(mSelectedConversation.getAccount());
1281					}
1282					this.mPostponedActivityResult = null;
1283				} else {
1284					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1285				}
1286			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1287				if (xmppConnectionServiceBound) {
1288					announcePgp(mSelectedConversation.getAccount(), mSelectedConversation);
1289					this.mPostponedActivityResult = null;
1290				} else {
1291					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1292				}
1293			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1294				mPendingImageUris.clear();
1295				mPendingImageUris.addAll(extractUriFromIntent(data));
1296				if (xmppConnectionServiceBound) {
1297					for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1298						attachImageToConversation(getSelectedConversation(), i.next());
1299					}
1300				}
1301			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1302				final List<Uri> uris = extractUriFromIntent(data);
1303				final Conversation c = getSelectedConversation();
1304				final OnPresenceSelected callback = new OnPresenceSelected() {
1305					@Override
1306					public void onPresenceSelected() {
1307						mPendingFileUris.clear();
1308						mPendingFileUris.addAll(uris);
1309						if (xmppConnectionServiceBound) {
1310							for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1311								attachFileToConversation(c, i.next());
1312							}
1313						}
1314					}
1315				};
1316				if (c == null || c.getMode() == Conversation.MODE_MULTI
1317						|| FileBackend.allFilesUnderSize(this, uris, getMaxHttpUploadSize(c))
1318						|| c.getNextEncryption() == Message.ENCRYPTION_OTR) {
1319					callback.onPresenceSelected();
1320				} else {
1321					selectPresence(c, callback);
1322				}
1323			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1324				if (mPendingImageUris.size() == 1) {
1325					Uri uri = mPendingImageUris.get(0);
1326					if (xmppConnectionServiceBound) {
1327						attachImageToConversation(getSelectedConversation(), uri);
1328						mPendingImageUris.clear();
1329					}
1330					Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1331					intent.setData(uri);
1332					sendBroadcast(intent);
1333				} else {
1334					mPendingImageUris.clear();
1335				}
1336			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1337				double latitude = data.getDoubleExtra("latitude", 0);
1338				double longitude = data.getDoubleExtra("longitude", 0);
1339				this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1340				if (xmppConnectionServiceBound) {
1341					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1342					this.mPendingGeoUri = null;
1343				}
1344			} else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1345				this.forbidProcessingPendings = !xmppConnectionServiceBound;
1346				if (xmppConnectionServiceBound) {
1347					mConversationFragment.onActivityResult(requestCode, resultCode, data);
1348					this.mPostponedActivityResult = null;
1349				} else {
1350					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1351				}
1352
1353			}
1354		} else {
1355			mPendingImageUris.clear();
1356			mPendingFileUris.clear();
1357			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1358				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1359			}
1360			if (requestCode == REQUEST_BATTERY_OP) {
1361				setNeverAskForBatteryOptimizationsAgain();
1362			}
1363		}
1364	}
1365
1366	private long getMaxHttpUploadSize(Conversation conversation) {
1367		return conversation.getAccount().getXmppConnection().getFeatures().getMaxHttpUploadSize();
1368	}
1369
1370	private void setNeverAskForBatteryOptimizationsAgain() {
1371		getPreferences().edit().putBoolean("show_battery_optimization", false).commit();
1372	}
1373
1374	private void openBatteryOptimizationDialogIfNeeded() {
1375		if (hasAccountWithoutPush()
1376				&& isOptimizingBattery()
1377				&& getPreferences().getBoolean("show_battery_optimization", true)) {
1378			AlertDialog.Builder builder = new AlertDialog.Builder(this);
1379			builder.setTitle(R.string.battery_optimizations_enabled);
1380			builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1381			builder.setPositiveButton(R.string.next, new OnClickListener() {
1382				@Override
1383				public void onClick(DialogInterface dialog, int which) {
1384					Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1385					Uri uri = Uri.parse("package:" + getPackageName());
1386					intent.setData(uri);
1387					startActivityForResult(intent, REQUEST_BATTERY_OP);
1388				}
1389			});
1390			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1391				builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1392					@Override
1393					public void onDismiss(DialogInterface dialog) {
1394						setNeverAskForBatteryOptimizationsAgain();
1395					}
1396				});
1397			}
1398			builder.create().show();
1399		}
1400	}
1401
1402	private boolean hasAccountWithoutPush() {
1403		for(Account account : xmppConnectionService.getAccounts()) {
1404			if (account.getStatus() != Account.State.DISABLED
1405					&& !xmppConnectionService.getPushManagementService().available(account)) {
1406				return true;
1407			}
1408		}
1409		return false;
1410	}
1411
1412	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1413		if (conversation == null) {
1414			return;
1415		}
1416		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1417
1418			@Override
1419			public void success(Message message) {
1420				xmppConnectionService.sendMessage(message);
1421			}
1422
1423			@Override
1424			public void error(int errorCode, Message object) {
1425
1426			}
1427
1428			@Override
1429			public void userInputRequried(PendingIntent pi, Message object) {
1430
1431			}
1432		});
1433	}
1434
1435	private void attachFileToConversation(Conversation conversation, Uri uri) {
1436		if (conversation == null) {
1437			return;
1438		}
1439		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1440		prepareFileToast.show();
1441		xmppConnectionService.attachFileToConversation(conversation, uri, new UiCallback<Message>() {
1442			@Override
1443			public void success(Message message) {
1444				hidePrepareFileToast(prepareFileToast);
1445				xmppConnectionService.sendMessage(message);
1446			}
1447
1448			@Override
1449			public void error(int errorCode, Message message) {
1450				hidePrepareFileToast(prepareFileToast);
1451				displayErrorDialog(errorCode);
1452			}
1453
1454			@Override
1455			public void userInputRequried(PendingIntent pi, Message message) {
1456
1457			}
1458		});
1459	}
1460
1461	private void attachImageToConversation(Conversation conversation, Uri uri) {
1462		if (conversation == null) {
1463			return;
1464		}
1465		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1466		prepareFileToast.show();
1467		xmppConnectionService.attachImageToConversation(conversation, uri,
1468				new UiCallback<Message>() {
1469
1470					@Override
1471					public void userInputRequried(PendingIntent pi, Message object) {
1472						hidePrepareFileToast(prepareFileToast);
1473					}
1474
1475					@Override
1476					public void success(Message message) {
1477						hidePrepareFileToast(prepareFileToast);
1478						xmppConnectionService.sendMessage(message);
1479					}
1480
1481					@Override
1482					public void error(int error, Message message) {
1483						hidePrepareFileToast(prepareFileToast);
1484						displayErrorDialog(error);
1485					}
1486				});
1487	}
1488
1489	private void hidePrepareFileToast(final Toast prepareFileToast) {
1490		if (prepareFileToast != null) {
1491			runOnUiThread(new Runnable() {
1492
1493				@Override
1494				public void run() {
1495					prepareFileToast.cancel();
1496				}
1497			});
1498		}
1499	}
1500
1501	public void updateConversationList() {
1502		xmppConnectionService
1503			.populateWithOrderedConversations(conversationList);
1504		if (swipedConversation != null) {
1505			if (swipedConversation.isRead()) {
1506				conversationList.remove(swipedConversation);
1507			} else {
1508				listView.discardUndo();
1509			}
1510		}
1511		listAdapter.notifyDataSetChanged();
1512	}
1513
1514	public void runIntent(PendingIntent pi, int requestCode) {
1515		try {
1516			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1517					null, 0, 0, 0);
1518		} catch (final SendIntentException ignored) {
1519		}
1520	}
1521
1522	public void encryptTextMessage(Message message) {
1523		xmppConnectionService.getPgpEngine().encrypt(message,
1524				new UiCallback<Message>() {
1525
1526					@Override
1527					public void userInputRequried(PendingIntent pi,
1528												  Message message) {
1529						ConversationActivity.this.runIntent(pi,
1530								ConversationActivity.REQUEST_SEND_MESSAGE);
1531					}
1532
1533					@Override
1534					public void success(Message message) {
1535						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1536						xmppConnectionService.sendMessage(message);
1537					}
1538
1539					@Override
1540					public void error(int error, Message message) {
1541
1542					}
1543				});
1544	}
1545
1546	public boolean useSendButtonToIndicateStatus() {
1547		return getPreferences().getBoolean("send_button_status", false);
1548	}
1549
1550	public boolean indicateReceived() {
1551		return getPreferences().getBoolean("indicate_received", false);
1552	}
1553
1554	public boolean useWhiteBackground() {
1555		return getPreferences().getBoolean("use_white_background",false);
1556	}
1557
1558	protected boolean trustKeysIfNeeded(int requestCode) {
1559		return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1560	}
1561
1562	protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1563		AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1564		final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1565		boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1566		boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED).isEmpty();
1567		boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED, targets).isEmpty();
1568		boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1569		boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1570		if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1571			axolotlService.createSessionsIfNeeded(mSelectedConversation);
1572			Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1573			String[] contacts = new String[targets.size()];
1574			for(int i = 0; i < contacts.length; ++i) {
1575				contacts[i] = targets.get(i).toString();
1576			}
1577			intent.putExtra("contacts", contacts);
1578			intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1579			intent.putExtra("choice", attachmentChoice);
1580			intent.putExtra("conversation",mSelectedConversation.getUuid());
1581			startActivityForResult(intent, requestCode);
1582			return true;
1583		} else {
1584			return false;
1585		}
1586	}
1587
1588	@Override
1589	protected void refreshUiReal() {
1590		updateConversationList();
1591		if (conversationList.size() > 0) {
1592			if (!this.mConversationFragment.isAdded()) {
1593				Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1594			}
1595			ConversationActivity.this.mConversationFragment.updateMessages();
1596			updateActionBarTitle();
1597			invalidateOptionsMenu();
1598		} else {
1599			Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1600		}
1601	}
1602
1603	@Override
1604	public void onAccountUpdate() {
1605		this.refreshUi();
1606	}
1607
1608	@Override
1609	public void onConversationUpdate() {
1610		this.refreshUi();
1611	}
1612
1613	@Override
1614	public void onRosterUpdate() {
1615		this.refreshUi();
1616	}
1617
1618	@Override
1619	public void OnUpdateBlocklist(Status status) {
1620		this.refreshUi();
1621	}
1622
1623	public void unblockConversation(final Blockable conversation) {
1624		xmppConnectionService.sendUnblockRequest(conversation);
1625	}
1626
1627	public boolean enterIsSend() {
1628		return getPreferences().getBoolean("enter_is_send",false);
1629	}
1630
1631	@Override
1632	public void onShowErrorToast(final int resId) {
1633		runOnUiThread(new Runnable() {
1634			@Override
1635			public void run() {
1636				Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1637			}
1638		});
1639	}
1640
1641	public boolean highlightSelectedConversations() {
1642		return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1643	}
1644
1645	public void setMessagesLoaded() {
1646		if (mConversationFragment != null) {
1647			mConversationFragment.setMessagesLoaded();
1648			mConversationFragment.updateMessages();
1649		}
1650	}
1651}