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, onOpenPGPKeyPublished);
 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 == KeyEvent.KEYCODE_SPACE) {
 957			startActivity(new Intent(this, StartConversationActivity.class));
 958			return true;
 959		} else if (modifier && key == downKey) {
 960			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
 961				showConversationsOverview();
 962				;
 963			}
 964			return selectDownConversation();
 965		} else if (modifier && key == upKey) {
 966			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
 967				showConversationsOverview();
 968			}
 969			return selectUpConversation();
 970		} else if (modifier && key == KeyEvent.KEYCODE_1) {
 971			return openConversationByIndex(0);
 972		} else if (modifier && key == KeyEvent.KEYCODE_2) {
 973			return openConversationByIndex(1);
 974		} else if (modifier && key == KeyEvent.KEYCODE_3) {
 975			return openConversationByIndex(2);
 976		} else if (modifier && key == KeyEvent.KEYCODE_4) {
 977			return openConversationByIndex(3);
 978		} else if (modifier && key == KeyEvent.KEYCODE_5) {
 979			return openConversationByIndex(4);
 980		} else if (modifier && key == KeyEvent.KEYCODE_6) {
 981			return openConversationByIndex(5);
 982		} else if (modifier && key == KeyEvent.KEYCODE_7) {
 983			return openConversationByIndex(6);
 984		} else if (modifier && key == KeyEvent.KEYCODE_8) {
 985			return openConversationByIndex(7);
 986		} else if (modifier && key == KeyEvent.KEYCODE_9) {
 987			return openConversationByIndex(8);
 988		} else if (modifier && key == KeyEvent.KEYCODE_0) {
 989			return openConversationByIndex(9);
 990		} else {
 991			return super.onKeyUp(key, event);
 992		}
 993	}
 994
 995	private void toggleConversationsOverview() {
 996		if (isConversationsOverviewVisable()) {
 997			hideConversationsOverview();
 998			if (mConversationFragment != null) {
 999				mConversationFragment.setFocusOnInputField();
1000			}
1001		} else {
1002			showConversationsOverview();
1003		}
1004	}
1005
1006	private boolean selectUpConversation() {
1007		if (this.mSelectedConversation != null) {
1008			int index = this.conversationList.indexOf(this.mSelectedConversation);
1009			if (index > 0) {
1010				return openConversationByIndex(index - 1);
1011			}
1012		}
1013		return false;
1014	}
1015
1016	private boolean selectDownConversation() {
1017		if (this.mSelectedConversation != null) {
1018			int index = this.conversationList.indexOf(this.mSelectedConversation);
1019			if (index != -1 && index < this.conversationList.size() - 1) {
1020				return openConversationByIndex(index + 1);
1021			}
1022		}
1023		return false;
1024	}
1025
1026	private boolean openConversationByIndex(int index) {
1027		try {
1028			this.conversationWasSelectedByKeyboard = true;
1029			setSelectedConversation(this.conversationList.get(index));
1030			this.mConversationFragment.reInit(getSelectedConversation());
1031			if (index > listView.getLastVisiblePosition() - 1 || index < listView.getFirstVisiblePosition() + 1) {
1032				this.listView.setSelection(index);
1033			}
1034			openConversation();
1035			return true;
1036		} catch (IndexOutOfBoundsException e) {
1037			return false;
1038		}
1039	}
1040
1041	@Override
1042	protected void onNewIntent(final Intent intent) {
1043		if (xmppConnectionServiceBound) {
1044			if (intent != null && VIEW_CONVERSATION.equals(intent.getType())) {
1045				handleViewConversationIntent(intent);
1046				setIntent(new Intent());
1047			}
1048		} else {
1049			setIntent(intent);
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		if (this.xmppConnectionServiceBound) {
1071			this.xmppConnectionService.getNotificationService().setIsInForeground(false);
1072		}
1073	}
1074
1075	@Override
1076	public void onResume() {
1077		super.onResume();
1078		final int theme = findTheme();
1079		final boolean usingEnterKey = usingEnterKey();
1080		if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
1081			recreate();
1082		}
1083		this.mActivityPaused = false;
1084		if (this.xmppConnectionServiceBound) {
1085			this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1086		}
1087
1088		if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
1089			sendReadMarkerIfNecessary(getSelectedConversation());
1090		}
1091
1092	}
1093
1094	@Override
1095	public void onSaveInstanceState(final Bundle savedInstanceState) {
1096		Conversation conversation = getSelectedConversation();
1097		if (conversation != null) {
1098			savedInstanceState.putString(STATE_OPEN_CONVERSATION, conversation.getUuid());
1099		} else {
1100			savedInstanceState.remove(STATE_OPEN_CONVERSATION);
1101		}
1102		savedInstanceState.putBoolean(STATE_PANEL_OPEN, isConversationsOverviewVisable());
1103		if (this.mPendingImageUris.size() >= 1) {
1104			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1105		} else {
1106			savedInstanceState.remove(STATE_PENDING_URI);
1107		}
1108		super.onSaveInstanceState(savedInstanceState);
1109	}
1110
1111	private void clearPending() {
1112		mPendingImageUris.clear();
1113		mPendingFileUris.clear();
1114		mPendingGeoUri = null;
1115		mPostponedActivityResult = null;
1116	}
1117
1118	@Override
1119	void onBackendConnected() {
1120		this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1121		updateConversationList();
1122
1123		if (mPendingConferenceInvite != null) {
1124			mPendingConferenceInvite.execute(this);
1125			mPendingConferenceInvite = null;
1126		}
1127
1128		if (xmppConnectionService.getAccounts().size() == 0) {
1129			if (mRedirected.compareAndSet(false, true)) {
1130				if (Config.X509_VERIFICATION) {
1131					startActivity(new Intent(this, ManageAccountActivity.class));
1132				} else if (Config.MAGIC_CREATE_DOMAIN != null) {
1133					startActivity(new Intent(this, WelcomeActivity.class));
1134				} else {
1135					startActivity(new Intent(this, EditAccountActivity.class));
1136				}
1137				finish();
1138			}
1139		} else if (conversationList.size() <= 0) {
1140			if (mRedirected.compareAndSet(false, true)) {
1141				Account pendingAccount = xmppConnectionService.getPendingAccount();
1142				if (pendingAccount == null) {
1143					Intent intent = new Intent(this, StartConversationActivity.class);
1144					intent.putExtra("init", true);
1145					startActivity(intent);
1146				} else {
1147					switchToAccount(pendingAccount, true);
1148				}
1149				finish();
1150			}
1151		} else if (getIntent() != null && VIEW_CONVERSATION.equals(getIntent().getType())) {
1152			clearPending();
1153			handleViewConversationIntent(getIntent());
1154		} else if (selectConversationByUuid(mOpenConverstaion)) {
1155			if (mPanelOpen) {
1156				showConversationsOverview();
1157			} else {
1158				if (isConversationsOverviewHideable()) {
1159					openConversation();
1160					updateActionBarTitle(true);
1161				}
1162			}
1163			this.mConversationFragment.reInit(getSelectedConversation());
1164			mOpenConverstaion = null;
1165		} else if (getSelectedConversation() == null) {
1166			showConversationsOverview();
1167			clearPending();
1168			setSelectedConversation(conversationList.get(0));
1169			this.mConversationFragment.reInit(getSelectedConversation());
1170		} else {
1171			this.mConversationFragment.messageListAdapter.updatePreferences();
1172			this.mConversationFragment.messagesView.invalidateViews();
1173			this.mConversationFragment.setupIme();
1174		}
1175
1176		if (this.mPostponedActivityResult != null) {
1177			this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1178		}
1179
1180		if (!forbidProcessingPendings) {
1181			for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1182				Uri foo = i.next();
1183				attachImageToConversation(getSelectedConversation(), foo);
1184			}
1185
1186			for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1187				attachFileToConversation(getSelectedConversation(), i.next());
1188			}
1189
1190			if (mPendingGeoUri != null) {
1191				attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1192				mPendingGeoUri = null;
1193			}
1194		}
1195		forbidProcessingPendings = false;
1196
1197		if (!ExceptionHelper.checkForCrash(this, this.xmppConnectionService)) {
1198			openBatteryOptimizationDialogIfNeeded();
1199		}
1200		setIntent(new Intent());
1201	}
1202
1203	private void handleViewConversationIntent(final Intent intent) {
1204		final String uuid = intent.getStringExtra(CONVERSATION);
1205		final String downloadUuid = intent.getStringExtra(MESSAGE);
1206		final String text = intent.getStringExtra(TEXT);
1207		final String nick = intent.getStringExtra(NICK);
1208		final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1209		if (selectConversationByUuid(uuid)) {
1210			this.mConversationFragment.reInit(getSelectedConversation());
1211			if (nick != null) {
1212				if (pm) {
1213					Jid jid = getSelectedConversation().getJid();
1214					try {
1215						Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1216						this.mConversationFragment.privateMessageWith(next);
1217					} catch (final InvalidJidException ignored) {
1218						//do nothing
1219					}
1220				} else {
1221					this.mConversationFragment.highlightInConference(nick);
1222				}
1223			} else {
1224				this.mConversationFragment.appendText(text);
1225			}
1226			hideConversationsOverview();
1227			openConversation();
1228			if (mContentView instanceof SlidingPaneLayout) {
1229				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1230			}
1231			if (downloadUuid != null) {
1232				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1233				if (message != null) {
1234					startDownloadable(message);
1235				}
1236			}
1237		}
1238	}
1239
1240	private boolean selectConversationByUuid(String uuid) {
1241		if (uuid == null) {
1242			return false;
1243		}
1244		for (Conversation aConversationList : conversationList) {
1245			if (aConversationList.getUuid().equals(uuid)) {
1246				setSelectedConversation(aConversationList);
1247				return true;
1248			}
1249		}
1250		return false;
1251	}
1252
1253	@Override
1254	protected void unregisterListeners() {
1255		super.unregisterListeners();
1256		xmppConnectionService.getNotificationService().setOpenConversation(null);
1257	}
1258
1259	@SuppressLint("NewApi")
1260	private static List<Uri> extractUriFromIntent(final Intent intent) {
1261		List<Uri> uris = new ArrayList<>();
1262		if (intent == null) {
1263			return uris;
1264		}
1265		Uri uri = intent.getData();
1266		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1267			ClipData clipData = intent.getClipData();
1268			for (int i = 0; i < clipData.getItemCount(); ++i) {
1269				uris.add(clipData.getItemAt(i).getUri());
1270			}
1271		} else {
1272			uris.add(uri);
1273		}
1274		return uris;
1275	}
1276
1277	@Override
1278	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1279		super.onActivityResult(requestCode, resultCode, data);
1280		if (resultCode == RESULT_OK) {
1281			if (requestCode == REQUEST_DECRYPT_PGP) {
1282				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1283			} else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1284				// the user chose OpenPGP for encryption and selected his key in the PGP provider
1285				if (xmppConnectionServiceBound) {
1286					if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1287						// associate selected PGP keyId with the account
1288						mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1289						// we need to announce the key as described in XEP-027
1290						announcePgp(mSelectedConversation.getAccount(), null, onOpenPGPKeyPublished);
1291					} else {
1292						choosePgpSignId(mSelectedConversation.getAccount());
1293					}
1294					this.mPostponedActivityResult = null;
1295				} else {
1296					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1297				}
1298			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1299				if (xmppConnectionServiceBound) {
1300					announcePgp(mSelectedConversation.getAccount(), mSelectedConversation, onOpenPGPKeyPublished);
1301					this.mPostponedActivityResult = null;
1302				} else {
1303					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1304				}
1305			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1306				mPendingImageUris.clear();
1307				mPendingImageUris.addAll(extractUriFromIntent(data));
1308				if (xmppConnectionServiceBound) {
1309					for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1310						attachImageToConversation(getSelectedConversation(), i.next());
1311					}
1312				}
1313			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1314				final List<Uri> uris = extractUriFromIntent(data);
1315				final Conversation c = getSelectedConversation();
1316				final OnPresenceSelected callback = new OnPresenceSelected() {
1317					@Override
1318					public void onPresenceSelected() {
1319						mPendingFileUris.clear();
1320						mPendingFileUris.addAll(uris);
1321						if (xmppConnectionServiceBound) {
1322							for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1323								attachFileToConversation(c, i.next());
1324							}
1325						}
1326					}
1327				};
1328				if (c == null || c.getMode() == Conversation.MODE_MULTI
1329						|| FileBackend.allFilesUnderSize(this, uris, getMaxHttpUploadSize(c))
1330						|| c.getNextEncryption() == Message.ENCRYPTION_OTR) {
1331					callback.onPresenceSelected();
1332				} else {
1333					selectPresence(c, callback);
1334				}
1335			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1336				if (mPendingImageUris.size() == 1) {
1337					Uri uri = mPendingImageUris.get(0);
1338					if (xmppConnectionServiceBound) {
1339						attachImageToConversation(getSelectedConversation(), uri);
1340						mPendingImageUris.clear();
1341					}
1342					Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1343					intent.setData(uri);
1344					sendBroadcast(intent);
1345				} else {
1346					mPendingImageUris.clear();
1347				}
1348			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1349				double latitude = data.getDoubleExtra("latitude", 0);
1350				double longitude = data.getDoubleExtra("longitude", 0);
1351				this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1352				if (xmppConnectionServiceBound) {
1353					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1354					this.mPendingGeoUri = null;
1355				}
1356			} else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1357				this.forbidProcessingPendings = !xmppConnectionServiceBound;
1358				if (xmppConnectionServiceBound) {
1359					mConversationFragment.onActivityResult(requestCode, resultCode, data);
1360					this.mPostponedActivityResult = null;
1361				} else {
1362					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1363				}
1364
1365			}
1366		} else {
1367			mPendingImageUris.clear();
1368			mPendingFileUris.clear();
1369			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1370				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1371			}
1372			if (requestCode == REQUEST_BATTERY_OP) {
1373				setNeverAskForBatteryOptimizationsAgain();
1374			}
1375		}
1376	}
1377
1378	private long getMaxHttpUploadSize(Conversation conversation) {
1379		return conversation.getAccount().getXmppConnection().getFeatures().getMaxHttpUploadSize();
1380	}
1381
1382	private void setNeverAskForBatteryOptimizationsAgain() {
1383		getPreferences().edit().putBoolean("show_battery_optimization", false).commit();
1384	}
1385
1386	private void openBatteryOptimizationDialogIfNeeded() {
1387		if (hasAccountWithoutPush()
1388				&& isOptimizingBattery()
1389				&& getPreferences().getBoolean("show_battery_optimization", true)) {
1390			AlertDialog.Builder builder = new AlertDialog.Builder(this);
1391			builder.setTitle(R.string.battery_optimizations_enabled);
1392			builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1393			builder.setPositiveButton(R.string.next, new OnClickListener() {
1394				@Override
1395				public void onClick(DialogInterface dialog, int which) {
1396					Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1397					Uri uri = Uri.parse("package:" + getPackageName());
1398					intent.setData(uri);
1399					try {
1400						startActivityForResult(intent, REQUEST_BATTERY_OP);
1401					} catch (ActivityNotFoundException e) {
1402						Toast.makeText(ConversationActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1403					}
1404				}
1405			});
1406			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1407				builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1408					@Override
1409					public void onDismiss(DialogInterface dialog) {
1410						setNeverAskForBatteryOptimizationsAgain();
1411					}
1412				});
1413			}
1414			builder.create().show();
1415		}
1416	}
1417
1418	private boolean hasAccountWithoutPush() {
1419		for(Account account : xmppConnectionService.getAccounts()) {
1420			if (account.getStatus() != Account.State.DISABLED
1421					&& !xmppConnectionService.getPushManagementService().available(account)) {
1422				return true;
1423			}
1424		}
1425		return false;
1426	}
1427
1428	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1429		if (conversation == null) {
1430			return;
1431		}
1432		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1433
1434			@Override
1435			public void success(Message message) {
1436				xmppConnectionService.sendMessage(message);
1437			}
1438
1439			@Override
1440			public void error(int errorCode, Message object) {
1441
1442			}
1443
1444			@Override
1445			public void userInputRequried(PendingIntent pi, Message object) {
1446
1447			}
1448		});
1449	}
1450
1451	private void attachFileToConversation(Conversation conversation, Uri uri) {
1452		if (conversation == null) {
1453			return;
1454		}
1455		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1456		prepareFileToast.show();
1457		xmppConnectionService.attachFileToConversation(conversation, uri, new UiCallback<Message>() {
1458			@Override
1459			public void success(Message message) {
1460				hidePrepareFileToast(prepareFileToast);
1461				xmppConnectionService.sendMessage(message);
1462			}
1463
1464			@Override
1465			public void error(int errorCode, Message message) {
1466				hidePrepareFileToast(prepareFileToast);
1467				displayErrorDialog(errorCode);
1468			}
1469
1470			@Override
1471			public void userInputRequried(PendingIntent pi, Message message) {
1472
1473			}
1474		});
1475	}
1476
1477	private void attachImageToConversation(Conversation conversation, Uri uri) {
1478		if (conversation == null) {
1479			return;
1480		}
1481		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1482		prepareFileToast.show();
1483		xmppConnectionService.attachImageToConversation(conversation, uri,
1484				new UiCallback<Message>() {
1485
1486					@Override
1487					public void userInputRequried(PendingIntent pi, Message object) {
1488						hidePrepareFileToast(prepareFileToast);
1489					}
1490
1491					@Override
1492					public void success(Message message) {
1493						hidePrepareFileToast(prepareFileToast);
1494						xmppConnectionService.sendMessage(message);
1495					}
1496
1497					@Override
1498					public void error(int error, Message message) {
1499						hidePrepareFileToast(prepareFileToast);
1500						displayErrorDialog(error);
1501					}
1502				});
1503	}
1504
1505	private void hidePrepareFileToast(final Toast prepareFileToast) {
1506		if (prepareFileToast != null) {
1507			runOnUiThread(new Runnable() {
1508
1509				@Override
1510				public void run() {
1511					prepareFileToast.cancel();
1512				}
1513			});
1514		}
1515	}
1516
1517	public void updateConversationList() {
1518		xmppConnectionService
1519			.populateWithOrderedConversations(conversationList);
1520		if (swipedConversation != null) {
1521			if (swipedConversation.isRead()) {
1522				conversationList.remove(swipedConversation);
1523			} else {
1524				listView.discardUndo();
1525			}
1526		}
1527		listAdapter.notifyDataSetChanged();
1528	}
1529
1530	public void runIntent(PendingIntent pi, int requestCode) {
1531		try {
1532			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1533					null, 0, 0, 0);
1534		} catch (final SendIntentException ignored) {
1535		}
1536	}
1537
1538	public void encryptTextMessage(Message message) {
1539		xmppConnectionService.getPgpEngine().encrypt(message,
1540				new UiCallback<Message>() {
1541
1542					@Override
1543					public void userInputRequried(PendingIntent pi,
1544												  Message message) {
1545						ConversationActivity.this.runIntent(pi,
1546								ConversationActivity.REQUEST_SEND_MESSAGE);
1547					}
1548
1549					@Override
1550					public void success(Message message) {
1551						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1552						xmppConnectionService.sendMessage(message);
1553					}
1554
1555					@Override
1556					public void error(int error, Message message) {
1557
1558					}
1559				});
1560	}
1561
1562	public boolean useSendButtonToIndicateStatus() {
1563		return getPreferences().getBoolean("send_button_status", false);
1564	}
1565
1566	public boolean indicateReceived() {
1567		return getPreferences().getBoolean("indicate_received", false);
1568	}
1569
1570	public boolean useWhiteBackground() {
1571		return getPreferences().getBoolean("use_white_background",false);
1572	}
1573
1574	protected boolean trustKeysIfNeeded(int requestCode) {
1575		return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1576	}
1577
1578	protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1579		AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1580		final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1581		boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1582		boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED).isEmpty();
1583		boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED, targets).isEmpty();
1584		boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1585		boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1586		if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1587			axolotlService.createSessionsIfNeeded(mSelectedConversation);
1588			Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1589			String[] contacts = new String[targets.size()];
1590			for(int i = 0; i < contacts.length; ++i) {
1591				contacts[i] = targets.get(i).toString();
1592			}
1593			intent.putExtra("contacts", contacts);
1594			intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1595			intent.putExtra("choice", attachmentChoice);
1596			intent.putExtra("conversation",mSelectedConversation.getUuid());
1597			startActivityForResult(intent, requestCode);
1598			return true;
1599		} else {
1600			return false;
1601		}
1602	}
1603
1604	@Override
1605	protected void refreshUiReal() {
1606		updateConversationList();
1607		if (conversationList.size() > 0) {
1608			if (!this.mConversationFragment.isAdded()) {
1609				Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1610			}
1611			ConversationActivity.this.mConversationFragment.updateMessages();
1612			updateActionBarTitle();
1613			invalidateOptionsMenu();
1614		} else {
1615			Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1616		}
1617	}
1618
1619	@Override
1620	public void onAccountUpdate() {
1621		this.refreshUi();
1622	}
1623
1624	@Override
1625	public void onConversationUpdate() {
1626		this.refreshUi();
1627	}
1628
1629	@Override
1630	public void onRosterUpdate() {
1631		this.refreshUi();
1632	}
1633
1634	@Override
1635	public void OnUpdateBlocklist(Status status) {
1636		this.refreshUi();
1637	}
1638
1639	public void unblockConversation(final Blockable conversation) {
1640		xmppConnectionService.sendUnblockRequest(conversation);
1641	}
1642
1643	public boolean enterIsSend() {
1644		return getPreferences().getBoolean("enter_is_send",false);
1645	}
1646
1647	@Override
1648	public void onShowErrorToast(final int resId) {
1649		runOnUiThread(new Runnable() {
1650			@Override
1651			public void run() {
1652				Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1653			}
1654		});
1655	}
1656
1657	public boolean highlightSelectedConversations() {
1658		return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1659	}
1660
1661	public void setMessagesLoaded() {
1662		if (mConversationFragment != null) {
1663			mConversationFragment.setMessagesLoaded();
1664			mConversationFragment.updateMessages();
1665		}
1666	}
1667}