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.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
 449						intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
 450						intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
 451						mPendingImageUris.clear();
 452						mPendingImageUris.add(uri);
 453						break;
 454					case ATTACHMENT_CHOICE_CHOOSE_FILE:
 455						chooser = true;
 456						intent.setType("*/*");
 457						intent.addCategory(Intent.CATEGORY_OPENABLE);
 458						intent.setAction(Intent.ACTION_GET_CONTENT);
 459						break;
 460					case ATTACHMENT_CHOICE_RECORD_VOICE:
 461						intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
 462						fallbackPackageId = "eu.siacs.conversations.voicerecorder";
 463						break;
 464					case ATTACHMENT_CHOICE_LOCATION:
 465						intent.setAction("eu.siacs.conversations.location.request");
 466						fallbackPackageId = "eu.siacs.conversations.sharelocation";
 467						break;
 468				}
 469				if (intent.resolveActivity(getPackageManager()) != null) {
 470					if (chooser) {
 471						startActivityForResult(
 472								Intent.createChooser(intent, getString(R.string.perform_action_with)),
 473								attachmentChoice);
 474					} else {
 475						startActivityForResult(intent, attachmentChoice);
 476					}
 477				} else if (fallbackPackageId != null) {
 478					startActivity(getInstallApkIntent(fallbackPackageId));
 479				}
 480			}
 481		};
 482		if ((account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) && encryption != Message.ENCRYPTION_OTR) {
 483			conversation.setNextCounterpart(null);
 484			callback.onPresenceSelected();
 485		} else {
 486			selectPresence(conversation, callback);
 487		}
 488	}
 489
 490	private Intent getInstallApkIntent(final String packageId) {
 491		Intent intent = new Intent(Intent.ACTION_VIEW);
 492		intent.setData(Uri.parse("market://details?id=" + packageId));
 493		if (intent.resolveActivity(getPackageManager()) != null) {
 494			return intent;
 495		} else {
 496			intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
 497			return intent;
 498		}
 499	}
 500
 501	public void attachFile(final int attachmentChoice) {
 502		if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
 503			if (!hasStoragePermission(attachmentChoice)) {
 504				return;
 505			}
 506		}
 507		switch (attachmentChoice) {
 508			case ATTACHMENT_CHOICE_LOCATION:
 509				getPreferences().edit().putString("recently_used_quick_action", "location").apply();
 510				break;
 511			case ATTACHMENT_CHOICE_RECORD_VOICE:
 512				getPreferences().edit().putString("recently_used_quick_action", "voice").apply();
 513				break;
 514			case ATTACHMENT_CHOICE_TAKE_PHOTO:
 515				getPreferences().edit().putString("recently_used_quick_action", "photo").apply();
 516				break;
 517			case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 518				getPreferences().edit().putString("recently_used_quick_action", "picture").apply();
 519				break;
 520		}
 521		final Conversation conversation = getSelectedConversation();
 522		final int encryption = conversation.getNextEncryption();
 523		final int mode = conversation.getMode();
 524		if (encryption == Message.ENCRYPTION_PGP) {
 525			if (hasPgp()) {
 526				if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
 527					xmppConnectionService.getPgpEngine().hasKey(
 528							conversation.getContact(),
 529							new UiCallback<Contact>() {
 530
 531								@Override
 532								public void userInputRequried(PendingIntent pi, Contact contact) {
 533									ConversationActivity.this.runIntent(pi, attachmentChoice);
 534								}
 535
 536								@Override
 537								public void success(Contact contact) {
 538									selectPresenceToAttachFile(attachmentChoice, encryption);
 539								}
 540
 541								@Override
 542								public void error(int error, Contact contact) {
 543									replaceToast(getString(error));
 544								}
 545							});
 546				} else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
 547					if (!conversation.getMucOptions().everybodyHasKeys()) {
 548						Toast warning = Toast
 549								.makeText(this,
 550										R.string.missing_public_keys,
 551										Toast.LENGTH_LONG);
 552						warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
 553						warning.show();
 554					}
 555					selectPresenceToAttachFile(attachmentChoice, encryption);
 556				} else {
 557					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 558							.findFragmentByTag("conversation");
 559					if (fragment != null) {
 560						fragment.showNoPGPKeyDialog(false,
 561								new OnClickListener() {
 562
 563									@Override
 564									public void onClick(DialogInterface dialog,
 565														int which) {
 566										conversation
 567												.setNextEncryption(Message.ENCRYPTION_NONE);
 568										xmppConnectionService.databaseBackend
 569												.updateConversation(conversation);
 570										selectPresenceToAttachFile(attachmentChoice, Message.ENCRYPTION_NONE);
 571									}
 572								});
 573					}
 574				}
 575			} else {
 576				showInstallPgpDialog();
 577			}
 578		} else {
 579			if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
 580				selectPresenceToAttachFile(attachmentChoice, encryption);
 581			}
 582		}
 583	}
 584
 585	@Override
 586	public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
 587		if (grantResults.length > 0)
 588			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 589				if (requestCode == REQUEST_START_DOWNLOAD) {
 590					if (this.mPendingDownloadableMessage != null) {
 591						startDownloadable(this.mPendingDownloadableMessage);
 592					}
 593				} else {
 594					attachFile(requestCode);
 595				}
 596			} else {
 597				Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
 598			}
 599	}
 600
 601	public void startDownloadable(Message message) {
 602		if (!hasStoragePermission(ConversationActivity.REQUEST_START_DOWNLOAD)) {
 603			this.mPendingDownloadableMessage = message;
 604			return;
 605		}
 606		Transferable transferable = message.getTransferable();
 607		if (transferable != null) {
 608			if (!transferable.start()) {
 609				Toast.makeText(this, R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
 610			}
 611		} else if (message.treatAsDownloadable() != Message.Decision.NEVER) {
 612			xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
 613		}
 614	}
 615
 616	@Override
 617	public boolean onOptionsItemSelected(final MenuItem item) {
 618		if (item.getItemId() == android.R.id.home) {
 619			showConversationsOverview();
 620			return true;
 621		} else if (item.getItemId() == R.id.action_add) {
 622			startActivity(new Intent(this, StartConversationActivity.class));
 623			return true;
 624		} else if (getSelectedConversation() != null) {
 625			switch (item.getItemId()) {
 626				case R.id.action_attach_file:
 627					attachFileDialog();
 628					break;
 629				case R.id.action_archive:
 630					this.endConversation(getSelectedConversation());
 631					break;
 632				case R.id.action_contact_details:
 633					switchToContactDetails(getSelectedConversation().getContact());
 634					break;
 635				case R.id.action_muc_details:
 636					Intent intent = new Intent(this,
 637							ConferenceDetailsActivity.class);
 638					intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 639					intent.putExtra("uuid", getSelectedConversation().getUuid());
 640					startActivity(intent);
 641					break;
 642				case R.id.action_invite:
 643					inviteToConversation(getSelectedConversation());
 644					break;
 645				case R.id.action_security:
 646					selectEncryptionDialog(getSelectedConversation());
 647					break;
 648				case R.id.action_clear_history:
 649					clearHistoryDialog(getSelectedConversation());
 650					break;
 651				case R.id.action_mute:
 652					muteConversationDialog(getSelectedConversation());
 653					break;
 654				case R.id.action_unmute:
 655					unmuteConversation(getSelectedConversation());
 656					break;
 657				case R.id.action_block:
 658					BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
 659					break;
 660				case R.id.action_unblock:
 661					BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
 662					break;
 663				default:
 664					break;
 665			}
 666			return super.onOptionsItemSelected(item);
 667		} else {
 668			return super.onOptionsItemSelected(item);
 669		}
 670	}
 671
 672	public void endConversation(Conversation conversation) {
 673		endConversation(conversation, true, true);
 674	}
 675
 676	public void endConversation(Conversation conversation, boolean showOverview, boolean reinit) {
 677		if (showOverview) {
 678			showConversationsOverview();
 679		}
 680		xmppConnectionService.archiveConversation(conversation);
 681		if (reinit) {
 682			if (conversationList.size() > 0) {
 683				setSelectedConversation(conversationList.get(0));
 684				this.mConversationFragment.reInit(getSelectedConversation());
 685			} else {
 686				setSelectedConversation(null);
 687				if (mRedirected.compareAndSet(false, true)) {
 688					Intent intent = new Intent(this, StartConversationActivity.class);
 689					intent.putExtra("init", true);
 690					startActivity(intent);
 691					finish();
 692				}
 693			}
 694		}
 695	}
 696
 697	@SuppressLint("InflateParams")
 698	protected void clearHistoryDialog(final Conversation conversation) {
 699		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 700		builder.setTitle(getString(R.string.clear_conversation_history));
 701		View dialogView = getLayoutInflater().inflate(
 702				R.layout.dialog_clear_history, null);
 703		final CheckBox endConversationCheckBox = (CheckBox) dialogView
 704				.findViewById(R.id.end_conversation_checkbox);
 705		builder.setView(dialogView);
 706		builder.setNegativeButton(getString(R.string.cancel), null);
 707		builder.setPositiveButton(getString(R.string.delete_messages),
 708				new OnClickListener() {
 709
 710					@Override
 711					public void onClick(DialogInterface dialog, int which) {
 712						ConversationActivity.this.xmppConnectionService.clearConversationHistory(conversation);
 713						if (endConversationCheckBox.isChecked()) {
 714							endConversation(conversation);
 715						} else {
 716							updateConversationList();
 717							ConversationActivity.this.mConversationFragment.updateMessages();
 718						}
 719					}
 720				});
 721		builder.create().show();
 722	}
 723
 724	protected void attachFileDialog() {
 725		View menuAttachFile = findViewById(R.id.action_attach_file);
 726		if (menuAttachFile == null) {
 727			return;
 728		}
 729		PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
 730		attachFilePopup.inflate(R.menu.attachment_choices);
 731		if (new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION).resolveActivity(getPackageManager()) == null) {
 732			attachFilePopup.getMenu().findItem(R.id.attach_record_voice).setVisible(false);
 733		}
 734		if (new Intent("eu.siacs.conversations.location.request").resolveActivity(getPackageManager()) == null) {
 735			attachFilePopup.getMenu().findItem(R.id.attach_location).setVisible(false);
 736		}
 737		attachFilePopup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 738
 739			@Override
 740			public boolean onMenuItemClick(MenuItem item) {
 741				switch (item.getItemId()) {
 742					case R.id.attach_choose_picture:
 743						attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 744						break;
 745					case R.id.attach_take_picture:
 746						attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
 747						break;
 748					case R.id.attach_choose_file:
 749						attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
 750						break;
 751					case R.id.attach_record_voice:
 752						attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
 753						break;
 754					case R.id.attach_location:
 755						attachFile(ATTACHMENT_CHOICE_LOCATION);
 756						break;
 757				}
 758				return false;
 759			}
 760		});
 761		attachFilePopup.show();
 762	}
 763
 764	public void verifyOtrSessionDialog(final Conversation conversation, View view) {
 765		if (!conversation.hasValidOtrSession() || conversation.getOtrSession().getSessionStatus() != SessionStatus.ENCRYPTED) {
 766			Toast.makeText(this, R.string.otr_session_not_started, Toast.LENGTH_LONG).show();
 767			return;
 768		}
 769		if (view == null) {
 770			return;
 771		}
 772		PopupMenu popup = new PopupMenu(this, view);
 773		popup.inflate(R.menu.verification_choices);
 774		popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 775			@Override
 776			public boolean onMenuItemClick(MenuItem menuItem) {
 777				Intent intent = new Intent(ConversationActivity.this, VerifyOTRActivity.class);
 778				intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
 779				intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
 780				intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
 781				switch (menuItem.getItemId()) {
 782					case R.id.scan_fingerprint:
 783						intent.putExtra("mode", VerifyOTRActivity.MODE_SCAN_FINGERPRINT);
 784						break;
 785					case R.id.ask_question:
 786						intent.putExtra("mode", VerifyOTRActivity.MODE_ASK_QUESTION);
 787						break;
 788					case R.id.manual_verification:
 789						intent.putExtra("mode", VerifyOTRActivity.MODE_MANUAL_VERIFICATION);
 790						break;
 791				}
 792				startActivity(intent);
 793				return true;
 794			}
 795		});
 796		popup.show();
 797	}
 798
 799	protected void selectEncryptionDialog(final Conversation conversation) {
 800		View menuItemView = findViewById(R.id.action_security);
 801		if (menuItemView == null) {
 802			return;
 803		}
 804		PopupMenu popup = new PopupMenu(this, menuItemView);
 805		final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 806				.findFragmentByTag("conversation");
 807		if (fragment != null) {
 808			popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 809
 810				@Override
 811				public boolean onMenuItemClick(MenuItem item) {
 812					switch (item.getItemId()) {
 813						case R.id.encryption_choice_none:
 814							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 815							item.setChecked(true);
 816							break;
 817						case R.id.encryption_choice_otr:
 818							conversation.setNextEncryption(Message.ENCRYPTION_OTR);
 819							item.setChecked(true);
 820							break;
 821						case R.id.encryption_choice_pgp:
 822							if (hasPgp()) {
 823								if (conversation.getAccount().getPgpSignature() != null) {
 824									conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 825									item.setChecked(true);
 826								} else {
 827									announcePgp(conversation.getAccount(), conversation, onOpenPGPKeyPublished);
 828								}
 829							} else {
 830								showInstallPgpDialog();
 831							}
 832							break;
 833						case R.id.encryption_choice_axolotl:
 834							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
 835									+ "Enabled axolotl for Contact " + conversation.getContact().getJid());
 836							conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
 837							item.setChecked(true);
 838							break;
 839						default:
 840							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 841							break;
 842					}
 843					xmppConnectionService.databaseBackend.updateConversation(conversation);
 844					fragment.updateChatMsgHint();
 845					invalidateOptionsMenu();
 846					refreshUi();
 847					return true;
 848				}
 849			});
 850			popup.inflate(R.menu.encryption_choices);
 851			MenuItem otr = popup.getMenu().findItem(R.id.encryption_choice_otr);
 852			MenuItem none = popup.getMenu().findItem(R.id.encryption_choice_none);
 853			MenuItem pgp = popup.getMenu().findItem(R.id.encryption_choice_pgp);
 854			MenuItem axolotl = popup.getMenu().findItem(R.id.encryption_choice_axolotl);
 855			pgp.setVisible(Config.supportOpenPgp());
 856			none.setVisible(Config.supportUnencrypted() || conversation.getMode() == Conversation.MODE_MULTI);
 857			otr.setVisible(Config.supportOtr());
 858			axolotl.setVisible(Config.supportOmemo());
 859			if (conversation.getMode() == Conversation.MODE_MULTI) {
 860				otr.setVisible(false);
 861			}
 862			if (!conversation.getAccount().getAxolotlService().isConversationAxolotlCapable(conversation)) {
 863				axolotl.setEnabled(false);
 864			}
 865			switch (conversation.getNextEncryption()) {
 866				case Message.ENCRYPTION_NONE:
 867					none.setChecked(true);
 868					break;
 869				case Message.ENCRYPTION_OTR:
 870					otr.setChecked(true);
 871					break;
 872				case Message.ENCRYPTION_PGP:
 873					pgp.setChecked(true);
 874					break;
 875				case Message.ENCRYPTION_AXOLOTL:
 876					axolotl.setChecked(true);
 877					break;
 878				default:
 879					none.setChecked(true);
 880					break;
 881			}
 882			popup.show();
 883		}
 884	}
 885
 886	protected void muteConversationDialog(final Conversation conversation) {
 887		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 888		builder.setTitle(R.string.disable_notifications);
 889		final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
 890		builder.setItems(R.array.mute_options_descriptions,
 891				new OnClickListener() {
 892
 893					@Override
 894					public void onClick(final DialogInterface dialog, final int which) {
 895						final long till;
 896						if (durations[which] == -1) {
 897							till = Long.MAX_VALUE;
 898						} else {
 899							till = System.currentTimeMillis() + (durations[which] * 1000);
 900						}
 901						conversation.setMutedTill(till);
 902						ConversationActivity.this.xmppConnectionService.databaseBackend
 903								.updateConversation(conversation);
 904						updateConversationList();
 905						ConversationActivity.this.mConversationFragment.updateMessages();
 906						invalidateOptionsMenu();
 907					}
 908				});
 909		builder.create().show();
 910	}
 911
 912	public void unmuteConversation(final Conversation conversation) {
 913		conversation.setMutedTill(0);
 914		this.xmppConnectionService.databaseBackend.updateConversation(conversation);
 915		updateConversationList();
 916		ConversationActivity.this.mConversationFragment.updateMessages();
 917		invalidateOptionsMenu();
 918	}
 919
 920	@Override
 921	public void onBackPressed() {
 922		if (!isConversationsOverviewVisable()) {
 923			showConversationsOverview();
 924		} else {
 925			moveTaskToBack(true);
 926		}
 927	}
 928
 929	@Override
 930	public boolean onKeyUp(int key, KeyEvent event) {
 931		int rotation = getWindowManager().getDefaultDisplay().getRotation();
 932		final int upKey;
 933		final int downKey;
 934		switch (rotation) {
 935			case Surface.ROTATION_90:
 936				upKey = KeyEvent.KEYCODE_DPAD_LEFT;
 937				downKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 938				break;
 939			case Surface.ROTATION_180:
 940				upKey = KeyEvent.KEYCODE_DPAD_DOWN;
 941				downKey = KeyEvent.KEYCODE_DPAD_UP;
 942				break;
 943			case Surface.ROTATION_270:
 944				upKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 945				downKey = KeyEvent.KEYCODE_DPAD_LEFT;
 946				break;
 947			default:
 948				upKey = KeyEvent.KEYCODE_DPAD_UP;
 949				downKey = KeyEvent.KEYCODE_DPAD_DOWN;
 950		}
 951		final boolean modifier = event.isCtrlPressed() || (event.getMetaState() & KeyEvent.META_ALT_LEFT_ON) != 0;
 952		if (modifier && key == KeyEvent.KEYCODE_TAB && isConversationsOverviewHideable()) {
 953			toggleConversationsOverview();
 954			return true;
 955		} else if (modifier && key == KeyEvent.KEYCODE_SPACE) {
 956			startActivity(new Intent(this, StartConversationActivity.class));
 957			return true;
 958		} else if (modifier && key == downKey) {
 959			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
 960				showConversationsOverview();
 961				;
 962			}
 963			return selectDownConversation();
 964		} else if (modifier && key == upKey) {
 965			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
 966				showConversationsOverview();
 967			}
 968			return selectUpConversation();
 969		} else if (modifier && key == KeyEvent.KEYCODE_1) {
 970			return openConversationByIndex(0);
 971		} else if (modifier && key == KeyEvent.KEYCODE_2) {
 972			return openConversationByIndex(1);
 973		} else if (modifier && key == KeyEvent.KEYCODE_3) {
 974			return openConversationByIndex(2);
 975		} else if (modifier && key == KeyEvent.KEYCODE_4) {
 976			return openConversationByIndex(3);
 977		} else if (modifier && key == KeyEvent.KEYCODE_5) {
 978			return openConversationByIndex(4);
 979		} else if (modifier && key == KeyEvent.KEYCODE_6) {
 980			return openConversationByIndex(5);
 981		} else if (modifier && key == KeyEvent.KEYCODE_7) {
 982			return openConversationByIndex(6);
 983		} else if (modifier && key == KeyEvent.KEYCODE_8) {
 984			return openConversationByIndex(7);
 985		} else if (modifier && key == KeyEvent.KEYCODE_9) {
 986			return openConversationByIndex(8);
 987		} else if (modifier && key == KeyEvent.KEYCODE_0) {
 988			return openConversationByIndex(9);
 989		} else {
 990			return super.onKeyUp(key, event);
 991		}
 992	}
 993
 994	private void toggleConversationsOverview() {
 995		if (isConversationsOverviewVisable()) {
 996			hideConversationsOverview();
 997			if (mConversationFragment != null) {
 998				mConversationFragment.setFocusOnInputField();
 999			}
1000		} else {
1001			showConversationsOverview();
1002		}
1003	}
1004
1005	private boolean selectUpConversation() {
1006		if (this.mSelectedConversation != null) {
1007			int index = this.conversationList.indexOf(this.mSelectedConversation);
1008			if (index > 0) {
1009				return openConversationByIndex(index - 1);
1010			}
1011		}
1012		return false;
1013	}
1014
1015	private boolean selectDownConversation() {
1016		if (this.mSelectedConversation != null) {
1017			int index = this.conversationList.indexOf(this.mSelectedConversation);
1018			if (index != -1 && index < this.conversationList.size() - 1) {
1019				return openConversationByIndex(index + 1);
1020			}
1021		}
1022		return false;
1023	}
1024
1025	private boolean openConversationByIndex(int index) {
1026		try {
1027			this.conversationWasSelectedByKeyboard = true;
1028			setSelectedConversation(this.conversationList.get(index));
1029			this.mConversationFragment.reInit(getSelectedConversation());
1030			if (index > listView.getLastVisiblePosition() - 1 || index < listView.getFirstVisiblePosition() + 1) {
1031				this.listView.setSelection(index);
1032			}
1033			openConversation();
1034			return true;
1035		} catch (IndexOutOfBoundsException e) {
1036			return false;
1037		}
1038	}
1039
1040	@Override
1041	protected void onNewIntent(final Intent intent) {
1042		if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1043			mOpenConverstaion = null;
1044			if (xmppConnectionServiceBound) {
1045				handleViewConversationIntent(intent);
1046				intent.setAction(Intent.ACTION_MAIN);
1047			} else {
1048				setIntent(intent);
1049			}
1050		}
1051	}
1052
1053	@Override
1054	public void onStart() {
1055		super.onStart();
1056		this.mRedirected.set(false);
1057		if (this.xmppConnectionServiceBound) {
1058			this.onBackendConnected();
1059		}
1060		if (conversationList.size() >= 1) {
1061			this.onConversationUpdate();
1062		}
1063	}
1064
1065	@Override
1066	public void onPause() {
1067		listView.discardUndo();
1068		super.onPause();
1069		this.mActivityPaused = true;
1070	}
1071
1072	@Override
1073	public void onResume() {
1074		super.onResume();
1075		final int theme = findTheme();
1076		final boolean usingEnterKey = usingEnterKey();
1077		if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
1078			recreate();
1079		}
1080		this.mActivityPaused = false;
1081
1082		if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
1083			sendReadMarkerIfNecessary(getSelectedConversation());
1084		}
1085
1086	}
1087
1088	@Override
1089	public void onSaveInstanceState(final Bundle savedInstanceState) {
1090		Conversation conversation = getSelectedConversation();
1091		if (conversation != null) {
1092			savedInstanceState.putString(STATE_OPEN_CONVERSATION, conversation.getUuid());
1093		} else {
1094			savedInstanceState.remove(STATE_OPEN_CONVERSATION);
1095		}
1096		savedInstanceState.putBoolean(STATE_PANEL_OPEN, isConversationsOverviewVisable());
1097		if (this.mPendingImageUris.size() >= 1) {
1098			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1099		} else {
1100			savedInstanceState.remove(STATE_PENDING_URI);
1101		}
1102		super.onSaveInstanceState(savedInstanceState);
1103	}
1104
1105	private void clearPending() {
1106		mPendingImageUris.clear();
1107		mPendingFileUris.clear();
1108		mPendingGeoUri = null;
1109		mPostponedActivityResult = null;
1110	}
1111
1112	@Override
1113	void onBackendConnected() {
1114		this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1115		updateConversationList();
1116
1117		if (mPendingConferenceInvite != null) {
1118			if (mPendingConferenceInvite.execute(this)) {
1119				mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
1120				mToast.show();
1121			}
1122			mPendingConferenceInvite = null;
1123		}
1124
1125		final Intent intent = getIntent();
1126
1127		if (xmppConnectionService.getAccounts().size() == 0) {
1128			if (mRedirected.compareAndSet(false, true)) {
1129				if (Config.X509_VERIFICATION) {
1130					startActivity(new Intent(this, ManageAccountActivity.class));
1131				} else if (Config.MAGIC_CREATE_DOMAIN != null) {
1132					startActivity(new Intent(this, WelcomeActivity.class));
1133				} else {
1134					Intent editAccount = new Intent(this, EditAccountActivity.class);
1135					editAccount.putExtra("init",true);
1136					startActivity(editAccount);
1137				}
1138				finish();
1139			}
1140		} else if (conversationList.size() <= 0) {
1141			if (mRedirected.compareAndSet(false, true)) {
1142				Account pendingAccount = xmppConnectionService.getPendingAccount();
1143				if (pendingAccount == null) {
1144					Intent startConversationActivity = new Intent(this, StartConversationActivity.class);
1145					intent.putExtra("init", true);
1146					startActivity(startConversationActivity);
1147				} else {
1148					switchToAccount(pendingAccount, true);
1149				}
1150				finish();
1151			}
1152		} else if (selectConversationByUuid(mOpenConverstaion)) {
1153			if (mPanelOpen) {
1154				showConversationsOverview();
1155			} else {
1156				if (isConversationsOverviewHideable()) {
1157					openConversation();
1158					updateActionBarTitle(true);
1159				}
1160			}
1161			this.mConversationFragment.reInit(getSelectedConversation());
1162			mOpenConverstaion = null;
1163		} else if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1164			clearPending();
1165			handleViewConversationIntent(intent);
1166			intent.setAction(Intent.ACTION_MAIN);
1167		} else if (getSelectedConversation() == null) {
1168			showConversationsOverview();
1169			clearPending();
1170			setSelectedConversation(conversationList.get(0));
1171			this.mConversationFragment.reInit(getSelectedConversation());
1172		} else {
1173			this.mConversationFragment.messageListAdapter.updatePreferences();
1174			this.mConversationFragment.messagesView.invalidateViews();
1175			this.mConversationFragment.setupIme();
1176		}
1177
1178		if (this.mPostponedActivityResult != null) {
1179			this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1180		}
1181
1182		if (!forbidProcessingPendings) {
1183			for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1184				Uri foo = i.next();
1185				attachImageToConversation(getSelectedConversation(), foo);
1186			}
1187
1188			for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1189				attachFileToConversation(getSelectedConversation(), i.next());
1190			}
1191
1192			if (mPendingGeoUri != null) {
1193				attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1194				mPendingGeoUri = null;
1195			}
1196		}
1197		forbidProcessingPendings = false;
1198
1199		if (!ExceptionHelper.checkForCrash(this, this.xmppConnectionService)) {
1200			openBatteryOptimizationDialogIfNeeded();
1201		}
1202	}
1203
1204	private void handleViewConversationIntent(final Intent intent) {
1205		final String uuid = intent.getStringExtra(CONVERSATION);
1206		final String downloadUuid = intent.getStringExtra(EXTRA_DOWNLOAD_UUID);
1207		final String text = intent.getStringExtra(TEXT);
1208		final String nick = intent.getStringExtra(NICK);
1209		final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1210		if (selectConversationByUuid(uuid)) {
1211			this.mConversationFragment.reInit(getSelectedConversation());
1212			if (nick != null) {
1213				if (pm) {
1214					Jid jid = getSelectedConversation().getJid();
1215					try {
1216						Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1217						this.mConversationFragment.privateMessageWith(next);
1218					} catch (final InvalidJidException ignored) {
1219						//do nothing
1220					}
1221				} else {
1222					this.mConversationFragment.highlightInConference(nick);
1223				}
1224			} else {
1225				this.mConversationFragment.appendText(text);
1226			}
1227			hideConversationsOverview();
1228			openConversation();
1229			if (mContentView instanceof SlidingPaneLayout) {
1230				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1231			}
1232			if (downloadUuid != null) {
1233				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1234				if (message != null) {
1235					startDownloadable(message);
1236				}
1237			}
1238		}
1239	}
1240
1241	private boolean selectConversationByUuid(String uuid) {
1242		if (uuid == null) {
1243			return false;
1244		}
1245		for (Conversation aConversationList : conversationList) {
1246			if (aConversationList.getUuid().equals(uuid)) {
1247				setSelectedConversation(aConversationList);
1248				return true;
1249			}
1250		}
1251		return false;
1252	}
1253
1254	@Override
1255	protected void unregisterListeners() {
1256		super.unregisterListeners();
1257		xmppConnectionService.getNotificationService().setOpenConversation(null);
1258	}
1259
1260	@SuppressLint("NewApi")
1261	private static List<Uri> extractUriFromIntent(final Intent intent) {
1262		List<Uri> uris = new ArrayList<>();
1263		if (intent == null) {
1264			return uris;
1265		}
1266		Uri uri = intent.getData();
1267		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1268			final ClipData clipData = intent.getClipData();
1269			if (clipData != null) {
1270				for (int i = 0; i < clipData.getItemCount(); ++i) {
1271					uris.add(clipData.getItemAt(i).getUri());
1272				}
1273			}
1274		} else {
1275			uris.add(uri);
1276		}
1277		return uris;
1278	}
1279
1280	@Override
1281	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1282		super.onActivityResult(requestCode, resultCode, data);
1283		if (resultCode == RESULT_OK) {
1284			if (requestCode == REQUEST_DECRYPT_PGP) {
1285				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1286			} else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1287				// the user chose OpenPGP for encryption and selected his key in the PGP provider
1288				if (xmppConnectionServiceBound) {
1289					if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1290						// associate selected PGP keyId with the account
1291						mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1292						// we need to announce the key as described in XEP-027
1293						announcePgp(mSelectedConversation.getAccount(), null, onOpenPGPKeyPublished);
1294					} else {
1295						choosePgpSignId(mSelectedConversation.getAccount());
1296					}
1297					this.mPostponedActivityResult = null;
1298				} else {
1299					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1300				}
1301			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1302				if (xmppConnectionServiceBound) {
1303					announcePgp(mSelectedConversation.getAccount(), mSelectedConversation, onOpenPGPKeyPublished);
1304					this.mPostponedActivityResult = null;
1305				} else {
1306					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1307				}
1308			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1309				mPendingImageUris.clear();
1310				mPendingImageUris.addAll(extractUriFromIntent(data));
1311				if (xmppConnectionServiceBound) {
1312					for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1313						attachImageToConversation(getSelectedConversation(), i.next());
1314					}
1315				}
1316			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1317				final List<Uri> uris = extractUriFromIntent(data);
1318				final Conversation c = getSelectedConversation();
1319				final OnPresenceSelected callback = new OnPresenceSelected() {
1320					@Override
1321					public void onPresenceSelected() {
1322						mPendingFileUris.clear();
1323						mPendingFileUris.addAll(uris);
1324						if (xmppConnectionServiceBound) {
1325							for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1326								attachFileToConversation(c, i.next());
1327							}
1328						}
1329					}
1330				};
1331				if (c == null || c.getMode() == Conversation.MODE_MULTI
1332						|| FileBackend.allFilesUnderSize(this, uris, getMaxHttpUploadSize(c))
1333						|| c.getNextEncryption() == Message.ENCRYPTION_OTR) {
1334					callback.onPresenceSelected();
1335				} else {
1336					selectPresence(c, callback);
1337				}
1338			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1339				if (mPendingImageUris.size() == 1) {
1340					Uri uri = mPendingImageUris.get(0);
1341					if (xmppConnectionServiceBound) {
1342						attachImageToConversation(getSelectedConversation(), uri);
1343						mPendingImageUris.clear();
1344					}
1345					Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1346					intent.setData(uri);
1347					sendBroadcast(intent);
1348				} else {
1349					mPendingImageUris.clear();
1350				}
1351			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1352				double latitude = data.getDoubleExtra("latitude", 0);
1353				double longitude = data.getDoubleExtra("longitude", 0);
1354				this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1355				if (xmppConnectionServiceBound) {
1356					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1357					this.mPendingGeoUri = null;
1358				}
1359			} else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1360				this.forbidProcessingPendings = !xmppConnectionServiceBound;
1361				if (xmppConnectionServiceBound) {
1362					mConversationFragment.onActivityResult(requestCode, resultCode, data);
1363					this.mPostponedActivityResult = null;
1364				} else {
1365					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1366				}
1367
1368			}
1369		} else {
1370			mPendingImageUris.clear();
1371			mPendingFileUris.clear();
1372			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1373				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1374			}
1375			if (requestCode == REQUEST_BATTERY_OP) {
1376				setNeverAskForBatteryOptimizationsAgain();
1377			}
1378		}
1379	}
1380
1381	private long getMaxHttpUploadSize(Conversation conversation) {
1382		return conversation.getAccount().getXmppConnection().getFeatures().getMaxHttpUploadSize();
1383	}
1384
1385	private void setNeverAskForBatteryOptimizationsAgain() {
1386		getPreferences().edit().putBoolean("show_battery_optimization", false).commit();
1387	}
1388
1389	private void openBatteryOptimizationDialogIfNeeded() {
1390		if (hasAccountWithoutPush()
1391				&& isOptimizingBattery()
1392				&& getPreferences().getBoolean("show_battery_optimization", true)) {
1393			AlertDialog.Builder builder = new AlertDialog.Builder(this);
1394			builder.setTitle(R.string.battery_optimizations_enabled);
1395			builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1396			builder.setPositiveButton(R.string.next, new OnClickListener() {
1397				@Override
1398				public void onClick(DialogInterface dialog, int which) {
1399					Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1400					Uri uri = Uri.parse("package:" + getPackageName());
1401					intent.setData(uri);
1402					try {
1403						startActivityForResult(intent, REQUEST_BATTERY_OP);
1404					} catch (ActivityNotFoundException e) {
1405						Toast.makeText(ConversationActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1406					}
1407				}
1408			});
1409			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1410				builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1411					@Override
1412					public void onDismiss(DialogInterface dialog) {
1413						setNeverAskForBatteryOptimizationsAgain();
1414					}
1415				});
1416			}
1417			builder.create().show();
1418		}
1419	}
1420
1421	private boolean hasAccountWithoutPush() {
1422		for(Account account : xmppConnectionService.getAccounts()) {
1423			if (account.getStatus() != Account.State.DISABLED
1424					&& !xmppConnectionService.getPushManagementService().available(account)) {
1425				return true;
1426			}
1427		}
1428		return false;
1429	}
1430
1431	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1432		if (conversation == null) {
1433			return;
1434		}
1435		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1436
1437			@Override
1438			public void success(Message message) {
1439				xmppConnectionService.sendMessage(message);
1440			}
1441
1442			@Override
1443			public void error(int errorCode, Message object) {
1444
1445			}
1446
1447			@Override
1448			public void userInputRequried(PendingIntent pi, Message object) {
1449
1450			}
1451		});
1452	}
1453
1454	private void attachFileToConversation(Conversation conversation, Uri uri) {
1455		if (conversation == null) {
1456			return;
1457		}
1458		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1459		prepareFileToast.show();
1460		xmppConnectionService.attachFileToConversation(conversation, uri, new UiCallback<Message>() {
1461			@Override
1462			public void success(Message message) {
1463				hidePrepareFileToast(prepareFileToast);
1464				xmppConnectionService.sendMessage(message);
1465			}
1466
1467			@Override
1468			public void error(final int errorCode, Message message) {
1469				hidePrepareFileToast(prepareFileToast);
1470				runOnUiThread(new Runnable() {
1471					@Override
1472					public void run() {
1473						replaceToast(getString(errorCode));
1474					}
1475				});
1476
1477			}
1478
1479			@Override
1480			public void userInputRequried(PendingIntent pi, Message message) {
1481				hidePrepareFileToast(prepareFileToast);
1482			}
1483		});
1484	}
1485
1486	private void attachImageToConversation(Conversation conversation, Uri uri) {
1487		if (conversation == null) {
1488			return;
1489		}
1490		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1491		prepareFileToast.show();
1492		xmppConnectionService.attachImageToConversation(conversation, uri,
1493				new UiCallback<Message>() {
1494
1495					@Override
1496					public void userInputRequried(PendingIntent pi, Message object) {
1497						hidePrepareFileToast(prepareFileToast);
1498					}
1499
1500					@Override
1501					public void success(Message message) {
1502						hidePrepareFileToast(prepareFileToast);
1503						xmppConnectionService.sendMessage(message);
1504					}
1505
1506					@Override
1507					public void error(final int error, Message message) {
1508						hidePrepareFileToast(prepareFileToast);
1509						runOnUiThread(new Runnable() {
1510							@Override
1511							public void run() {
1512								replaceToast(getString(error));
1513							}
1514						});
1515					}
1516				});
1517	}
1518
1519	private void hidePrepareFileToast(final Toast prepareFileToast) {
1520		if (prepareFileToast != null) {
1521			runOnUiThread(new Runnable() {
1522
1523				@Override
1524				public void run() {
1525					prepareFileToast.cancel();
1526				}
1527			});
1528		}
1529	}
1530
1531	public void updateConversationList() {
1532		xmppConnectionService
1533			.populateWithOrderedConversations(conversationList);
1534		if (swipedConversation != null) {
1535			if (swipedConversation.isRead()) {
1536				conversationList.remove(swipedConversation);
1537			} else {
1538				listView.discardUndo();
1539			}
1540		}
1541		listAdapter.notifyDataSetChanged();
1542	}
1543
1544	public void runIntent(PendingIntent pi, int requestCode) {
1545		try {
1546			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1547					null, 0, 0, 0);
1548		} catch (final SendIntentException ignored) {
1549		}
1550	}
1551
1552	public void encryptTextMessage(Message message) {
1553		xmppConnectionService.getPgpEngine().encrypt(message,
1554				new UiCallback<Message>() {
1555
1556					@Override
1557					public void userInputRequried(PendingIntent pi,Message message) {
1558						ConversationActivity.this.runIntent(pi,ConversationActivity.REQUEST_SEND_MESSAGE);
1559					}
1560
1561					@Override
1562					public void success(Message message) {
1563						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1564						xmppConnectionService.sendMessage(message);
1565						if (mConversationFragment != null) {
1566							mConversationFragment.messageSent();
1567						}
1568					}
1569
1570					@Override
1571					public void error(final int error, Message message) {
1572						runOnUiThread(new Runnable() {
1573							@Override
1574							public void run() {
1575								Toast.makeText(ConversationActivity.this,
1576										R.string.unable_to_connect_to_keychain,
1577										Toast.LENGTH_SHORT
1578								).show();
1579							}
1580						});
1581					}
1582				});
1583	}
1584
1585	public boolean useSendButtonToIndicateStatus() {
1586		return getPreferences().getBoolean("send_button_status", false);
1587	}
1588
1589	public boolean indicateReceived() {
1590		return getPreferences().getBoolean("indicate_received", false);
1591	}
1592
1593	public boolean useGreenBackground() {
1594		return getPreferences().getBoolean("use_green_background",true);
1595	}
1596
1597	protected boolean trustKeysIfNeeded(int requestCode) {
1598		return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1599	}
1600
1601	protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1602		AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1603		final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1604		boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1605		boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED).isEmpty();
1606		boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED, targets).isEmpty();
1607		boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1608		boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1609		if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1610			axolotlService.createSessionsIfNeeded(mSelectedConversation);
1611			Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1612			String[] contacts = new String[targets.size()];
1613			for(int i = 0; i < contacts.length; ++i) {
1614				contacts[i] = targets.get(i).toString();
1615			}
1616			intent.putExtra("contacts", contacts);
1617			intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1618			intent.putExtra("choice", attachmentChoice);
1619			intent.putExtra("conversation",mSelectedConversation.getUuid());
1620			startActivityForResult(intent, requestCode);
1621			return true;
1622		} else {
1623			return false;
1624		}
1625	}
1626
1627	@Override
1628	protected void refreshUiReal() {
1629		updateConversationList();
1630		if (conversationList.size() > 0) {
1631			if (!this.mConversationFragment.isAdded()) {
1632				Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1633			}
1634			ConversationActivity.this.mConversationFragment.updateMessages();
1635			updateActionBarTitle();
1636			invalidateOptionsMenu();
1637		} else {
1638			Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1639		}
1640	}
1641
1642	@Override
1643	public void onAccountUpdate() {
1644		this.refreshUi();
1645	}
1646
1647	@Override
1648	public void onConversationUpdate() {
1649		this.refreshUi();
1650	}
1651
1652	@Override
1653	public void onRosterUpdate() {
1654		this.refreshUi();
1655	}
1656
1657	@Override
1658	public void OnUpdateBlocklist(Status status) {
1659		this.refreshUi();
1660	}
1661
1662	public void unblockConversation(final Blockable conversation) {
1663		xmppConnectionService.sendUnblockRequest(conversation);
1664	}
1665
1666	public boolean enterIsSend() {
1667		return getPreferences().getBoolean("enter_is_send",false);
1668	}
1669
1670	@Override
1671	public void onShowErrorToast(final int resId) {
1672		runOnUiThread(new Runnable() {
1673			@Override
1674			public void run() {
1675				Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1676			}
1677		});
1678	}
1679
1680	public boolean highlightSelectedConversations() {
1681		return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1682	}
1683
1684	public void setMessagesLoaded() {
1685		if (mConversationFragment != null) {
1686			mConversationFragment.setMessagesLoaded();
1687			mConversationFragment.updateMessages();
1688		}
1689	}
1690}