ConversationActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.annotation.SuppressLint;
   4import android.app.ActionBar;
   5import android.app.AlertDialog;
   6import android.app.FragmentTransaction;
   7import android.app.PendingIntent;
   8import android.content.ClipData;
   9import android.content.DialogInterface;
  10import android.content.DialogInterface.OnClickListener;
  11import android.content.Intent;
  12import android.content.IntentSender.SendIntentException;
  13import android.net.Uri;
  14import android.os.Build;
  15import android.os.Bundle;
  16import android.provider.MediaStore;
  17import android.support.v4.widget.SlidingPaneLayout;
  18import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
  19import android.view.Menu;
  20import android.view.MenuItem;
  21import android.view.View;
  22import android.widget.AdapterView;
  23import android.widget.AdapterView.OnItemClickListener;
  24import android.widget.ArrayAdapter;
  25import android.widget.CheckBox;
  26import android.widget.PopupMenu;
  27import android.widget.PopupMenu.OnMenuItemClickListener;
  28import android.widget.Toast;
  29
  30import net.java.otr4j.session.SessionStatus;
  31import de.timroes.android.listview.EnhancedListView;
  32
  33import java.util.ArrayList;
  34import java.util.Iterator;
  35import java.util.List;
  36
  37import eu.siacs.conversations.R;
  38import eu.siacs.conversations.entities.Blockable;
  39import eu.siacs.conversations.entities.Contact;
  40import eu.siacs.conversations.entities.Conversation;
  41import eu.siacs.conversations.entities.Message;
  42import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
  43import eu.siacs.conversations.services.XmppConnectionService.OnConversationUpdate;
  44import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
  45import eu.siacs.conversations.ui.adapter.ConversationAdapter;
  46import eu.siacs.conversations.utils.ExceptionHelper;
  47import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  48
  49public class ConversationActivity extends XmppActivity
  50	implements OnAccountUpdate, OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist {
  51
  52	public static final String ACTION_DOWNLOAD = "eu.siacs.conversations.action.DOWNLOAD";
  53
  54	public static final String VIEW_CONVERSATION = "viewConversation";
  55	public static final String CONVERSATION = "conversationUuid";
  56	public static final String MESSAGE = "messageUuid";
  57	public static final String TEXT = "text";
  58	public static final String NICK = "nick";
  59
  60	public static final int REQUEST_SEND_MESSAGE = 0x0201;
  61	public static final int REQUEST_DECRYPT_PGP = 0x0202;
  62	public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
  63	private static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
  64	private static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
  65	private static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
  66	private static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
  67	private static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
  68	private static final String STATE_OPEN_CONVERSATION = "state_open_conversation";
  69	private static final String STATE_PANEL_OPEN = "state_panel_open";
  70	private static final String STATE_PENDING_URI = "state_pending_uri";
  71
  72	private String mOpenConverstaion = null;
  73	private boolean mPanelOpen = true;
  74	final private List<Uri> mPendingImageUris = new ArrayList<>();
  75	final private List<Uri> mPendingFileUris = new ArrayList<>();
  76	private Uri mPendingGeoUri = null;
  77
  78	private View mContentView;
  79
  80	private List<Conversation> conversationList = new ArrayList<>();
  81	private Conversation swipedConversation = null;
  82	private Conversation mSelectedConversation = null;
  83	private EnhancedListView listView;
  84	private ConversationFragment mConversationFragment;
  85
  86	private ArrayAdapter<Conversation> listAdapter;
  87
  88	private Toast prepareFileToast;
  89
  90	private boolean mActivityPaused = false;
  91	private boolean mRedirected = true;
  92
  93	public Conversation getSelectedConversation() {
  94		return this.mSelectedConversation;
  95	}
  96
  97	public void setSelectedConversation(Conversation conversation) {
  98		this.mSelectedConversation = conversation;
  99	}
 100
 101	public void showConversationsOverview() {
 102		if (mContentView instanceof SlidingPaneLayout) {
 103			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 104			mSlidingPaneLayout.openPane();
 105		}
 106	}
 107
 108	@Override
 109	protected String getShareableUri() {
 110		Conversation conversation = getSelectedConversation();
 111		if (conversation != null) {
 112			return conversation.getAccount().getShareableUri();
 113		} else {
 114			return "";
 115		}
 116	}
 117
 118	public void hideConversationsOverview() {
 119		if (mContentView instanceof SlidingPaneLayout) {
 120			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 121			mSlidingPaneLayout.closePane();
 122		}
 123	}
 124
 125	public boolean isConversationsOverviewHideable() {
 126		if (mContentView instanceof SlidingPaneLayout) {
 127			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 128			return mSlidingPaneLayout.isSlideable();
 129		} else {
 130			return false;
 131		}
 132	}
 133
 134	public boolean isConversationsOverviewVisable() {
 135		if (mContentView instanceof SlidingPaneLayout) {
 136			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 137			return mSlidingPaneLayout.isOpen();
 138		} else {
 139			return true;
 140		}
 141	}
 142
 143	@Override
 144	protected void onCreate(final Bundle savedInstanceState) {
 145		super.onCreate(savedInstanceState);
 146		if (savedInstanceState != null) {
 147			mOpenConverstaion = savedInstanceState.getString(STATE_OPEN_CONVERSATION, null);
 148			mPanelOpen = savedInstanceState.getBoolean(STATE_PANEL_OPEN, true);
 149			String pending = savedInstanceState.getString(STATE_PENDING_URI, null);
 150			if (pending != null) {
 151				mPendingImageUris.clear();
 152				mPendingImageUris.add(Uri.parse(pending));
 153			}
 154		}
 155
 156		setContentView(R.layout.fragment_conversations_overview);
 157
 158		this.mConversationFragment = new ConversationFragment();
 159		FragmentTransaction transaction = getFragmentManager().beginTransaction();
 160		transaction.replace(R.id.selected_conversation, this.mConversationFragment, "conversation");
 161		transaction.commit();
 162
 163		listView = (EnhancedListView) findViewById(R.id.list);
 164		this.listAdapter = new ConversationAdapter(this, conversationList);
 165		listView.setAdapter(this.listAdapter);
 166
 167		if (getActionBar() != null) {
 168			getActionBar().setDisplayHomeAsUpEnabled(false);
 169			getActionBar().setHomeButtonEnabled(false);
 170		}
 171
 172		listView.setOnItemClickListener(new OnItemClickListener() {
 173
 174			@Override
 175			public void onItemClick(AdapterView<?> arg0, View clickedView,
 176					int position, long arg3) {
 177				if (getSelectedConversation() != conversationList.get(position)) {
 178					setSelectedConversation(conversationList.get(position));
 179					ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 180				}
 181				hideConversationsOverview();
 182				openConversation();
 183			}
 184		});
 185
 186		listView.setDismissCallback(new EnhancedListView.OnDismissCallback() {
 187
 188			@Override
 189			public EnhancedListView.Undoable onDismiss(final EnhancedListView enhancedListView, final int position) {
 190
 191				final int index = listView.getFirstVisiblePosition();
 192				View v = listView.getChildAt(0);
 193				final int top = (v == null) ? 0 : (v.getTop() - listView.getPaddingTop());
 194
 195				swipedConversation = listAdapter.getItem(position);
 196				listAdapter.remove(swipedConversation);
 197				swipedConversation.markRead();
 198				xmppConnectionService.getNotificationService().clear(swipedConversation);
 199
 200				final boolean formerlySelected = (getSelectedConversation() == swipedConversation);
 201				if (position == 0 && listAdapter.getCount() == 0) {
 202					endConversation(swipedConversation, false, true);
 203					return null;
 204				} else if (formerlySelected) {
 205					setSelectedConversation(listAdapter.getItem(0));
 206					ConversationActivity.this.mConversationFragment
 207							.reInit(getSelectedConversation());
 208				}
 209
 210				return new EnhancedListView.Undoable() {
 211
 212					@Override
 213					public void undo() {
 214						listAdapter.insert(swipedConversation, position);
 215						if (formerlySelected) {
 216							setSelectedConversation(swipedConversation);
 217							ConversationActivity.this.mConversationFragment
 218									.reInit(getSelectedConversation());
 219						}
 220						swipedConversation = null;
 221						listView.setSelectionFromTop(index + (listView.getChildCount() < position ? 1 : 0), top);
 222					}
 223
 224					@Override
 225					public void discard() {
 226						if (!swipedConversation.isRead()
 227								&& swipedConversation.getMode() == Conversation.MODE_SINGLE) {
 228							swipedConversation = null;
 229							return;
 230						}
 231						endConversation(swipedConversation, false, false);
 232						swipedConversation = null;
 233					}
 234
 235					@Override
 236					public String getTitle() {
 237						if (swipedConversation.getMode() == Conversation.MODE_MULTI) {
 238							return getResources().getString(R.string.title_undo_swipe_out_muc);
 239						} else {
 240							return getResources().getString(R.string.title_undo_swipe_out_conversation);
 241						}
 242					}
 243				};
 244			}
 245		});
 246		listView.enableSwipeToDismiss();
 247		listView.setSwipingLayout(R.id.swipeable_item);
 248		listView.setUndoStyle(EnhancedListView.UndoStyle.SINGLE_POPUP);
 249		listView.setUndoHideDelay(3000);
 250		listView.setRequireTouchBeforeDismiss(false);
 251
 252		mContentView = findViewById(R.id.content_view_spl);
 253		if (mContentView == null) {
 254			mContentView = findViewById(R.id.content_view_ll);
 255		}
 256		if (mContentView instanceof SlidingPaneLayout) {
 257			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 258			mSlidingPaneLayout.setParallaxDistance(150);
 259			mSlidingPaneLayout
 260				.setShadowResource(R.drawable.es_slidingpane_shadow);
 261			mSlidingPaneLayout.setSliderFadeColor(0);
 262			mSlidingPaneLayout.setPanelSlideListener(new PanelSlideListener() {
 263
 264				@Override
 265				public void onPanelOpened(View arg0) {
 266					updateActionBarTitle();
 267					invalidateOptionsMenu();
 268					hideKeyboard();
 269					if (xmppConnectionServiceBound) {
 270						xmppConnectionService.getNotificationService()
 271							.setOpenConversation(null);
 272					}
 273					closeContextMenu();
 274				}
 275
 276				@Override
 277				public void onPanelClosed(View arg0) {
 278					listView.discardUndo();
 279					openConversation();
 280				}
 281
 282				@Override
 283				public void onPanelSlide(View arg0, float arg1) {
 284					// TODO Auto-generated method stub
 285
 286				}
 287			});
 288		}
 289	}
 290
 291	@Override
 292	public void switchToConversation(Conversation conversation) {
 293		setSelectedConversation(conversation);
 294		runOnUiThread(new Runnable() {
 295			@Override
 296			public void run() {
 297				ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 298				openConversation();
 299			}
 300		});
 301	}
 302
 303	private void updateActionBarTitle() {
 304		updateActionBarTitle(isConversationsOverviewHideable() && !isConversationsOverviewVisable());
 305	}
 306
 307	private void updateActionBarTitle(boolean titleShouldBeName) {
 308		final ActionBar ab = getActionBar();
 309		final Conversation conversation = getSelectedConversation();
 310		if (ab != null) {
 311			if (titleShouldBeName && conversation != null) {
 312				ab.setDisplayHomeAsUpEnabled(true);
 313				ab.setHomeButtonEnabled(true);
 314				if (conversation.getMode() == Conversation.MODE_SINGLE || useSubjectToIdentifyConference()) {
 315					ab.setTitle(conversation.getName());
 316				} else {
 317					ab.setTitle(conversation.getJid().toBareJid().toString());
 318				}
 319			} else {
 320				ab.setDisplayHomeAsUpEnabled(false);
 321				ab.setHomeButtonEnabled(false);
 322				ab.setTitle(R.string.app_name);
 323			}
 324		}
 325	}
 326
 327	private void openConversation() {
 328		this.updateActionBarTitle();
 329		this.invalidateOptionsMenu();
 330		if (xmppConnectionServiceBound) {
 331			final Conversation conversation = getSelectedConversation();
 332			xmppConnectionService.getNotificationService().setOpenConversation(conversation);
 333			sendReadMarkerIfNecessary(conversation);
 334		}
 335		listAdapter.notifyDataSetChanged();
 336	}
 337
 338	public void sendReadMarkerIfNecessary(final Conversation conversation) {
 339		if (!mActivityPaused && conversation != null) {
 340			if (!conversation.isRead()) {
 341				xmppConnectionService.sendReadMarker(conversation);
 342			} else {
 343				xmppConnectionService.markRead(conversation);
 344			}
 345		}
 346	}
 347
 348	@Override
 349	public boolean onCreateOptionsMenu(Menu menu) {
 350		getMenuInflater().inflate(R.menu.conversations, menu);
 351		final MenuItem menuSecure = menu.findItem(R.id.action_security);
 352		final MenuItem menuArchive = menu.findItem(R.id.action_archive);
 353		final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
 354		final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
 355		final MenuItem menuAttach = menu.findItem(R.id.action_attach_file);
 356		final MenuItem menuClearHistory = menu.findItem(R.id.action_clear_history);
 357		final MenuItem menuAdd = menu.findItem(R.id.action_add);
 358		final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
 359		final MenuItem menuMute = menu.findItem(R.id.action_mute);
 360		final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
 361
 362		if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
 363			menuArchive.setVisible(false);
 364			menuMucDetails.setVisible(false);
 365			menuContactDetails.setVisible(false);
 366			menuSecure.setVisible(false);
 367			menuInviteContact.setVisible(false);
 368			menuAttach.setVisible(false);
 369			menuClearHistory.setVisible(false);
 370			menuMute.setVisible(false);
 371			menuUnmute.setVisible(false);
 372		} else {
 373			menuAdd.setVisible(!isConversationsOverviewHideable());
 374			if (this.getSelectedConversation() != null) {
 375				if (this.getSelectedConversation().getLatestMessage()
 376						.getEncryption() != Message.ENCRYPTION_NONE) {
 377					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 378						menuSecure.setIcon(R.drawable.ic_lock_outline_white_48dp);
 379					} else {
 380						menuSecure.setIcon(R.drawable.ic_action_secure);
 381					}
 382				}
 383				if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
 384					menuContactDetails.setVisible(false);
 385					menuAttach.setVisible(false);
 386					menuInviteContact.setVisible(getSelectedConversation().getMucOptions().canInvite());
 387				} else {
 388					menuMucDetails.setVisible(false);
 389				}
 390				if (this.getSelectedConversation().isMuted()) {
 391					menuMute.setVisible(false);
 392				} else {
 393					menuUnmute.setVisible(false);
 394				}
 395			}
 396		}
 397		return true;
 398	}
 399
 400	private void selectPresenceToAttachFile(final int attachmentChoice, final int encryption) {
 401		if (attachmentChoice == ATTACHMENT_CHOICE_LOCATION && encryption != Message.ENCRYPTION_OTR) {
 402			getSelectedConversation().setNextCounterpart(null);
 403			Intent intent = new Intent("eu.siacs.conversations.location.request");
 404			startActivityForResult(intent,attachmentChoice);
 405		} else {
 406			selectPresence(getSelectedConversation(), new OnPresenceSelected() {
 407
 408				@Override
 409				public void onPresenceSelected() {
 410					Intent intent = new Intent();
 411					boolean chooser = false;
 412					switch (attachmentChoice) {
 413						case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 414							intent.setAction(Intent.ACTION_GET_CONTENT);
 415							if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
 416								intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
 417							}
 418							intent.setType("image/*");
 419							chooser = true;
 420							break;
 421						case ATTACHMENT_CHOICE_TAKE_PHOTO:
 422							Uri uri = xmppConnectionService.getFileBackend().getTakePhotoUri();
 423							intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
 424							intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
 425							mPendingImageUris.clear();
 426							mPendingImageUris.add(uri);
 427							break;
 428						case ATTACHMENT_CHOICE_CHOOSE_FILE:
 429							chooser = true;
 430							intent.setType("*/*");
 431							intent.addCategory(Intent.CATEGORY_OPENABLE);
 432							intent.setAction(Intent.ACTION_GET_CONTENT);
 433							break;
 434						case ATTACHMENT_CHOICE_RECORD_VOICE:
 435							intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
 436							break;
 437						case ATTACHMENT_CHOICE_LOCATION:
 438							intent.setAction("eu.siacs.conversations.location.request");
 439							break;
 440					}
 441					if (intent.resolveActivity(getPackageManager()) != null) {
 442						if (chooser) {
 443							startActivityForResult(
 444									Intent.createChooser(intent, getString(R.string.perform_action_with)),
 445									attachmentChoice);
 446						} else {
 447							startActivityForResult(intent, attachmentChoice);
 448						}
 449					}
 450				}
 451			});
 452		}
 453	}
 454
 455	private void attachFile(final int attachmentChoice) {
 456		final Conversation conversation = getSelectedConversation();
 457		final int encryption = conversation.getNextEncryption(forceEncryption());
 458		if (encryption == Message.ENCRYPTION_PGP) {
 459			if (hasPgp()) {
 460				if (conversation.getContact().getPgpKeyId() != 0) {
 461					xmppConnectionService.getPgpEngine().hasKey(
 462							conversation.getContact(),
 463							new UiCallback<Contact>() {
 464
 465								@Override
 466								public void userInputRequried(PendingIntent pi,
 467										Contact contact) {
 468									ConversationActivity.this.runIntent(pi,attachmentChoice);
 469								}
 470
 471								@Override
 472								public void success(Contact contact) {
 473									selectPresenceToAttachFile(attachmentChoice,encryption);
 474								}
 475
 476								@Override
 477								public void error(int error, Contact contact) {
 478									displayErrorDialog(error);
 479								}
 480							});
 481				} else {
 482					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 483						.findFragmentByTag("conversation");
 484					if (fragment != null) {
 485						fragment.showNoPGPKeyDialog(false,
 486								new OnClickListener() {
 487
 488									@Override
 489									public void onClick(DialogInterface dialog,
 490											int which) {
 491										conversation
 492											.setNextEncryption(Message.ENCRYPTION_NONE);
 493										xmppConnectionService.databaseBackend
 494											.updateConversation(conversation);
 495										selectPresenceToAttachFile(attachmentChoice,Message.ENCRYPTION_NONE);
 496									}
 497								});
 498					}
 499				}
 500			} else {
 501				showInstallPgpDialog();
 502			}
 503		} else {
 504			selectPresenceToAttachFile(attachmentChoice,encryption);
 505		}
 506	}
 507
 508	@Override
 509	public boolean onOptionsItemSelected(final MenuItem item) {
 510		if (item.getItemId() == android.R.id.home) {
 511			showConversationsOverview();
 512			return true;
 513		} else if (item.getItemId() == R.id.action_add) {
 514			startActivity(new Intent(this, StartConversationActivity.class));
 515			return true;
 516		} else if (getSelectedConversation() != null) {
 517			switch (item.getItemId()) {
 518				case R.id.action_attach_file:
 519					attachFileDialog();
 520					break;
 521				case R.id.action_archive:
 522					this.endConversation(getSelectedConversation());
 523					break;
 524				case R.id.action_contact_details:
 525					switchToContactDetails(getSelectedConversation().getContact());
 526					break;
 527				case R.id.action_muc_details:
 528					Intent intent = new Intent(this,
 529							ConferenceDetailsActivity.class);
 530					intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 531					intent.putExtra("uuid", getSelectedConversation().getUuid());
 532					startActivity(intent);
 533					break;
 534				case R.id.action_invite:
 535					inviteToConversation(getSelectedConversation());
 536					break;
 537				case R.id.action_security:
 538					selectEncryptionDialog(getSelectedConversation());
 539					break;
 540				case R.id.action_clear_history:
 541					clearHistoryDialog(getSelectedConversation());
 542					break;
 543				case R.id.action_mute:
 544					muteConversationDialog(getSelectedConversation());
 545					break;
 546				case R.id.action_unmute:
 547					unmuteConversation(getSelectedConversation());
 548					break;
 549				case R.id.action_block:
 550					BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
 551					break;
 552				case R.id.action_unblock:
 553					BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
 554					break;
 555				default:
 556					break;
 557			}
 558			return super.onOptionsItemSelected(item);
 559		} else {
 560			return super.onOptionsItemSelected(item);
 561		}
 562	}
 563
 564	public void endConversation(Conversation conversation) {
 565		endConversation(conversation, true, true);
 566	}
 567
 568	public void endConversation(Conversation conversation, boolean showOverview, boolean reinit) {
 569		if (showOverview) {
 570			showConversationsOverview();
 571		}
 572		xmppConnectionService.archiveConversation(conversation);
 573		if (reinit) {
 574			if (conversationList.size() > 0) {
 575				setSelectedConversation(conversationList.get(0));
 576				this.mConversationFragment.reInit(getSelectedConversation());
 577			} else {
 578				setSelectedConversation(null);
 579			}
 580		}
 581	}
 582
 583	@SuppressLint("InflateParams")
 584	protected void clearHistoryDialog(final Conversation conversation) {
 585		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 586		builder.setTitle(getString(R.string.clear_conversation_history));
 587		View dialogView = getLayoutInflater().inflate(
 588				R.layout.dialog_clear_history, null);
 589		final CheckBox endConversationCheckBox = (CheckBox) dialogView
 590			.findViewById(R.id.end_conversation_checkbox);
 591		builder.setView(dialogView);
 592		builder.setNegativeButton(getString(R.string.cancel), null);
 593		builder.setPositiveButton(getString(R.string.delete_messages),
 594				new OnClickListener() {
 595
 596					@Override
 597					public void onClick(DialogInterface dialog, int which) {
 598						ConversationActivity.this.xmppConnectionService.clearConversationHistory(conversation);
 599						if (endConversationCheckBox.isChecked()) {
 600							endConversation(conversation);
 601						} else {
 602							updateConversationList();
 603							ConversationActivity.this.mConversationFragment.updateMessages();
 604						}
 605					}
 606				});
 607		builder.create().show();
 608	}
 609
 610	protected void attachFileDialog() {
 611		View menuAttachFile = findViewById(R.id.action_attach_file);
 612		if (menuAttachFile == null) {
 613			return;
 614		}
 615		PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
 616		attachFilePopup.inflate(R.menu.attachment_choices);
 617		if (new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION).resolveActivity(getPackageManager()) == null) {
 618			attachFilePopup.getMenu().findItem(R.id.attach_record_voice).setVisible(false);
 619		}
 620		if (new Intent("eu.siacs.conversations.location.request").resolveActivity(getPackageManager()) == null) {
 621			attachFilePopup.getMenu().findItem(R.id.attach_location).setVisible(false);
 622		}
 623		attachFilePopup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 624
 625			@Override
 626			public boolean onMenuItemClick(MenuItem item) {
 627				switch (item.getItemId()) {
 628					case R.id.attach_choose_picture:
 629						attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 630						break;
 631					case R.id.attach_take_picture:
 632						attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
 633						break;
 634					case R.id.attach_choose_file:
 635						attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
 636						break;
 637					case R.id.attach_record_voice:
 638						attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
 639						break;
 640					case R.id.attach_location:
 641						attachFile(ATTACHMENT_CHOICE_LOCATION);
 642						break;
 643				}
 644				return false;
 645			}
 646		});
 647		attachFilePopup.show();
 648	}
 649
 650	public void verifyOtrSessionDialog(final Conversation conversation, View view) {
 651		if (!conversation.hasValidOtrSession() || conversation.getOtrSession().getSessionStatus() != SessionStatus.ENCRYPTED) {
 652			Toast.makeText(this, R.string.otr_session_not_started, Toast.LENGTH_LONG).show();
 653			return;
 654		}
 655		if (view == null) {
 656			return;
 657		}
 658		PopupMenu popup = new PopupMenu(this, view);
 659		popup.inflate(R.menu.verification_choices);
 660		popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 661			@Override
 662			public boolean onMenuItemClick(MenuItem menuItem) {
 663				Intent intent = new Intent(ConversationActivity.this, VerifyOTRActivity.class);
 664				intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
 665				intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
 666				intent.putExtra("account", conversation.getAccount().getJid().toBareJid().toString());
 667				switch (menuItem.getItemId()) {
 668					case R.id.scan_fingerprint:
 669						intent.putExtra("mode",VerifyOTRActivity.MODE_SCAN_FINGERPRINT);
 670						break;
 671					case R.id.ask_question:
 672						intent.putExtra("mode",VerifyOTRActivity.MODE_ASK_QUESTION);
 673						break;
 674					case R.id.manual_verification:
 675						intent.putExtra("mode",VerifyOTRActivity.MODE_MANUAL_VERIFICATION);
 676						break;
 677				}
 678				startActivity(intent);
 679				return true;
 680			}
 681		});
 682		popup.show();
 683	}
 684
 685	protected void selectEncryptionDialog(final Conversation conversation) {
 686		View menuItemView = findViewById(R.id.action_security);
 687		if (menuItemView == null) {
 688			return;
 689		}
 690		PopupMenu popup = new PopupMenu(this, menuItemView);
 691		final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 692			.findFragmentByTag("conversation");
 693		if (fragment != null) {
 694			popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 695
 696				@Override
 697				public boolean onMenuItemClick(MenuItem item) {
 698					switch (item.getItemId()) {
 699						case R.id.encryption_choice_none:
 700							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 701							item.setChecked(true);
 702							break;
 703						case R.id.encryption_choice_otr:
 704							conversation.setNextEncryption(Message.ENCRYPTION_OTR);
 705							item.setChecked(true);
 706							break;
 707						case R.id.encryption_choice_pgp:
 708							if (hasPgp()) {
 709								if (conversation.getAccount().getKeys()
 710										.has("pgp_signature")) {
 711									conversation
 712										.setNextEncryption(Message.ENCRYPTION_PGP);
 713									item.setChecked(true);
 714								} else {
 715									announcePgp(conversation.getAccount(),
 716											conversation);
 717								}
 718							} else {
 719								showInstallPgpDialog();
 720							}
 721							break;
 722						default:
 723							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 724							break;
 725					}
 726					xmppConnectionService.databaseBackend
 727						.updateConversation(conversation);
 728					fragment.updateChatMsgHint();
 729					return true;
 730				}
 731			});
 732			popup.inflate(R.menu.encryption_choices);
 733			MenuItem otr = popup.getMenu().findItem(R.id.encryption_choice_otr);
 734			MenuItem none = popup.getMenu().findItem(
 735					R.id.encryption_choice_none);
 736			if (conversation.getMode() == Conversation.MODE_MULTI) {
 737				otr.setEnabled(false);
 738			} else {
 739				if (forceEncryption()) {
 740					none.setVisible(false);
 741				}
 742			}
 743			switch (conversation.getNextEncryption(forceEncryption())) {
 744				case Message.ENCRYPTION_NONE:
 745					none.setChecked(true);
 746					break;
 747				case Message.ENCRYPTION_OTR:
 748					otr.setChecked(true);
 749					break;
 750				case Message.ENCRYPTION_PGP:
 751					popup.getMenu().findItem(R.id.encryption_choice_pgp)
 752						.setChecked(true);
 753					break;
 754				default:
 755					popup.getMenu().findItem(R.id.encryption_choice_none)
 756						.setChecked(true);
 757					break;
 758			}
 759			popup.show();
 760		}
 761	}
 762
 763	protected void muteConversationDialog(final Conversation conversation) {
 764		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 765		builder.setTitle(R.string.disable_notifications);
 766		final int[] durations = getResources().getIntArray(
 767				R.array.mute_options_durations);
 768		builder.setItems(R.array.mute_options_descriptions,
 769				new OnClickListener() {
 770
 771					@Override
 772					public void onClick(final DialogInterface dialog, final int which) {
 773						final long till;
 774						if (durations[which] == -1) {
 775							till = Long.MAX_VALUE;
 776						} else {
 777							till = System.currentTimeMillis() + (durations[which] * 1000);
 778						}
 779						conversation.setMutedTill(till);
 780						ConversationActivity.this.xmppConnectionService.databaseBackend
 781							.updateConversation(conversation);
 782						updateConversationList();
 783						ConversationActivity.this.mConversationFragment.updateMessages();
 784						invalidateOptionsMenu();
 785					}
 786				});
 787		builder.create().show();
 788	}
 789
 790	public void unmuteConversation(final Conversation conversation) {
 791		conversation.setMutedTill(0);
 792		this.xmppConnectionService.databaseBackend.updateConversation(conversation);
 793		updateConversationList();
 794		ConversationActivity.this.mConversationFragment.updateMessages();
 795		invalidateOptionsMenu();
 796	}
 797
 798	@Override
 799	public void onBackPressed() {
 800		if (!isConversationsOverviewVisable()) {
 801			showConversationsOverview();
 802		} else {
 803			moveTaskToBack(true);
 804		}
 805	}
 806
 807	@Override
 808	protected void onNewIntent(final Intent intent) {
 809		if (xmppConnectionServiceBound) {
 810			if (intent != null && VIEW_CONVERSATION.equals(intent.getType())) {
 811				handleViewConversationIntent(intent);
 812			}
 813		} else {
 814			setIntent(intent);
 815		}
 816	}
 817
 818	@Override
 819	public void onStart() {
 820		super.onStart();
 821		this.mRedirected = false;
 822		if (this.xmppConnectionServiceBound) {
 823			this.onBackendConnected();
 824		}
 825		if (conversationList.size() >= 1) {
 826			this.onConversationUpdate();
 827		}
 828	}
 829
 830	@Override
 831	public void onPause() {
 832		listView.discardUndo();
 833		super.onPause();
 834		this.mActivityPaused = true;
 835		if (this.xmppConnectionServiceBound) {
 836			this.xmppConnectionService.getNotificationService().setIsInForeground(false);
 837		}
 838	}
 839
 840	@Override
 841	public void onResume() {
 842		super.onResume();
 843		final int theme = findTheme();
 844		final boolean usingEnterKey = usingEnterKey();
 845		if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
 846			recreate();
 847		}
 848		this.mActivityPaused = false;
 849		if (this.xmppConnectionServiceBound) {
 850			this.xmppConnectionService.getNotificationService().setIsInForeground(true);
 851		}
 852
 853		if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
 854			sendReadMarkerIfNecessary(getSelectedConversation());
 855		}
 856
 857	}
 858
 859	@Override
 860	public void onSaveInstanceState(final Bundle savedInstanceState) {
 861		Conversation conversation = getSelectedConversation();
 862		if (conversation != null) {
 863			savedInstanceState.putString(STATE_OPEN_CONVERSATION,
 864					conversation.getUuid());
 865		}
 866		savedInstanceState.putBoolean(STATE_PANEL_OPEN,
 867				isConversationsOverviewVisable());
 868		if (this.mPendingImageUris.size() >= 1) {
 869			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
 870		}
 871		super.onSaveInstanceState(savedInstanceState);
 872	}
 873
 874	@Override
 875	void onBackendConnected() {
 876		this.xmppConnectionService.getNotificationService().setIsInForeground(true);
 877		updateConversationList();
 878		if (xmppConnectionService.getAccounts().size() == 0) {
 879			if (!mRedirected) {
 880				this.mRedirected = true;
 881				startActivity(new Intent(this, EditAccountActivity.class));
 882				finish();
 883			}
 884		} else if (conversationList.size() <= 0) {
 885			if (!mRedirected) {
 886				this.mRedirected = true;
 887				Intent intent = new Intent(this, StartConversationActivity.class);
 888				intent.putExtra("init",true);
 889				startActivity(intent);
 890				finish();
 891			}
 892		} else if (getIntent() != null && VIEW_CONVERSATION.equals(getIntent().getType())) {
 893			handleViewConversationIntent(getIntent());
 894		} else if (selectConversationByUuid(mOpenConverstaion)) {
 895			if (mPanelOpen) {
 896				showConversationsOverview();
 897			} else {
 898				if (isConversationsOverviewHideable()) {
 899					openConversation();
 900				}
 901			}
 902			this.mConversationFragment.reInit(getSelectedConversation());
 903			mOpenConverstaion = null;
 904		} else if (getSelectedConversation() != null) {
 905			this.mConversationFragment.reInit(getSelectedConversation());
 906		} else {
 907			showConversationsOverview();
 908			mPendingImageUris.clear();
 909			mPendingFileUris.clear();
 910			mPendingGeoUri = null;
 911			setSelectedConversation(conversationList.get(0));
 912			this.mConversationFragment.reInit(getSelectedConversation());
 913		}
 914
 915		for(Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
 916			attachImageToConversation(getSelectedConversation(),i.next());
 917		}
 918
 919		for(Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
 920			attachFileToConversation(getSelectedConversation(),i.next());
 921		}
 922
 923		if (mPendingGeoUri != null) {
 924			attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
 925			mPendingGeoUri = null;
 926		}
 927		ExceptionHelper.checkForCrash(this, this.xmppConnectionService);
 928		setIntent(new Intent());
 929	}
 930
 931	private void handleViewConversationIntent(final Intent intent) {
 932		final String uuid = (String) intent.getExtras().get(CONVERSATION);
 933		final String downloadUuid = (String) intent.getExtras().get(MESSAGE);
 934		final String text = intent.getExtras().getString(TEXT, "");
 935		final String nick = intent.getExtras().getString(NICK, null);
 936		if (selectConversationByUuid(uuid)) {
 937			this.mConversationFragment.reInit(getSelectedConversation());
 938			if (nick != null) {
 939				this.mConversationFragment.highlightInConference(nick);
 940			} else {
 941				this.mConversationFragment.appendText(text);
 942			}
 943			hideConversationsOverview();
 944			openConversation();
 945			if (mContentView instanceof SlidingPaneLayout) {
 946				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
 947			}
 948			if (downloadUuid != null) {
 949				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
 950				if (message != null) {
 951					mConversationFragment.messageListAdapter.startDownloadable(message);
 952				}
 953			}
 954		}
 955	}
 956
 957	private boolean selectConversationByUuid(String uuid) {
 958		if (uuid == null) {
 959			return false;
 960		}
 961		for (Conversation aConversationList : conversationList) {
 962			if (aConversationList.getUuid().equals(uuid)) {
 963				setSelectedConversation(aConversationList);
 964				return true;
 965			}
 966		}
 967		return false;
 968	}
 969
 970	@Override
 971	protected void unregisterListeners() {
 972		super.unregisterListeners();
 973		xmppConnectionService.getNotificationService().setOpenConversation(null);
 974	}
 975
 976	@SuppressLint("NewApi")
 977	private static List<Uri> extractUriFromIntent(final Intent intent) {
 978		List<Uri> uris = new ArrayList<>();
 979		Uri uri = intent.getData();
 980		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
 981			ClipData clipData = intent.getClipData();
 982			for(int i = 0; i < clipData.getItemCount(); ++i) {
 983				uris.add(clipData.getItemAt(i).getUri());
 984			}
 985		} else {
 986			uris.add(uri);
 987		}
 988		return uris;
 989	}
 990
 991	@Override
 992	protected void onActivityResult(int requestCode, int resultCode,
 993			final Intent data) {
 994		super.onActivityResult(requestCode, resultCode, data);
 995		if (resultCode == RESULT_OK) {
 996			if (requestCode == REQUEST_DECRYPT_PGP) {
 997				mConversationFragment.hideSnackbar();
 998				mConversationFragment.updateMessages();
 999			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1000				mPendingImageUris.clear();
1001				mPendingImageUris.addAll(extractUriFromIntent(data));
1002				if (xmppConnectionServiceBound) {
1003					for(Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1004						attachImageToConversation(getSelectedConversation(),i.next());
1005					}
1006				}
1007			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1008				mPendingFileUris.clear();
1009				mPendingFileUris.addAll(extractUriFromIntent(data));
1010				if (xmppConnectionServiceBound) {
1011					for(Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1012						attachFileToConversation(getSelectedConversation(), i.next());
1013					}
1014				}
1015			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1016				if (mPendingImageUris.size() == 1) {
1017					Uri uri = mPendingImageUris.get(0);
1018					if (xmppConnectionServiceBound) {
1019						attachImageToConversation(getSelectedConversation(), uri);
1020						mPendingImageUris.clear();
1021					}
1022					Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1023					intent.setData(uri);
1024					sendBroadcast(intent);
1025				} else {
1026					mPendingImageUris.clear();
1027				}
1028			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1029				double latitude = data.getDoubleExtra("latitude",0);
1030				double longitude = data.getDoubleExtra("longitude",0);
1031				this.mPendingGeoUri = Uri.parse("geo:"+String.valueOf(latitude)+","+String.valueOf(longitude));
1032				if (xmppConnectionServiceBound) {
1033					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1034					this.mPendingGeoUri = null;
1035				}
1036			}
1037		}
1038	}
1039
1040	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1041		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1042
1043			@Override
1044			public void success(Message message) {
1045				xmppConnectionService.sendMessage(message);
1046			}
1047
1048			@Override
1049			public void error(int errorCode, Message object) {
1050
1051			}
1052
1053			@Override
1054			public void userInputRequried(PendingIntent pi, Message object) {
1055
1056			}
1057		});
1058	}
1059
1060	private void attachFileToConversation(Conversation conversation, Uri uri) {
1061		prepareFileToast = Toast.makeText(getApplicationContext(),
1062				getText(R.string.preparing_file), Toast.LENGTH_LONG);
1063		prepareFileToast.show();
1064		xmppConnectionService.attachFileToConversation(conversation,uri, new UiCallback<Message>() {
1065			@Override
1066			public void success(Message message) {
1067				hidePrepareFileToast();
1068				xmppConnectionService.sendMessage(message);
1069			}
1070
1071			@Override
1072			public void error(int errorCode, Message message) {
1073				displayErrorDialog(errorCode);
1074			}
1075
1076			@Override
1077			public void userInputRequried(PendingIntent pi, Message message) {
1078
1079			}
1080		});
1081	}
1082
1083	private void attachImageToConversation(Conversation conversation, Uri uri) {
1084		prepareFileToast = Toast.makeText(getApplicationContext(),
1085				getText(R.string.preparing_image), Toast.LENGTH_LONG);
1086		prepareFileToast.show();
1087		xmppConnectionService.attachImageToConversation(conversation, uri,
1088				new UiCallback<Message>() {
1089
1090					@Override
1091					public void userInputRequried(PendingIntent pi,
1092							Message object) {
1093						hidePrepareFileToast();
1094					}
1095
1096					@Override
1097					public void success(Message message) {
1098						xmppConnectionService.sendMessage(message);
1099					}
1100
1101					@Override
1102					public void error(int error, Message message) {
1103						hidePrepareFileToast();
1104						displayErrorDialog(error);
1105					}
1106				});
1107	}
1108
1109	private void hidePrepareFileToast() {
1110		if (prepareFileToast != null) {
1111			runOnUiThread(new Runnable() {
1112
1113				@Override
1114				public void run() {
1115					prepareFileToast.cancel();
1116				}
1117			});
1118		}
1119	}
1120
1121	public void updateConversationList() {
1122		xmppConnectionService
1123			.populateWithOrderedConversations(conversationList);
1124		if (swipedConversation != null) {
1125			if (swipedConversation.isRead()) {
1126				conversationList.remove(swipedConversation);
1127			} else {
1128				listView.discardUndo();
1129			}
1130		}
1131		listAdapter.notifyDataSetChanged();
1132	}
1133
1134	public void runIntent(PendingIntent pi, int requestCode) {
1135		try {
1136			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1137					null, 0, 0, 0);
1138		} catch (final SendIntentException ignored) {
1139		}
1140	}
1141
1142	public void encryptTextMessage(Message message) {
1143		xmppConnectionService.getPgpEngine().encrypt(message,
1144				new UiCallback<Message>() {
1145
1146					@Override
1147					public void userInputRequried(PendingIntent pi,
1148							Message message) {
1149						ConversationActivity.this.runIntent(pi,
1150								ConversationActivity.REQUEST_SEND_MESSAGE);
1151					}
1152
1153					@Override
1154					public void success(Message message) {
1155						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1156						xmppConnectionService.sendMessage(message);
1157					}
1158
1159					@Override
1160					public void error(int error, Message message) {
1161
1162					}
1163				});
1164	}
1165
1166	public boolean forceEncryption() {
1167		return getPreferences().getBoolean("force_encryption", false);
1168	}
1169
1170	public boolean useSendButtonToIndicateStatus() {
1171		return getPreferences().getBoolean("send_button_status", false);
1172	}
1173
1174	public boolean indicateReceived() {
1175		return getPreferences().getBoolean("indicate_received", false);
1176	}
1177
1178	@Override
1179	protected void refreshUiReal() {
1180		updateConversationList();
1181		if (xmppConnectionService != null && xmppConnectionService.getAccounts().size() == 0) {
1182			if (!mRedirected) {
1183				this.mRedirected = true;
1184				startActivity(new Intent(this, EditAccountActivity.class));
1185				finish();
1186			}
1187		} else if (conversationList.size() == 0) {
1188			if (!mRedirected) {
1189				this.mRedirected = true;
1190				Intent intent = new Intent(this, StartConversationActivity.class);
1191				intent.putExtra("init",true);
1192				startActivity(intent);
1193				finish();
1194			}
1195		} else {
1196			ConversationActivity.this.mConversationFragment.updateMessages();
1197			updateActionBarTitle();
1198		}
1199	}
1200
1201	@Override
1202	public void onAccountUpdate() {
1203		this.refreshUi();
1204	}
1205
1206	@Override
1207	public void onConversationUpdate() {
1208		this.refreshUi();
1209	}
1210
1211	@Override
1212	public void onRosterUpdate() {
1213		this.refreshUi();
1214	}
1215
1216	@Override
1217	public void OnUpdateBlocklist(Status status) {
1218		this.refreshUi();
1219		runOnUiThread(new Runnable() {
1220			@Override
1221			public void run() {
1222				invalidateOptionsMenu();
1223			}
1224		});
1225	}
1226
1227	public void unblockConversation(final Blockable conversation) {
1228		xmppConnectionService.sendUnblockRequest(conversation);
1229	}
1230
1231	public boolean enterIsSend() {
1232		return getPreferences().getBoolean("enter_is_send",false);
1233	}
1234}