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