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