ConversationFragment.java

   1package eu.siacs.conversations.ui;
   2
   3import android.annotation.SuppressLint;
   4import android.app.Activity;
   5import android.content.SharedPreferences;
   6import android.content.pm.PackageManager;
   7import android.databinding.DataBindingUtil;
   8import android.net.Uri;
   9import android.os.Build;
  10import android.preference.PreferenceManager;
  11import android.provider.MediaStore;
  12import android.support.annotation.IdRes;
  13import android.support.v7.app.AlertDialog;
  14import android.app.Fragment;
  15import android.app.PendingIntent;
  16import android.content.ActivityNotFoundException;
  17import android.content.Context;
  18import android.content.DialogInterface;
  19import android.content.Intent;
  20import android.content.IntentSender.SendIntentException;
  21import android.os.Bundle;
  22import android.os.Handler;
  23import android.os.SystemClock;
  24import android.support.v13.view.inputmethod.InputConnectionCompat;
  25import android.support.v13.view.inputmethod.InputContentInfoCompat;
  26import android.text.Editable;
  27import android.util.Log;
  28import android.util.Pair;
  29import android.view.ContextMenu;
  30import android.view.ContextMenu.ContextMenuInfo;
  31import android.view.Gravity;
  32import android.view.LayoutInflater;
  33import android.view.Menu;
  34import android.view.MenuInflater;
  35import android.view.MenuItem;
  36import android.view.MotionEvent;
  37import android.view.View;
  38import android.view.View.OnClickListener;
  39import android.view.ViewGroup;
  40import android.view.inputmethod.EditorInfo;
  41import android.view.inputmethod.InputMethodManager;
  42import android.widget.AbsListView;
  43import android.widget.AbsListView.OnScrollListener;
  44import android.widget.AdapterView;
  45import android.widget.AdapterView.AdapterContextMenuInfo;
  46import android.widget.CheckBox;
  47import android.widget.ListView;
  48import android.widget.PopupMenu;
  49import android.widget.TextView.OnEditorActionListener;
  50import android.widget.Toast;
  51
  52import org.openintents.openpgp.util.OpenPgpApi;
  53
  54import java.util.ArrayList;
  55import java.util.Arrays;
  56import java.util.Collections;
  57import java.util.HashSet;
  58import java.util.Iterator;
  59import java.util.List;
  60import java.util.Set;
  61import java.util.UUID;
  62import java.util.concurrent.atomic.AtomicBoolean;
  63
  64import eu.siacs.conversations.Config;
  65import eu.siacs.conversations.R;
  66import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  67import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  68import eu.siacs.conversations.databinding.FragmentConversationBinding;
  69import eu.siacs.conversations.entities.Account;
  70import eu.siacs.conversations.entities.Blockable;
  71import eu.siacs.conversations.entities.Contact;
  72import eu.siacs.conversations.entities.Conversation;
  73import eu.siacs.conversations.entities.DownloadableFile;
  74import eu.siacs.conversations.entities.Message;
  75import eu.siacs.conversations.entities.MucOptions;
  76import eu.siacs.conversations.entities.Presence;
  77import eu.siacs.conversations.entities.ReadByMarker;
  78import eu.siacs.conversations.entities.Transferable;
  79import eu.siacs.conversations.entities.TransferablePlaceholder;
  80import eu.siacs.conversations.http.HttpDownloadConnection;
  81import eu.siacs.conversations.persistance.FileBackend;
  82import eu.siacs.conversations.services.MessageArchiveService;
  83import eu.siacs.conversations.services.XmppConnectionService;
  84import eu.siacs.conversations.ui.adapter.MessageAdapter;
  85import eu.siacs.conversations.ui.util.ActivityResult;
  86import eu.siacs.conversations.ui.util.AttachmentTool;
  87import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
  88import eu.siacs.conversations.ui.util.PendingItem;
  89import eu.siacs.conversations.ui.util.PresenceSelector;
  90import eu.siacs.conversations.ui.util.SendButtonAction;
  91import eu.siacs.conversations.ui.util.SendButtonTool;
  92import eu.siacs.conversations.ui.widget.EditMessage;
  93import eu.siacs.conversations.utils.MessageUtils;
  94import eu.siacs.conversations.utils.NickValidityChecker;
  95import eu.siacs.conversations.utils.StylingHelper;
  96import eu.siacs.conversations.utils.UIHelper;
  97import eu.siacs.conversations.xmpp.XmppConnection;
  98import eu.siacs.conversations.xmpp.chatstate.ChatState;
  99import eu.siacs.conversations.xmpp.jid.InvalidJidException;
 100import eu.siacs.conversations.xmpp.jid.Jid;
 101
 102import static eu.siacs.conversations.ui.XmppActivity.EXTRA_ACCOUNT;
 103import static eu.siacs.conversations.ui.XmppActivity.REQUEST_ANNOUNCE_PGP;
 104import static eu.siacs.conversations.ui.XmppActivity.REQUEST_CHOOSE_PGP_ID;
 105
 106
 107public class ConversationFragment extends XmppFragment implements EditMessage.KeyboardListener {
 108
 109
 110	public static final int REQUEST_SEND_MESSAGE = 0x0201;
 111	public static final int REQUEST_DECRYPT_PGP = 0x0202;
 112	public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
 113	public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
 114	public static final int REQUEST_TRUST_KEYS_MENU = 0x0209;
 115	public static final int REQUEST_START_DOWNLOAD = 0x0210;
 116	public static final int REQUEST_ADD_EDITOR_CONTENT = 0x0211;
 117	public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
 118	public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
 119	public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
 120	public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
 121	public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
 122	public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
 123	public static final int ATTACHMENT_CHOICE_RECORD_VIDEO = 0x0307;
 124
 125	public static final String RECENTLY_USED_QUICK_ACTION = "recently_used_quick_action";
 126	public static final String STATE_CONVERSATION_UUID = ConversationFragment.class.getName() + ".uuid";
 127	public static final String STATE_SCROLL_POSITION = ConversationFragment.class.getName() + ".scroll_position";
 128
 129
 130	final protected List<Message> messageList = new ArrayList<>();
 131	private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
 132	private final PendingItem<String> pendingConversationsUuid = new PendingItem<>();
 133	private final PendingItem<Bundle> pendingExtras = new PendingItem<>();
 134	public Uri mPendingEditorContent = null;
 135	protected MessageAdapter messageListAdapter;
 136	private Conversation conversation;
 137	private FragmentConversationBinding binding;
 138	private Toast messageLoaderToast;
 139	private ConversationActivity activity;
 140
 141	private OnClickListener clickToMuc = new OnClickListener() {
 142
 143		@Override
 144		public void onClick(View v) {
 145			Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
 146			intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 147			intent.putExtra("uuid", conversation.getUuid());
 148			startActivity(intent);
 149		}
 150	};
 151	private OnClickListener leaveMuc = new OnClickListener() {
 152
 153		@Override
 154		public void onClick(View v) {
 155			activity.xmppConnectionService.archiveConversation(conversation);
 156			activity.onConversationArchived(conversation);
 157		}
 158	};
 159	private OnClickListener joinMuc = new OnClickListener() {
 160
 161		@Override
 162		public void onClick(View v) {
 163			activity.xmppConnectionService.joinMuc(conversation);
 164		}
 165	};
 166	private OnClickListener enterPassword = new OnClickListener() {
 167
 168		@Override
 169		public void onClick(View v) {
 170			MucOptions muc = conversation.getMucOptions();
 171			String password = muc.getPassword();
 172			if (password == null) {
 173				password = "";
 174			}
 175			activity.quickPasswordEdit(password, value -> {
 176				activity.xmppConnectionService.providePasswordForMuc(conversation, value);
 177				return null;
 178			});
 179		}
 180	};
 181	private OnScrollListener mOnScrollListener = new OnScrollListener() {
 182
 183		@Override
 184		public void onScrollStateChanged(AbsListView view, int scrollState) {
 185			// TODO Auto-generated method stub
 186
 187		}
 188
 189		@Override
 190		public void onScroll(final AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
 191			synchronized (ConversationFragment.this.messageList) {
 192				if (firstVisibleItem < 5 && conversation != null && conversation.messagesLoaded.compareAndSet(true, false) && messageList.size() > 0) {
 193					long timestamp;
 194					if (messageList.get(0).getType() == Message.TYPE_STATUS && messageList.size() >= 2) {
 195						timestamp = messageList.get(1).getTimeSent();
 196					} else {
 197						timestamp = messageList.get(0).getTimeSent();
 198					}
 199					activity.xmppConnectionService.loadMoreMessages(conversation, timestamp, new XmppConnectionService.OnMoreMessagesLoaded() {
 200						@Override
 201						public void onMoreMessagesLoaded(final int c, final Conversation conversation) {
 202							if (ConversationFragment.this.conversation != conversation) {
 203								conversation.messagesLoaded.set(true);
 204								return;
 205							}
 206							getActivity().runOnUiThread(() -> {
 207								final int oldPosition = binding.messagesView.getFirstVisiblePosition();
 208								Message message = null;
 209								int childPos;
 210								for (childPos = 0; childPos + oldPosition < messageList.size(); ++childPos) {
 211									message = messageList.get(oldPosition + childPos);
 212									if (message.getType() != Message.TYPE_STATUS) {
 213										break;
 214									}
 215								}
 216								final String uuid = message != null ? message.getUuid() : null;
 217								View v = binding.messagesView.getChildAt(childPos);
 218								final int pxOffset = (v == null) ? 0 : v.getTop();
 219								ConversationFragment.this.conversation.populateWithMessages(ConversationFragment.this.messageList);
 220								try {
 221									updateStatusMessages();
 222								} catch (IllegalStateException e) {
 223									Log.d(Config.LOGTAG, "caught illegal state exception while updating status messages");
 224								}
 225								messageListAdapter.notifyDataSetChanged();
 226								int pos = Math.max(getIndexOf(uuid, messageList), 0);
 227								binding.messagesView.setSelectionFromTop(pos, pxOffset);
 228								if (messageLoaderToast != null) {
 229									messageLoaderToast.cancel();
 230								}
 231								conversation.messagesLoaded.set(true);
 232							});
 233						}
 234
 235						@Override
 236						public void informUser(final int resId) {
 237
 238							getActivity().runOnUiThread(() -> {
 239								if (messageLoaderToast != null) {
 240									messageLoaderToast.cancel();
 241								}
 242								if (ConversationFragment.this.conversation != conversation) {
 243									return;
 244								}
 245								messageLoaderToast = Toast.makeText(view.getContext(), resId, Toast.LENGTH_LONG);
 246								messageLoaderToast.show();
 247							});
 248
 249						}
 250					});
 251
 252				}
 253			}
 254		}
 255	};
 256
 257	private EditMessage.OnCommitContentListener mEditorContentListener = new EditMessage.OnCommitContentListener() {
 258		@Override
 259		public boolean onCommitContent(InputContentInfoCompat inputContentInfo, int flags, Bundle opts, String[] contentMimeTypes) {
 260			// try to get permission to read the image, if applicable
 261			if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
 262				try {
 263					inputContentInfo.requestPermission();
 264				} catch (Exception e) {
 265					Log.e(Config.LOGTAG, "InputContentInfoCompat#requestPermission() failed.", e);
 266					Toast.makeText(getActivity(), activity.getString(R.string.no_permission_to_access_x, inputContentInfo.getDescription()), Toast.LENGTH_LONG
 267					).show();
 268					return false;
 269				}
 270			}
 271			if (activity.hasStoragePermission(REQUEST_ADD_EDITOR_CONTENT)) {
 272				attachImageToConversation(inputContentInfo.getContentUri());
 273			} else {
 274				mPendingEditorContent = inputContentInfo.getContentUri();
 275			}
 276			return true;
 277		}
 278	};
 279	private Message selectedMessage;
 280	private OnClickListener mEnableAccountListener = new OnClickListener() {
 281		@Override
 282		public void onClick(View v) {
 283			final Account account = conversation == null ? null : conversation.getAccount();
 284			if (account != null) {
 285				account.setOption(Account.OPTION_DISABLED, false);
 286				activity.xmppConnectionService.updateAccount(account);
 287			}
 288		}
 289	};
 290	private OnClickListener mUnblockClickListener = new OnClickListener() {
 291		@Override
 292		public void onClick(final View v) {
 293			v.post(() -> v.setVisibility(View.INVISIBLE));
 294			if (conversation.isDomainBlocked()) {
 295				BlockContactDialog.show(activity, conversation);
 296			} else {
 297				unblockConversation(conversation);
 298			}
 299		}
 300	};
 301	private OnClickListener mBlockClickListener = this::showBlockSubmenu;
 302	private OnClickListener mAddBackClickListener = new OnClickListener() {
 303
 304		@Override
 305		public void onClick(View v) {
 306			final Contact contact = conversation == null ? null : conversation.getContact();
 307			if (contact != null) {
 308				activity.xmppConnectionService.createContact(contact);
 309				activity.switchToContactDetails(contact);
 310			}
 311		}
 312	};
 313	private View.OnLongClickListener mLongPressBlockListener = this::showBlockSubmenu;
 314	private OnClickListener mAllowPresenceSubscription = new OnClickListener() {
 315		@Override
 316		public void onClick(View v) {
 317			final Contact contact = conversation == null ? null : conversation.getContact();
 318			if (contact != null) {
 319				activity.xmppConnectionService.sendPresencePacket(contact.getAccount(),
 320						activity.xmppConnectionService.getPresenceGenerator()
 321								.sendPresenceUpdatesTo(contact));
 322				hideSnackbar();
 323			}
 324		}
 325	};
 326
 327	protected OnClickListener clickToDecryptListener = new OnClickListener() {
 328
 329		@Override
 330		public void onClick(View v) {
 331			PendingIntent pendingIntent = conversation.getAccount().getPgpDecryptionService().getPendingIntent();
 332			if (pendingIntent != null) {
 333				try {
 334					getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(),
 335							REQUEST_DECRYPT_PGP,
 336							null,
 337							0,
 338							0,
 339							0);
 340				} catch (SendIntentException e) {
 341					Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
 342					conversation.getAccount().getPgpDecryptionService().continueDecryption(true);
 343				}
 344			}
 345			updateSnackBar(conversation);
 346		}
 347	};
 348	private AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
 349	private OnEditorActionListener mEditorActionListener = (v, actionId, event) -> {
 350		if (actionId == EditorInfo.IME_ACTION_SEND) {
 351			InputMethodManager imm = (InputMethodManager) v.getContext()
 352					.getSystemService(Context.INPUT_METHOD_SERVICE);
 353			if (imm.isFullscreenMode()) {
 354				imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
 355			}
 356			sendMessage();
 357			return true;
 358		} else {
 359			return false;
 360		}
 361	};
 362	private OnClickListener mSendButtonListener = new OnClickListener() {
 363
 364		@Override
 365		public void onClick(View v) {
 366			Object tag = v.getTag();
 367			if (tag instanceof SendButtonAction) {
 368				SendButtonAction action = (SendButtonAction) tag;
 369				switch (action) {
 370					case TAKE_PHOTO:
 371					case RECORD_VIDEO:
 372					case SEND_LOCATION:
 373					case RECORD_VOICE:
 374					case CHOOSE_PICTURE:
 375						attachFile(action.toChoice());
 376						break;
 377					case CANCEL:
 378						if (conversation != null) {
 379							if (conversation.setCorrectingMessage(null)) {
 380								binding.textinput.setText("");
 381								binding.textinput.append(conversation.getDraftMessage());
 382								conversation.setDraftMessage(null);
 383							} else if (conversation.getMode() == Conversation.MODE_MULTI) {
 384								conversation.setNextCounterpart(null);
 385							}
 386							updateChatMsgHint();
 387							updateSendButton();
 388							updateEditablity();
 389						}
 390						break;
 391					default:
 392						sendMessage();
 393				}
 394			} else {
 395				sendMessage();
 396			}
 397		}
 398	};
 399	private int completionIndex = 0;
 400	private int lastCompletionLength = 0;
 401	private String incomplete;
 402	private int lastCompletionCursor;
 403	private boolean firstWord = false;
 404	private Message mPendingDownloadableMessage;
 405
 406	private int getIndexOf(String uuid, List<Message> messages) {
 407		if (uuid == null) {
 408			return messages.size() - 1;
 409		}
 410		for (int i = 0; i < messages.size(); ++i) {
 411			if (uuid.equals(messages.get(i).getUuid())) {
 412				return i;
 413			} else {
 414				Message next = messages.get(i);
 415				while (next != null && next.wasMergedIntoPrevious()) {
 416					if (uuid.equals(next.getUuid())) {
 417						return i;
 418					}
 419					next = next.next();
 420				}
 421
 422			}
 423		}
 424		return -1;
 425	}
 426
 427	public Pair<Integer, Integer> getScrollPosition() {
 428		if (this.binding.messagesView.getCount() == 0 ||
 429				this.binding.messagesView.getLastVisiblePosition() == this.binding.messagesView.getCount() - 1) {
 430			return null;
 431		} else {
 432			final int pos = this.binding.messagesView.getFirstVisiblePosition();
 433			final View view = this.binding.messagesView.getChildAt(0);
 434			if (view == null) {
 435				return null;
 436			} else {
 437				return new Pair<>(pos, view.getTop());
 438			}
 439		}
 440	}
 441
 442	public void setScrollPosition(Pair<Integer, Integer> scrollPosition) {
 443		if (scrollPosition != null) {
 444			this.binding.messagesView.setSelectionFromTop(scrollPosition.first, scrollPosition.second);
 445		}
 446	}
 447
 448
 449	private void attachLocationToConversation(Conversation conversation, Uri uri) {
 450		if (conversation == null) {
 451			return;
 452		}
 453		activity.xmppConnectionService.attachLocationToConversation(conversation, uri, new UiCallback<Message>() {
 454
 455			@Override
 456			public void success(Message message) {
 457				activity.xmppConnectionService.sendMessage(message);
 458			}
 459
 460			@Override
 461			public void error(int errorCode, Message object) {
 462
 463			}
 464
 465			@Override
 466			public void userInputRequried(PendingIntent pi, Message object) {
 467
 468			}
 469		});
 470	}
 471
 472	private void attachFileToConversation(Conversation conversation, Uri uri) {
 473		if (conversation == null) {
 474			return;
 475		}
 476		final Toast prepareFileToast = Toast.makeText(getActivity(), getText(R.string.preparing_file), Toast.LENGTH_LONG);
 477		prepareFileToast.show();
 478		activity.delegateUriPermissionsToService(uri);
 479		activity.xmppConnectionService.attachFileToConversation(conversation, uri, new UiInformableCallback<Message>() {
 480			@Override
 481			public void inform(final String text) {
 482				hidePrepareFileToast(prepareFileToast);
 483				getActivity().runOnUiThread(() -> activity.replaceToast(text));
 484			}
 485
 486			@Override
 487			public void success(Message message) {
 488				getActivity().runOnUiThread(() -> activity.hideToast());
 489				hidePrepareFileToast(prepareFileToast);
 490				activity.xmppConnectionService.sendMessage(message);
 491			}
 492
 493			@Override
 494			public void error(final int errorCode, Message message) {
 495				hidePrepareFileToast(prepareFileToast);
 496				getActivity().runOnUiThread(() -> activity.replaceToast(getString(errorCode)));
 497
 498			}
 499
 500			@Override
 501			public void userInputRequried(PendingIntent pi, Message message) {
 502				hidePrepareFileToast(prepareFileToast);
 503			}
 504		});
 505	}
 506
 507	public void attachImageToConversation(Uri uri) {
 508		this.attachImageToConversation(conversation, uri);
 509	}
 510
 511	private void attachImageToConversation(Conversation conversation, Uri uri) {
 512		if (conversation == null) {
 513			return;
 514		}
 515		final Toast prepareFileToast = Toast.makeText(getActivity(), getText(R.string.preparing_image), Toast.LENGTH_LONG);
 516		prepareFileToast.show();
 517		activity.delegateUriPermissionsToService(uri);
 518		activity.xmppConnectionService.attachImageToConversation(conversation, uri,
 519				new UiCallback<Message>() {
 520
 521					@Override
 522					public void userInputRequried(PendingIntent pi, Message object) {
 523						hidePrepareFileToast(prepareFileToast);
 524					}
 525
 526					@Override
 527					public void success(Message message) {
 528						hidePrepareFileToast(prepareFileToast);
 529						activity.xmppConnectionService.sendMessage(message);
 530					}
 531
 532					@Override
 533					public void error(final int error, Message message) {
 534						hidePrepareFileToast(prepareFileToast);
 535						activity.runOnUiThread(() -> activity.replaceToast(getString(error)));
 536					}
 537				});
 538	}
 539
 540	private void hidePrepareFileToast(final Toast prepareFileToast) {
 541		if (prepareFileToast != null) {
 542			activity.runOnUiThread(prepareFileToast::cancel);
 543		}
 544	}
 545
 546	private void sendMessage() {
 547		final String body = this.binding.textinput.getText().toString();
 548		final Conversation conversation = this.conversation;
 549		if (body.length() == 0 || conversation == null) {
 550			return;
 551		}
 552		final Message message;
 553		if (conversation.getCorrectingMessage() == null) {
 554			message = new Message(conversation, body, conversation.getNextEncryption());
 555			if (conversation.getMode() == Conversation.MODE_MULTI) {
 556				final Jid nextCounterpart = conversation.getNextCounterpart();
 557				if (nextCounterpart != null) {
 558					message.setCounterpart(nextCounterpart);
 559					message.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(nextCounterpart));
 560					message.setType(Message.TYPE_PRIVATE);
 561				}
 562			}
 563		} else {
 564			message = conversation.getCorrectingMessage();
 565			message.setBody(body);
 566			message.setEdited(message.getUuid());
 567			message.setUuid(UUID.randomUUID().toString());
 568		}
 569		switch (message.getConversation().getNextEncryption()) {
 570			case Message.ENCRYPTION_PGP:
 571				sendPgpMessage(message);
 572				break;
 573			case Message.ENCRYPTION_AXOLOTL:
 574				if (!trustKeysIfNeeded(REQUEST_TRUST_KEYS_TEXT)) {
 575					sendAxolotlMessage(message);
 576				}
 577				break;
 578			default:
 579				sendPlainTextMessage(message);
 580		}
 581	}
 582
 583	protected boolean trustKeysIfNeeded(int requestCode) {
 584		return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
 585	}
 586
 587	protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
 588		AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
 589		final List<Jid> targets = axolotlService.getCryptoTargets(conversation);
 590		boolean hasUnaccepted = !conversation.getAcceptedCryptoTargets().containsAll(targets);
 591		boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided()).isEmpty();
 592		boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets).isEmpty();
 593		boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(conversation).isEmpty();
 594		boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
 595		if (hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
 596			axolotlService.createSessionsIfNeeded(conversation);
 597			Intent intent = new Intent(getActivity(), TrustKeysActivity.class);
 598			String[] contacts = new String[targets.size()];
 599			for (int i = 0; i < contacts.length; ++i) {
 600				contacts[i] = targets.get(i).toString();
 601			}
 602			intent.putExtra("contacts", contacts);
 603			intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
 604			intent.putExtra("choice", attachmentChoice);
 605			intent.putExtra("conversation", conversation.getUuid());
 606			startActivityForResult(intent, requestCode);
 607			return true;
 608		} else {
 609			return false;
 610		}
 611	}
 612
 613	public void updateChatMsgHint() {
 614		final boolean multi = conversation.getMode() == Conversation.MODE_MULTI;
 615		if (conversation.getCorrectingMessage() != null) {
 616			this.binding.textinput.setHint(R.string.send_corrected_message);
 617		} else if (multi && conversation.getNextCounterpart() != null) {
 618			this.binding.textinput.setHint(getString(
 619					R.string.send_private_message_to,
 620					conversation.getNextCounterpart().getResourcepart()));
 621		} else if (multi && !conversation.getMucOptions().participating()) {
 622			this.binding.textinput.setHint(R.string.you_are_not_participating);
 623		} else {
 624			this.binding.textinput.setHint(UIHelper.getMessageHint(getActivity(), conversation));
 625			getActivity().invalidateOptionsMenu();
 626		}
 627	}
 628
 629	public void setupIme() {
 630		this.binding.textinput.refreshIme();
 631	}
 632
 633	private void handleActivityResult(ActivityResult activityResult) {
 634		if (activityResult.resultCode == Activity.RESULT_OK) {
 635			handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
 636		} else {
 637			handleNegativeActivityResult(activityResult.requestCode);
 638		}
 639	}
 640
 641	private void handlePositiveActivityResult(int requestCode, final Intent data) {
 642		switch (requestCode) {
 643			case REQUEST_TRUST_KEYS_TEXT:
 644				final String body = this.binding.textinput.getText().toString();
 645				Message message = new Message(conversation, body, conversation.getNextEncryption());
 646				sendAxolotlMessage(message);
 647				break;
 648			case REQUEST_TRUST_KEYS_MENU:
 649				int choice = data.getIntExtra("choice", ATTACHMENT_CHOICE_INVALID);
 650				selectPresenceToAttachFile(choice);
 651				break;
 652			case REQUEST_CHOOSE_PGP_ID:
 653				long id = data.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, 0);
 654				if (id != 0) {
 655					conversation.getAccount().setPgpSignId(id);
 656					activity.announcePgp(conversation.getAccount(), null, null, activity.onOpenPGPKeyPublished);
 657				} else {
 658					activity.choosePgpSignId(conversation.getAccount());
 659				}
 660				break;
 661			case REQUEST_ANNOUNCE_PGP:
 662				activity.announcePgp(conversation.getAccount(), conversation, data, activity.onOpenPGPKeyPublished);
 663				break;
 664			case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 665				List<Uri> imageUris = AttachmentTool.extractUriFromIntent(data);
 666				for (Iterator<Uri> i = imageUris.iterator(); i.hasNext(); i.remove()) {
 667					Log.d(Config.LOGTAG, "ConversationsActivity.onActivityResult() - attaching image to conversations. CHOOSE_IMAGE");
 668					attachImageToConversation(conversation, i.next());
 669				}
 670				break;
 671			case ATTACHMENT_CHOICE_CHOOSE_FILE:
 672			case ATTACHMENT_CHOICE_RECORD_VIDEO:
 673			case ATTACHMENT_CHOICE_RECORD_VOICE:
 674				final List<Uri> fileUris = AttachmentTool.extractUriFromIntent(data);
 675				final PresenceSelector.OnPresenceSelected callback = () -> {
 676					for (Iterator<Uri> i = fileUris.iterator(); i.hasNext(); i.remove()) {
 677						Log.d(Config.LOGTAG, "ConversationsActivity.onActivityResult() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO");
 678						attachFileToConversation(conversation, i.next());
 679					}
 680				};
 681				if (conversation == null || conversation.getMode() == Conversation.MODE_MULTI || FileBackend.allFilesUnderSize(getActivity(), fileUris, getMaxHttpUploadSize(conversation))) {
 682					callback.onPresenceSelected();
 683				} else {
 684					activity.selectPresence(conversation, callback);
 685				}
 686				break;
 687			case ATTACHMENT_CHOICE_LOCATION:
 688				double latitude = data.getDoubleExtra("latitude", 0);
 689				double longitude = data.getDoubleExtra("longitude", 0);
 690				Uri geo = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
 691				attachLocationToConversation(conversation, geo);
 692				break;
 693		}
 694	}
 695
 696	private void handleNegativeActivityResult(int requestCode) {
 697		switch (requestCode) {
 698			//nothing to do for now
 699		}
 700	}
 701
 702	@Override
 703	public void onActivityResult(int requestCode, int resultCode, final Intent data) {
 704		super.onActivityResult(requestCode, resultCode, data);
 705		ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
 706		if (activity != null && activity.xmppConnectionService != null) {
 707			handleActivityResult(activityResult);
 708		} else {
 709			this.postponedActivityResult.push(activityResult);
 710		}
 711	}
 712
 713	public void unblockConversation(final Blockable conversation) {
 714		activity.xmppConnectionService.sendUnblockRequest(conversation);
 715	}
 716
 717	@Override
 718	public void onAttach(Activity activity) {
 719		super.onAttach(activity);
 720		Log.d(Config.LOGTAG, "ConversationFragment.onAttach()");
 721		if (activity instanceof ConversationActivity) {
 722			this.activity = (ConversationActivity) activity;
 723		} else {
 724			throw new IllegalStateException("Trying to attach fragment to activity that is not the ConversationActivity");
 725		}
 726	}
 727
 728	@Override
 729	public void onDetach() {
 730		super.onDetach();
 731		this.activity = null;
 732	}
 733
 734	@Override
 735	public void onCreate(Bundle savedInstanceState) {
 736		super.onCreate(savedInstanceState);
 737		setHasOptionsMenu(true);
 738	}
 739
 740
 741	@Override
 742	public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
 743		menuInflater.inflate(R.menu.fragment_conversation, menu);
 744		final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
 745		final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
 746		final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
 747		final MenuItem menuMute = menu.findItem(R.id.action_mute);
 748		final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
 749
 750
 751		if (conversation != null) {
 752			if (conversation.getMode() == Conversation.MODE_MULTI) {
 753				menuContactDetails.setVisible(false);
 754				menuInviteContact.setVisible(conversation.getMucOptions().canInvite());
 755			} else {
 756				menuContactDetails.setVisible(!this.conversation.withSelf());
 757				menuMucDetails.setVisible(false);
 758				final XmppConnectionService service = activity.xmppConnectionService;
 759				menuInviteContact.setVisible(service != null && service.findConferenceServer(conversation.getAccount()) != null);
 760			}
 761			if (conversation.isMuted()) {
 762				menuMute.setVisible(false);
 763			} else {
 764				menuUnmute.setVisible(false);
 765			}
 766			ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu);
 767			ConversationMenuConfigurator.configureEncryptionMenu(conversation, menu);
 768		}
 769		super.onCreateOptionsMenu(menu, menuInflater);
 770	}
 771
 772	@Override
 773	public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 774		this.binding = DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
 775		binding.getRoot().setOnClickListener(null); //TODO why the fuck did we do this?
 776
 777		binding.textinput.addTextChangedListener(new StylingHelper.MessageEditorStyler(binding.textinput));
 778
 779		binding.textinput.setOnEditorActionListener(mEditorActionListener);
 780		binding.textinput.setRichContentListener(new String[]{"image/*"}, mEditorContentListener);
 781
 782		binding.textSendButton.setOnClickListener(this.mSendButtonListener);
 783
 784		binding.messagesView.setOnScrollListener(mOnScrollListener);
 785		binding.messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
 786		messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList);
 787		messageListAdapter.setOnContactPictureClicked(message -> {
 788			final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
 789			if (received) {
 790				if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
 791					Jid user = message.getCounterpart();
 792					if (user != null && !user.isBareJid()) {
 793						if (!message.getConversation().getMucOptions().isUserInRoom(user)) {
 794							Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResourcepart()), Toast.LENGTH_SHORT).show();
 795						}
 796						highlightInConference(user.getResourcepart());
 797					}
 798					return;
 799				} else {
 800					if (!message.getContact().isSelf()) {
 801						String fingerprint;
 802						if (message.getEncryption() == Message.ENCRYPTION_PGP
 803								|| message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 804							fingerprint = "pgp";
 805						} else {
 806							fingerprint = message.getFingerprint();
 807						}
 808						activity.switchToContactDetails(message.getContact(), fingerprint);
 809						return;
 810					}
 811				}
 812			}
 813			Account account = message.getConversation().getAccount();
 814			Intent intent;
 815			if (activity.manuallyChangePresence() && !received) {
 816				intent = new Intent(activity, SetPresenceActivity.class);
 817				intent.putExtra(EXTRA_ACCOUNT, account.getJid().toBareJid().toString());
 818			} else {
 819				intent = new Intent(activity, EditAccountActivity.class);
 820				intent.putExtra("jid", account.getJid().toBareJid().toString());
 821				String fingerprint;
 822				if (message.getEncryption() == Message.ENCRYPTION_PGP
 823						|| message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 824					fingerprint = "pgp";
 825				} else {
 826					fingerprint = message.getFingerprint();
 827				}
 828				intent.putExtra("fingerprint", fingerprint);
 829			}
 830			startActivity(intent);
 831		});
 832		messageListAdapter.setOnContactPictureLongClicked(message -> {
 833			if (message.getStatus() <= Message.STATUS_RECEIVED) {
 834				if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
 835					final MucOptions mucOptions = conversation.getMucOptions();
 836					if (!mucOptions.allowPm()) {
 837						Toast.makeText(getActivity(), R.string.private_messages_are_disabled, Toast.LENGTH_SHORT).show();
 838						return;
 839					}
 840					Jid user = message.getCounterpart();
 841					if (user != null && !user.isBareJid()) {
 842						if (mucOptions.isUserInRoom(user)) {
 843							privateMessageWith(user);
 844						} else {
 845							Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResourcepart()), Toast.LENGTH_SHORT).show();
 846						}
 847					}
 848				}
 849			} else {
 850				activity.showQrCode(conversation.getAccount().getShareableUri());
 851			}
 852		});
 853		messageListAdapter.setOnQuoteListener(this::quoteText);
 854		binding.messagesView.setAdapter(messageListAdapter);
 855
 856		registerForContextMenu(binding.messagesView);
 857
 858		return binding.getRoot();
 859	}
 860
 861	private void quoteText(String text) {
 862		if (binding.textinput.isEnabled()) {
 863			text = text.replaceAll("(\n *){2,}", "\n").replaceAll("(^|\n)", "$1> ").replaceAll("\n$", "");
 864			Editable editable = binding.textinput.getEditableText();
 865			int position = binding.textinput.getSelectionEnd();
 866			if (position == -1) position = editable.length();
 867			if (position > 0 && editable.charAt(position - 1) != '\n') {
 868				editable.insert(position++, "\n");
 869			}
 870			editable.insert(position, text);
 871			position += text.length();
 872			editable.insert(position++, "\n");
 873			if (position < editable.length() && editable.charAt(position) != '\n') {
 874				editable.insert(position, "\n");
 875			}
 876			binding.textinput.setSelection(position);
 877			binding.textinput.requestFocus();
 878			InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
 879			if (inputMethodManager != null) {
 880				inputMethodManager.showSoftInput(binding.textinput, InputMethodManager.SHOW_IMPLICIT);
 881			}
 882		}
 883	}
 884
 885	private void quoteMessage(Message message) {
 886		quoteText(MessageUtils.prepareQuote(message));
 887	}
 888
 889	@Override
 890	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
 891		synchronized (this.messageList) {
 892			super.onCreateContextMenu(menu, v, menuInfo);
 893			AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
 894			this.selectedMessage = this.messageList.get(acmi.position);
 895			populateContextMenu(menu);
 896		}
 897	}
 898
 899	private void populateContextMenu(ContextMenu menu) {
 900		final Message m = this.selectedMessage;
 901		final Transferable t = m.getTransferable();
 902		Message relevantForCorrection = m;
 903		while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
 904			relevantForCorrection = relevantForCorrection.next();
 905		}
 906		if (m.getType() != Message.TYPE_STATUS) {
 907			final boolean treatAsFile = m.getType() != Message.TYPE_TEXT
 908					&& m.getType() != Message.TYPE_PRIVATE
 909					&& t == null;
 910			final boolean encrypted = m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
 911					|| m.getEncryption() == Message.ENCRYPTION_PGP;
 912			activity.getMenuInflater().inflate(R.menu.message_context, menu);
 913			menu.setHeaderTitle(R.string.message_options);
 914			MenuItem copyMessage = menu.findItem(R.id.copy_message);
 915			MenuItem quoteMessage = menu.findItem(R.id.quote_message);
 916			MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
 917			MenuItem correctMessage = menu.findItem(R.id.correct_message);
 918			MenuItem shareWith = menu.findItem(R.id.share_with);
 919			MenuItem sendAgain = menu.findItem(R.id.send_again);
 920			MenuItem copyUrl = menu.findItem(R.id.copy_url);
 921			MenuItem downloadFile = menu.findItem(R.id.download_file);
 922			MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
 923			MenuItem deleteFile = menu.findItem(R.id.delete_file);
 924			MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
 925			if (!treatAsFile && !encrypted && !m.isGeoUri() && !m.treatAsDownloadable()) {
 926				copyMessage.setVisible(true);
 927				quoteMessage.setVisible(MessageUtils.prepareQuote(m).length() > 0);
 928			}
 929			if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
 930				retryDecryption.setVisible(true);
 931			}
 932			if (relevantForCorrection.getType() == Message.TYPE_TEXT
 933					&& relevantForCorrection.isLastCorrectableMessage()
 934					&& (m.getConversation().getMucOptions().nonanonymous() || m.getConversation().getMode() == Conversation.MODE_SINGLE)) {
 935				correctMessage.setVisible(true);
 936			}
 937			if (treatAsFile || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) {
 938				shareWith.setVisible(true);
 939			}
 940			if (m.getStatus() == Message.STATUS_SEND_FAILED) {
 941				sendAgain.setVisible(true);
 942			}
 943			if (m.hasFileOnRemoteHost()
 944					|| m.isGeoUri()
 945					|| m.treatAsDownloadable()
 946					|| (t != null && t instanceof HttpDownloadConnection)) {
 947				copyUrl.setVisible(true);
 948			}
 949			if ((m.isFileOrImage() && t instanceof TransferablePlaceholder && m.hasFileOnRemoteHost())) {
 950				downloadFile.setVisible(true);
 951				downloadFile.setTitle(activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, m)));
 952			}
 953			boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
 954					|| m.getStatus() == Message.STATUS_UNSEND
 955					|| m.getStatus() == Message.STATUS_OFFERED;
 956			if ((t != null && !(t instanceof TransferablePlaceholder)) || waitingOfferedSending && m.needsUploading()) {
 957				cancelTransmission.setVisible(true);
 958			}
 959			if (treatAsFile) {
 960				String path = m.getRelativeFilePath();
 961				if (path == null || !path.startsWith("/")) {
 962					deleteFile.setVisible(true);
 963					deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
 964				}
 965			}
 966			if (m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null) {
 967				showErrorMessage.setVisible(true);
 968			}
 969		}
 970	}
 971
 972	@Override
 973	public boolean onContextItemSelected(MenuItem item) {
 974		switch (item.getItemId()) {
 975			case R.id.share_with:
 976				shareWith(selectedMessage);
 977				return true;
 978			case R.id.correct_message:
 979				correctMessage(selectedMessage);
 980				return true;
 981			case R.id.copy_message:
 982				copyMessage(selectedMessage);
 983				return true;
 984			case R.id.quote_message:
 985				quoteMessage(selectedMessage);
 986				return true;
 987			case R.id.send_again:
 988				resendMessage(selectedMessage);
 989				return true;
 990			case R.id.copy_url:
 991				copyUrl(selectedMessage);
 992				return true;
 993			case R.id.download_file:
 994				downloadFile(selectedMessage);
 995				return true;
 996			case R.id.cancel_transmission:
 997				cancelTransmission(selectedMessage);
 998				return true;
 999			case R.id.retry_decryption:
1000				retryDecryption(selectedMessage);
1001				return true;
1002			case R.id.delete_file:
1003				deleteFile(selectedMessage);
1004				return true;
1005			case R.id.show_error_message:
1006				showErrorMessage(selectedMessage);
1007				return true;
1008			default:
1009				return super.onContextItemSelected(item);
1010		}
1011	}
1012
1013	@Override
1014	public boolean onOptionsItemSelected(final MenuItem item) {
1015		if (conversation == null) {
1016			return super.onOptionsItemSelected(item);
1017		}
1018		switch (item.getItemId()) {
1019			case R.id.encryption_choice_axolotl:
1020			case R.id.encryption_choice_pgp:
1021			case R.id.encryption_choice_none:
1022				handleEncryptionSelection(item);
1023				break;
1024			case R.id.attach_choose_picture:
1025			case R.id.attach_take_picture:
1026			case R.id.attach_record_video:
1027			case R.id.attach_choose_file:
1028			case R.id.attach_record_voice:
1029			case R.id.attach_location:
1030				handleAttachmentSelection(item);
1031				break;
1032			case R.id.action_archive:
1033				activity.xmppConnectionService.archiveConversation(conversation);
1034				activity.onConversationArchived(conversation);
1035				break;
1036			case R.id.action_contact_details:
1037				activity.switchToContactDetails(conversation.getContact());
1038				break;
1039			case R.id.action_muc_details:
1040				Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
1041				intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
1042				intent.putExtra("uuid", conversation.getUuid());
1043				startActivity(intent);
1044				break;
1045			case R.id.action_invite:
1046				activity.inviteToConversation(conversation);
1047				break;
1048			case R.id.action_clear_history:
1049				clearHistoryDialog(conversation);
1050				break;
1051			case R.id.action_mute:
1052				muteConversationDialog(conversation);
1053				break;
1054			case R.id.action_unmute:
1055				unmuteConversation(conversation);
1056				break;
1057			case R.id.action_block:
1058			case R.id.action_unblock:
1059				final Activity activity = getActivity();
1060				if (activity instanceof XmppActivity) {
1061					BlockContactDialog.show((XmppActivity) activity, conversation);
1062				}
1063				break;
1064			default:
1065				break;
1066		}
1067		return super.onOptionsItemSelected(item);
1068	}
1069
1070	private void handleAttachmentSelection(MenuItem item) {
1071		switch (item.getItemId()) {
1072			case R.id.attach_choose_picture:
1073				attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1074				break;
1075			case R.id.attach_take_picture:
1076				attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1077				break;
1078			case R.id.attach_record_video:
1079				attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1080				break;
1081			case R.id.attach_choose_file:
1082				attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1083				break;
1084			case R.id.attach_record_voice:
1085				attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1086				break;
1087			case R.id.attach_location:
1088				attachFile(ATTACHMENT_CHOICE_LOCATION);
1089				break;
1090		}
1091	}
1092
1093	private void handleEncryptionSelection(MenuItem item) {
1094		if (conversation == null) {
1095			return;
1096		}
1097		switch (item.getItemId()) {
1098			case R.id.encryption_choice_none:
1099				conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1100				item.setChecked(true);
1101				break;
1102			case R.id.encryption_choice_pgp:
1103				if (activity.hasPgp()) {
1104					if (conversation.getAccount().getPgpSignature() != null) {
1105						conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1106						item.setChecked(true);
1107					} else {
1108						activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
1109					}
1110				} else {
1111					activity.showInstallPgpDialog();
1112				}
1113				break;
1114			case R.id.encryption_choice_axolotl:
1115				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
1116						+ "Enabled axolotl for Contact " + conversation.getContact().getJid());
1117				conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1118				item.setChecked(true);
1119				break;
1120			default:
1121				conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1122				break;
1123		}
1124		activity.xmppConnectionService.updateConversation(conversation);
1125		updateChatMsgHint();
1126		getActivity().invalidateOptionsMenu();
1127		activity.refreshUi();
1128	}
1129
1130	public void attachFile(final int attachmentChoice) {
1131		if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1132			if (!Config.ONLY_INTERNAL_STORAGE && !activity.hasStoragePermission(attachmentChoice)) {
1133				return;
1134			}
1135		}
1136		try {
1137			activity.getPreferences().edit()
1138					.putString(RECENTLY_USED_QUICK_ACTION, SendButtonAction.of(attachmentChoice).toString())
1139					.apply();
1140		} catch (IllegalArgumentException e) {
1141			//just do not save
1142		}
1143		final int encryption = conversation.getNextEncryption();
1144		final int mode = conversation.getMode();
1145		if (encryption == Message.ENCRYPTION_PGP) {
1146			if (activity.hasPgp()) {
1147				if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
1148					activity.xmppConnectionService.getPgpEngine().hasKey(
1149							conversation.getContact(),
1150							new UiCallback<Contact>() {
1151
1152								@Override
1153								public void userInputRequried(PendingIntent pi, Contact contact) {
1154									startPendingIntent(pi, attachmentChoice);
1155								}
1156
1157								@Override
1158								public void success(Contact contact) {
1159									selectPresenceToAttachFile(attachmentChoice);
1160								}
1161
1162								@Override
1163								public void error(int error, Contact contact) {
1164									activity.replaceToast(getString(error));
1165								}
1166							});
1167				} else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
1168					if (!conversation.getMucOptions().everybodyHasKeys()) {
1169						Toast warning = Toast.makeText(getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
1170						warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1171						warning.show();
1172					}
1173					selectPresenceToAttachFile(attachmentChoice);
1174				} else {
1175					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
1176							.findFragmentByTag("conversation");
1177					if (fragment != null) {
1178						fragment.showNoPGPKeyDialog(false, (dialog, which) -> {
1179							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1180							activity.xmppConnectionService.updateConversation(conversation);
1181							selectPresenceToAttachFile(attachmentChoice);
1182						});
1183					}
1184				}
1185			} else {
1186				activity.showInstallPgpDialog();
1187			}
1188		} else {
1189			if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
1190				selectPresenceToAttachFile(attachmentChoice);
1191			}
1192		}
1193	}
1194
1195	@Override
1196	public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
1197		if (grantResults.length > 0)
1198			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
1199				if (requestCode == REQUEST_START_DOWNLOAD) {
1200					if (this.mPendingDownloadableMessage != null) {
1201						startDownloadable(this.mPendingDownloadableMessage);
1202					}
1203				} else if (requestCode == REQUEST_ADD_EDITOR_CONTENT) {
1204					if (this.mPendingEditorContent != null) {
1205						attachImageToConversation(this.mPendingEditorContent);
1206					}
1207				} else {
1208					attachFile(requestCode);
1209				}
1210			} else {
1211				Toast.makeText(getActivity(), R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
1212			}
1213	}
1214
1215	public void startDownloadable(Message message) {
1216		if (!Config.ONLY_INTERNAL_STORAGE && !activity.hasStoragePermission(REQUEST_START_DOWNLOAD)) {
1217			this.mPendingDownloadableMessage = message;
1218			return;
1219		}
1220		Transferable transferable = message.getTransferable();
1221		if (transferable != null) {
1222			if (!transferable.start()) {
1223				Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1224			}
1225		} else if (message.treatAsDownloadable()) {
1226			activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
1227		}
1228	}
1229
1230	@SuppressLint("InflateParams")
1231	protected void clearHistoryDialog(final Conversation conversation) {
1232		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1233		builder.setTitle(getString(R.string.clear_conversation_history));
1234		final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
1235		final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox);
1236		builder.setView(dialogView);
1237		builder.setNegativeButton(getString(R.string.cancel), null);
1238		builder.setPositiveButton(getString(R.string.delete_messages), (dialog, which) -> {
1239			this.activity.xmppConnectionService.clearConversationHistory(conversation);
1240			if (endConversationCheckBox.isChecked()) {
1241				this.activity.xmppConnectionService.archiveConversation(conversation);
1242				this.activity.onConversationArchived(conversation);
1243			} else {
1244				activity.onConversationsListItemUpdated();
1245				refresh();
1246			}
1247		});
1248		builder.create().show();
1249	}
1250
1251	protected void muteConversationDialog(final Conversation conversation) {
1252		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1253		builder.setTitle(R.string.disable_notifications);
1254		final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
1255		builder.setItems(R.array.mute_options_descriptions, (dialog, which) -> {
1256			final long till;
1257			if (durations[which] == -1) {
1258				till = Long.MAX_VALUE;
1259			} else {
1260				till = System.currentTimeMillis() + (durations[which] * 1000);
1261			}
1262			conversation.setMutedTill(till);
1263			activity.xmppConnectionService.updateConversation(conversation);
1264			activity.onConversationsListItemUpdated();
1265			refresh();
1266			getActivity().invalidateOptionsMenu();
1267		});
1268		builder.create().show();
1269	}
1270
1271	public void unmuteConversation(final Conversation conversation) {
1272		conversation.setMutedTill(0);
1273		this.activity.xmppConnectionService.updateConversation(conversation);
1274		this.activity.onConversationsListItemUpdated();
1275		refresh();
1276		getActivity().invalidateOptionsMenu();
1277	}
1278
1279	protected void selectPresenceToAttachFile(final int attachmentChoice) {
1280		final Account account = conversation.getAccount();
1281		final PresenceSelector.OnPresenceSelected callback = () -> {
1282			Intent intent = new Intent();
1283			boolean chooser = false;
1284			String fallbackPackageId = null;
1285			switch (attachmentChoice) {
1286				case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
1287					intent.setAction(Intent.ACTION_GET_CONTENT);
1288					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1289						intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1290					}
1291					intent.setType("image/*");
1292					chooser = true;
1293					break;
1294				case ATTACHMENT_CHOICE_RECORD_VIDEO:
1295					intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
1296					break;
1297				case ATTACHMENT_CHOICE_TAKE_PHOTO:
1298					Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
1299					//TODO save photo uri
1300					//mPendingImageUris.clear();
1301					//mPendingImageUris.add(uri);
1302					intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
1303					intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
1304					intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1305					intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
1306					break;
1307				case ATTACHMENT_CHOICE_CHOOSE_FILE:
1308					chooser = true;
1309					intent.setType("*/*");
1310					intent.addCategory(Intent.CATEGORY_OPENABLE);
1311					intent.setAction(Intent.ACTION_GET_CONTENT);
1312					break;
1313				case ATTACHMENT_CHOICE_RECORD_VOICE:
1314					intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
1315					fallbackPackageId = "eu.siacs.conversations.voicerecorder";
1316					break;
1317				case ATTACHMENT_CHOICE_LOCATION:
1318					intent.setAction("eu.siacs.conversations.location.request");
1319					fallbackPackageId = "eu.siacs.conversations.sharelocation";
1320					break;
1321			}
1322			if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
1323				if (chooser) {
1324					startActivityForResult(
1325							Intent.createChooser(intent, getString(R.string.perform_action_with)),
1326							attachmentChoice);
1327				} else {
1328					startActivityForResult(intent, attachmentChoice);
1329				}
1330			} else if (fallbackPackageId != null) {
1331				startActivity(getInstallApkIntent(fallbackPackageId));
1332			}
1333		};
1334		if (account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) {
1335			conversation.setNextCounterpart(null);
1336			callback.onPresenceSelected();
1337		} else {
1338			activity.selectPresence(conversation, callback);
1339		}
1340	}
1341
1342	private Intent getInstallApkIntent(final String packageId) {
1343		Intent intent = new Intent(Intent.ACTION_VIEW);
1344		intent.setData(Uri.parse("market://details?id=" + packageId));
1345		if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
1346			return intent;
1347		} else {
1348			intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
1349			return intent;
1350		}
1351	}
1352
1353	@Override
1354	public void onResume() {
1355		new Handler().post(() -> {
1356			final Activity activity = getActivity();
1357			if (activity == null) {
1358				return;
1359			}
1360			final PackageManager packageManager = activity.getPackageManager();
1361			ConversationMenuConfigurator.updateAttachmentAvailability(packageManager);
1362			getActivity().invalidateOptionsMenu();
1363		});
1364		super.onResume();
1365	}
1366
1367	private void showErrorMessage(final Message message) {
1368		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1369		builder.setTitle(R.string.error_message);
1370		builder.setMessage(message.getErrorMessage());
1371		builder.setPositiveButton(R.string.confirm, null);
1372		builder.create().show();
1373	}
1374
1375	private void shareWith(Message message) {
1376		Intent shareIntent = new Intent();
1377		shareIntent.setAction(Intent.ACTION_SEND);
1378		if (message.isGeoUri()) {
1379			shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
1380			shareIntent.setType("text/plain");
1381		} else if (!message.isFileOrImage()) {
1382			shareIntent.putExtra(Intent.EXTRA_TEXT, message.getMergedBody().toString());
1383			shareIntent.setType("text/plain");
1384		} else {
1385			final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1386			try {
1387				shareIntent.putExtra(Intent.EXTRA_STREAM, FileBackend.getUriForFile(getActivity(), file));
1388			} catch (SecurityException e) {
1389				Toast.makeText(getActivity(), activity.getString(R.string.no_permission_to_access_x, file.getAbsolutePath()), Toast.LENGTH_SHORT).show();
1390				return;
1391			}
1392			shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1393			String mime = message.getMimeType();
1394			if (mime == null) {
1395				mime = "*/*";
1396			}
1397			shareIntent.setType(mime);
1398		}
1399		try {
1400			startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
1401		} catch (ActivityNotFoundException e) {
1402			//This should happen only on faulty androids because normally chooser is always available
1403			Toast.makeText(getActivity(), R.string.no_application_found_to_open_file, Toast.LENGTH_SHORT).show();
1404		}
1405	}
1406
1407	private void copyMessage(Message message) {
1408		if (activity.copyTextToClipboard(message.getMergedBody().toString(), R.string.message)) {
1409			Toast.makeText(getActivity(), R.string.message_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1410		}
1411	}
1412
1413	private void deleteFile(Message message) {
1414		if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
1415			message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1416			activity.onConversationsListItemUpdated();
1417			refresh();
1418		}
1419	}
1420
1421	private void resendMessage(final Message message) {
1422		if (message.isFileOrImage()) {
1423			DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1424			if (file.exists()) {
1425				final Conversation conversation = message.getConversation();
1426				final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
1427				if (!message.hasFileOnRemoteHost()
1428						&& xmppConnection != null
1429						&& !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
1430					activity.selectPresence(conversation, () -> {
1431						message.setCounterpart(conversation.getNextCounterpart());
1432						activity.xmppConnectionService.resendFailedMessages(message);
1433					});
1434					return;
1435				}
1436			} else {
1437				Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
1438				message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1439				activity.onConversationsListItemUpdated();
1440				refresh();
1441				return;
1442			}
1443		}
1444		activity.xmppConnectionService.resendFailedMessages(message);
1445	}
1446
1447	private void copyUrl(Message message) {
1448		final String url;
1449		final int resId;
1450		if (message.isGeoUri()) {
1451			resId = R.string.location;
1452			url = message.getBody();
1453		} else if (message.hasFileOnRemoteHost()) {
1454			resId = R.string.file_url;
1455			url = message.getFileParams().url.toString();
1456		} else {
1457			url = message.getBody().trim();
1458			resId = R.string.file_url;
1459		}
1460		if (activity.copyTextToClipboard(url, resId)) {
1461			Toast.makeText(getActivity(), R.string.url_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1462		}
1463	}
1464
1465	private void downloadFile(Message message) {
1466		activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
1467	}
1468
1469	public static void downloadFile(Activity activity, Message message) {
1470		Fragment fragment = activity.getFragmentManager().findFragmentById(R.id.main_fragment);
1471		if (fragment != null && fragment instanceof ConversationFragment) {
1472			((ConversationFragment) fragment).downloadFile(message);
1473			return;
1474		}
1475		fragment = activity.getFragmentManager().findFragmentById(R.id.secondary_fragment);
1476		if (fragment != null && fragment instanceof ConversationFragment) {
1477			((ConversationFragment) fragment).downloadFile(message);
1478		}
1479	}
1480
1481	private void cancelTransmission(Message message) {
1482		Transferable transferable = message.getTransferable();
1483		if (transferable != null) {
1484			transferable.cancel();
1485		} else if (message.getStatus() != Message.STATUS_RECEIVED) {
1486			activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1487		}
1488	}
1489
1490	private void retryDecryption(Message message) {
1491		message.setEncryption(Message.ENCRYPTION_PGP);
1492		activity.onConversationsListItemUpdated();
1493		refresh();
1494		conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
1495	}
1496
1497	private void privateMessageWith(final Jid counterpart) {
1498		if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1499			activity.xmppConnectionService.sendChatState(conversation);
1500		}
1501		this.binding.textinput.setText("");
1502		this.conversation.setNextCounterpart(counterpart);
1503		updateChatMsgHint();
1504		updateSendButton();
1505		updateEditablity();
1506	}
1507
1508	private void correctMessage(Message message) {
1509		while (message.mergeable(message.next())) {
1510			message = message.next();
1511		}
1512		this.conversation.setCorrectingMessage(message);
1513		final Editable editable = binding.textinput.getText();
1514		this.conversation.setDraftMessage(editable.toString());
1515		this.binding.textinput.setText("");
1516		this.binding.textinput.append(message.getBody());
1517
1518	}
1519
1520	private void highlightInConference(String nick) {
1521		final Editable editable = this.binding.textinput.getText();
1522		String oldString = editable.toString().trim();
1523		final int pos = this.binding.textinput.getSelectionStart();
1524		if (oldString.isEmpty() || pos == 0) {
1525			editable.insert(0, nick + ": ");
1526		} else {
1527			final char before = editable.charAt(pos - 1);
1528			final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
1529			if (before == '\n') {
1530				editable.insert(pos, nick + ": ");
1531			} else {
1532				if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
1533					if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
1534						editable.insert(pos - 2, ", " + nick);
1535						return;
1536					}
1537				}
1538				editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
1539				if (Character.isWhitespace(after)) {
1540					this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
1541				}
1542			}
1543		}
1544	}
1545
1546
1547	@Override
1548	public void onSaveInstanceState(Bundle outState) {
1549		super.onSaveInstanceState(outState);
1550		if (conversation != null) {
1551			outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
1552		}
1553	}
1554
1555	@Override
1556	public void onActivityCreated(Bundle savedInstanceState) {
1557		super.onActivityCreated(savedInstanceState);
1558		if (savedInstanceState == null) {
1559			return;
1560		}
1561		String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
1562		if (uuid != null) {
1563			this.pendingConversationsUuid.push(uuid);
1564		}
1565	}
1566
1567	@Override
1568	public void onStart() {
1569		super.onStart();
1570		reInit(conversation);
1571		final Bundle extras = pendingExtras.pop();
1572		if (extras != null) {
1573			processExtras(extras);
1574		}
1575	}
1576
1577	@Override
1578	public void onStop() {
1579		super.onStop();
1580		final Activity activity = getActivity();
1581		if (activity == null || !activity.isChangingConfigurations()) {
1582			messageListAdapter.stopAudioPlayer();
1583		}
1584		if (this.conversation != null) {
1585			final String msg = this.binding.textinput.getText().toString();
1586			if (this.conversation.setNextMessage(msg)) {
1587				this.activity.xmppConnectionService.updateConversation(this.conversation);
1588			}
1589			updateChatState(this.conversation, msg);
1590			this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
1591		}
1592	}
1593
1594	private void updateChatState(final Conversation conversation, final String msg) {
1595		ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
1596		Account.State status = conversation.getAccount().getStatus();
1597		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
1598			activity.xmppConnectionService.sendChatState(conversation);
1599		}
1600	}
1601
1602	public void reInit(Conversation conversation, Bundle extras) {
1603		this.reInit(conversation);
1604		if (extras != null) {
1605			if (activity != null) {
1606				processExtras(extras);
1607			} else {
1608				pendingExtras.push(extras);
1609			}
1610		}
1611	}
1612
1613	private void reInit(Conversation conversation) {
1614		reInit(conversation, false);
1615	}
1616
1617	private void reInit(Conversation conversation, boolean restore) {
1618		if (conversation == null) {
1619			return;
1620		}
1621		if (this.activity == null) {
1622			this.conversation = conversation;
1623			return;
1624		}
1625		Log.d(Config.LOGTAG, "reInit(restore="+Boolean.toString(restore)+")");
1626		setupIme();
1627		if (this.conversation != null) {
1628			final String msg = this.binding.textinput.getText().toString();
1629			if (this.conversation.setNextMessage(msg)) {
1630				activity.xmppConnectionService.updateConversation(conversation);
1631			}
1632			if (this.conversation != conversation && !restore) {
1633				updateChatState(this.conversation, msg);
1634				messageListAdapter.stopAudioPlayer();
1635			}
1636			if (!restore) {
1637				this.conversation.trim();
1638			}
1639
1640		}
1641
1642		if (activity != null) {
1643			this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
1644		}
1645
1646		this.conversation = conversation;
1647		this.binding.textinput.setKeyboardListener(null);
1648		this.binding.textinput.setText("");
1649		this.binding.textinput.append(this.conversation.getNextMessage());
1650		this.binding.textinput.setKeyboardListener(this);
1651		messageListAdapter.updatePreferences();
1652		this.binding.messagesView.setAdapter(messageListAdapter);
1653		refresh(false);
1654		this.conversation.messagesLoaded.set(true);
1655		final boolean isAtBottom;
1656		synchronized (this.messageList) {
1657			final Message first = conversation.getFirstUnreadMessage();
1658			final int bottom = Math.max(0, this.messageList.size() - 1);
1659			final int pos;
1660			if (first == null) {
1661				pos = bottom;
1662			} else {
1663				int i = getIndexOf(first.getUuid(), this.messageList);
1664				pos = i < 0 ? bottom : i;
1665			}
1666			this.binding.messagesView.setSelection(pos);
1667			isAtBottom = pos == bottom;
1668		}
1669		if (activity != null) {
1670			activity.onConversationRead(this.conversation);
1671			//TODO if we only do this when this fragment is running on main it won't *bing* in tablet layout which might be unnecessary since we can *see* it
1672			activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
1673		}
1674	}
1675
1676	private void processExtras(Bundle extras) {
1677		final String downloadUuid = extras.getString(ConversationActivity.EXTRA_DOWNLOAD_UUID);
1678		final String text = extras.getString(ConversationActivity.EXTRA_TEXT);
1679		final String nick = extras.getString(ConversationActivity.EXTRA_NICK);
1680		final boolean pm = extras.getBoolean(ConversationActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
1681		if (nick != null) {
1682			if (pm) {
1683				Jid jid = conversation.getJid();
1684				try {
1685					Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1686					privateMessageWith(next);
1687				} catch (final InvalidJidException ignored) {
1688					//do nothing
1689				}
1690			} else {
1691				highlightInConference(nick);
1692			}
1693		} else {
1694			appendText(text);
1695		}
1696		final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
1697		if (message != null) {
1698			startDownloadable(message);
1699		}
1700	}
1701
1702	private boolean showBlockSubmenu(View view) {
1703		final Jid jid = conversation.getJid();
1704		if (jid.isDomainJid()) {
1705			BlockContactDialog.show(activity, conversation);
1706		} else {
1707			PopupMenu popupMenu = new PopupMenu(getActivity(), view);
1708			popupMenu.inflate(R.menu.block);
1709			popupMenu.setOnMenuItemClickListener(menuItem -> {
1710				Blockable blockable;
1711				switch (menuItem.getItemId()) {
1712					case R.id.block_domain:
1713						blockable = conversation.getAccount().getRoster().getContact(jid.toDomainJid());
1714						break;
1715					default:
1716						blockable = conversation;
1717				}
1718				BlockContactDialog.show(activity, blockable);
1719				return true;
1720			});
1721			popupMenu.show();
1722		}
1723		return true;
1724	}
1725
1726	private void updateSnackBar(final Conversation conversation) {
1727		final Account account = conversation.getAccount();
1728		final XmppConnection connection = account.getXmppConnection();
1729		final int mode = conversation.getMode();
1730		final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
1731		if (account.getStatus() == Account.State.DISABLED) {
1732			showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
1733		} else if (conversation.isBlocked()) {
1734			showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
1735		} else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1736			showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
1737		} else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1738			showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
1739		} else if (mode == Conversation.MODE_MULTI
1740				&& !conversation.getMucOptions().online()
1741				&& account.getStatus() == Account.State.ONLINE) {
1742			switch (conversation.getMucOptions().getError()) {
1743				case NICK_IN_USE:
1744					showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
1745					break;
1746				case NO_RESPONSE:
1747					showSnackbar(R.string.joining_conference, 0, null);
1748					break;
1749				case SERVER_NOT_FOUND:
1750					if (conversation.receivedMessagesCount() > 0) {
1751						showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
1752					} else {
1753						showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
1754					}
1755					break;
1756				case PASSWORD_REQUIRED:
1757					showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
1758					break;
1759				case BANNED:
1760					showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
1761					break;
1762				case MEMBERS_ONLY:
1763					showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
1764					break;
1765				case KICKED:
1766					showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
1767					break;
1768				case UNKNOWN:
1769					showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
1770					break;
1771				case INVALID_NICK:
1772					showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
1773				case SHUTDOWN:
1774					showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
1775					break;
1776				default:
1777					hideSnackbar();
1778					break;
1779			}
1780		} else if (account.hasPendingPgpIntent(conversation)) {
1781			showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
1782		} else if (connection != null
1783				&& connection.getFeatures().blocking()
1784				&& conversation.countMessages() != 0
1785				&& !conversation.isBlocked()
1786				&& conversation.isWithStranger()) {
1787			showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
1788		} else {
1789			hideSnackbar();
1790		}
1791	}
1792
1793	@Override
1794	public void refresh() {
1795		this.refresh(true);
1796	}
1797
1798
1799	private void refresh(boolean notifyConversationRead) {
1800		synchronized (this.messageList) {
1801			if (this.conversation != null) {
1802				conversation.populateWithMessages(this.messageList);
1803				updateSnackBar(conversation);
1804				updateStatusMessages();
1805				this.messageListAdapter.notifyDataSetChanged();
1806				updateChatMsgHint();
1807				if (notifyConversationRead && activity != null) {
1808					activity.onConversationRead(this.conversation);
1809				}
1810				updateSendButton();
1811				updateEditablity();
1812			}
1813		}
1814	}
1815
1816	protected void messageSent() {
1817		mSendingPgpMessage.set(false);
1818		this.binding.textinput.setText("");
1819		if (conversation.setCorrectingMessage(null)) {
1820			this.binding.textinput.append(conversation.getDraftMessage());
1821			conversation.setDraftMessage(null);
1822		}
1823		if (conversation.setNextMessage(this.binding.textinput.getText().toString())) {
1824			activity.xmppConnectionService.updateConversation(conversation);
1825		}
1826		updateChatMsgHint();
1827		new Handler().post(() -> {
1828			int size = messageList.size();
1829			this.binding.messagesView.setSelection(size - 1);
1830		});
1831	}
1832
1833	public void setFocusOnInputField() {
1834		this.binding.textinput.requestFocus();
1835	}
1836
1837	public void doneSendingPgpMessage() {
1838		mSendingPgpMessage.set(false);
1839	}
1840
1841	public long getMaxHttpUploadSize(Conversation conversation) {
1842		final XmppConnection connection = conversation.getAccount().getXmppConnection();
1843		return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
1844	}
1845
1846	private void updateEditablity() {
1847		boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
1848		this.binding.textinput.setFocusable(canWrite);
1849		this.binding.textinput.setFocusableInTouchMode(canWrite);
1850		this.binding.textSendButton.setEnabled(canWrite);
1851		this.binding.textinput.setCursorVisible(canWrite);
1852	}
1853
1854	public void updateSendButton() {
1855		boolean useSendButtonToIndicateStatus = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
1856		final Conversation c = this.conversation;
1857		final Presence.Status status;
1858		final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
1859		final SendButtonAction action = SendButtonTool.getAction(getActivity(), c, text);
1860		if (useSendButtonToIndicateStatus && c.getAccount().getStatus() == Account.State.ONLINE) {
1861			if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
1862				status = Presence.Status.OFFLINE;
1863			} else if (c.getMode() == Conversation.MODE_SINGLE) {
1864				status = c.getContact().getShownStatus();
1865			} else {
1866				status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
1867			}
1868		} else {
1869			status = Presence.Status.OFFLINE;
1870		}
1871		this.binding.textSendButton.setTag(action);
1872		this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(getActivity(), action, status));
1873	}
1874
1875	protected void updateDateSeparators() {
1876		synchronized (this.messageList) {
1877			for (int i = 0; i < this.messageList.size(); ++i) {
1878				final Message current = this.messageList.get(i);
1879				if (i == 0 || !UIHelper.sameDay(this.messageList.get(i - 1).getTimeSent(), current.getTimeSent())) {
1880					this.messageList.add(i, Message.createDateSeparator(current));
1881					i++;
1882				}
1883			}
1884		}
1885	}
1886
1887	protected void updateStatusMessages() {
1888		updateDateSeparators();
1889		synchronized (this.messageList) {
1890			if (showLoadMoreMessages(conversation)) {
1891				this.messageList.add(0, Message.createLoadMoreMessage(conversation));
1892			}
1893			if (conversation.getMode() == Conversation.MODE_SINGLE) {
1894				ChatState state = conversation.getIncomingChatState();
1895				if (state == ChatState.COMPOSING) {
1896					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
1897				} else if (state == ChatState.PAUSED) {
1898					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
1899				} else {
1900					for (int i = this.messageList.size() - 1; i >= 0; --i) {
1901						if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
1902							return;
1903						} else {
1904							if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
1905								this.messageList.add(i + 1,
1906										Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
1907								return;
1908							}
1909						}
1910					}
1911				}
1912			} else {
1913				final MucOptions mucOptions = conversation.getMucOptions();
1914				final List<MucOptions.User> allUsers = mucOptions.getUsers();
1915				final Set<ReadByMarker> addedMarkers = new HashSet<>();
1916				ChatState state = ChatState.COMPOSING;
1917				List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
1918				if (users.size() == 0) {
1919					state = ChatState.PAUSED;
1920					users = conversation.getMucOptions().getUsersWithChatState(state, 5);
1921				}
1922				if (mucOptions.isPrivateAndNonAnonymous()) {
1923					for (int i = this.messageList.size() - 1; i >= 0; --i) {
1924						final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
1925						final List<MucOptions.User> shownMarkers = new ArrayList<>();
1926						for (ReadByMarker marker : markersForMessage) {
1927							if (!ReadByMarker.contains(marker, addedMarkers)) {
1928								addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
1929								MucOptions.User user = mucOptions.findUser(marker);
1930								if (user != null && !users.contains(user)) {
1931									shownMarkers.add(user);
1932								}
1933							}
1934						}
1935						final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
1936						final Message statusMessage;
1937						final int size = shownMarkers.size();
1938						if (size > 1) {
1939							final String body;
1940							if (size <= 4) {
1941								body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
1942							} else {
1943								body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
1944							}
1945							statusMessage = Message.createStatusMessage(conversation, body);
1946							statusMessage.setCounterparts(shownMarkers);
1947						} else if (size == 1) {
1948							statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
1949							statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
1950							statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
1951						} else {
1952							statusMessage = null;
1953						}
1954						if (statusMessage != null) {
1955							this.messageList.add(i + 1, statusMessage);
1956						}
1957						addedMarkers.add(markerForSender);
1958						if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
1959							break;
1960						}
1961					}
1962				}
1963				if (users.size() > 0) {
1964					Message statusMessage;
1965					if (users.size() == 1) {
1966						MucOptions.User user = users.get(0);
1967						int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
1968						statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
1969						statusMessage.setTrueCounterpart(user.getRealJid());
1970						statusMessage.setCounterpart(user.getFullJid());
1971					} else {
1972						int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
1973						statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
1974						statusMessage.setCounterparts(users);
1975					}
1976					this.messageList.add(statusMessage);
1977				}
1978
1979			}
1980		}
1981	}
1982
1983	public void stopScrolling() {
1984		long now = SystemClock.uptimeMillis();
1985		MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
1986		binding.messagesView.dispatchTouchEvent(cancel);
1987	}
1988
1989	private boolean showLoadMoreMessages(final Conversation c) {
1990		final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
1991		final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
1992		return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
1993	}
1994
1995	private boolean hasMamSupport(final Conversation c) {
1996		if (c.getMode() == Conversation.MODE_SINGLE) {
1997			final XmppConnection connection = c.getAccount().getXmppConnection();
1998			return connection != null && connection.getFeatures().mam();
1999		} else {
2000			return c.getMucOptions().mamSupport();
2001		}
2002	}
2003
2004	protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
2005		showSnackbar(message, action, clickListener, null);
2006	}
2007
2008	protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
2009		this.binding.snackbar.setVisibility(View.VISIBLE);
2010		this.binding.snackbar.setOnClickListener(null);
2011		this.binding.snackbarMessage.setText(message);
2012		this.binding.snackbarMessage.setOnClickListener(null);
2013		this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
2014		if (action != 0) {
2015			this.binding.snackbarAction.setText(action);
2016		}
2017		this.binding.snackbarAction.setOnClickListener(clickListener);
2018		this.binding.snackbarAction.setOnLongClickListener(longClickListener);
2019	}
2020
2021	protected void hideSnackbar() {
2022		this.binding.snackbar.setVisibility(View.GONE);
2023	}
2024
2025	protected void sendPlainTextMessage(Message message) {
2026		activity.xmppConnectionService.sendMessage(message);
2027		messageSent();
2028	}
2029
2030	protected void sendPgpMessage(final Message message) {
2031		final XmppConnectionService xmppService = activity.xmppConnectionService;
2032		final Contact contact = message.getConversation().getContact();
2033		if (!activity.hasPgp()) {
2034			activity.showInstallPgpDialog();
2035			return;
2036		}
2037		if (conversation.getAccount().getPgpSignature() == null) {
2038			activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
2039			return;
2040		}
2041		if (!mSendingPgpMessage.compareAndSet(false, true)) {
2042			Log.d(Config.LOGTAG, "sending pgp message already in progress");
2043		}
2044		if (conversation.getMode() == Conversation.MODE_SINGLE) {
2045			if (contact.getPgpKeyId() != 0) {
2046				xmppService.getPgpEngine().hasKey(contact,
2047						new UiCallback<Contact>() {
2048
2049							@Override
2050							public void userInputRequried(PendingIntent pi, Contact contact) {
2051								startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
2052							}
2053
2054							@Override
2055							public void success(Contact contact) {
2056								encryptTextMessage(message);
2057							}
2058
2059							@Override
2060							public void error(int error, Contact contact) {
2061								activity.runOnUiThread(() -> Toast.makeText(activity,
2062										R.string.unable_to_connect_to_keychain,
2063										Toast.LENGTH_SHORT
2064								).show());
2065								mSendingPgpMessage.set(false);
2066							}
2067						});
2068
2069			} else {
2070				showNoPGPKeyDialog(false, (dialog, which) -> {
2071					conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2072					xmppService.updateConversation(conversation);
2073					message.setEncryption(Message.ENCRYPTION_NONE);
2074					xmppService.sendMessage(message);
2075					messageSent();
2076				});
2077			}
2078		} else {
2079			if (conversation.getMucOptions().pgpKeysInUse()) {
2080				if (!conversation.getMucOptions().everybodyHasKeys()) {
2081					Toast warning = Toast
2082							.makeText(getActivity(),
2083									R.string.missing_public_keys,
2084									Toast.LENGTH_LONG);
2085					warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2086					warning.show();
2087				}
2088				encryptTextMessage(message);
2089			} else {
2090				showNoPGPKeyDialog(true, (dialog, which) -> {
2091					conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2092					message.setEncryption(Message.ENCRYPTION_NONE);
2093					xmppService.updateConversation(conversation);
2094					xmppService.sendMessage(message);
2095					messageSent();
2096				});
2097			}
2098		}
2099	}
2100
2101	public void encryptTextMessage(Message message) {
2102		activity.xmppConnectionService.getPgpEngine().encrypt(message,
2103				new UiCallback<Message>() {
2104
2105					@Override
2106					public void userInputRequried(PendingIntent pi, Message message) {
2107						startPendingIntent(pi, REQUEST_SEND_MESSAGE);
2108					}
2109
2110					@Override
2111					public void success(Message message) {
2112						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
2113						activity.xmppConnectionService.sendMessage(message);
2114						getActivity().runOnUiThread(() -> messageSent());
2115					}
2116
2117					@Override
2118					public void error(final int error, Message message) {
2119						getActivity().runOnUiThread(() -> {
2120							doneSendingPgpMessage();
2121							Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
2122						});
2123
2124					}
2125				});
2126	}
2127
2128	public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
2129		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
2130		builder.setIconAttribute(android.R.attr.alertDialogIcon);
2131		if (plural) {
2132			builder.setTitle(getString(R.string.no_pgp_keys));
2133			builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
2134		} else {
2135			builder.setTitle(getString(R.string.no_pgp_key));
2136			builder.setMessage(getText(R.string.contact_has_no_pgp_key));
2137		}
2138		builder.setNegativeButton(getString(R.string.cancel), null);
2139		builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
2140		builder.create().show();
2141	}
2142
2143	protected void sendAxolotlMessage(final Message message) {
2144		activity.xmppConnectionService.sendMessage(message);
2145		messageSent();
2146	}
2147
2148	public void appendText(String text) {
2149		if (text == null) {
2150			return;
2151		}
2152		String previous = this.binding.textinput.getText().toString();
2153		if (previous.length() != 0 && !previous.endsWith(" ")) {
2154			text = " " + text;
2155		}
2156		this.binding.textinput.append(text);
2157	}
2158
2159	@Override
2160	public boolean onEnterPressed() {
2161		SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
2162		final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
2163		if (enterIsSend) {
2164			sendMessage();
2165			return true;
2166		} else {
2167			return false;
2168		}
2169	}
2170
2171	@Override
2172	public void onTypingStarted() {
2173		Account.State status = conversation.getAccount().getStatus();
2174		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
2175			activity.xmppConnectionService.sendChatState(conversation);
2176		}
2177		updateSendButton();
2178	}
2179
2180	@Override
2181	public void onTypingStopped() {
2182		Account.State status = conversation.getAccount().getStatus();
2183		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
2184			activity.xmppConnectionService.sendChatState(conversation);
2185		}
2186	}
2187
2188	@Override
2189	public void onTextDeleted() {
2190		Account.State status = conversation.getAccount().getStatus();
2191		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
2192			activity.xmppConnectionService.sendChatState(conversation);
2193		}
2194		updateSendButton();
2195	}
2196
2197	@Override
2198	public void onTextChanged() {
2199		if (conversation != null && conversation.getCorrectingMessage() != null) {
2200			updateSendButton();
2201		}
2202	}
2203
2204	@Override
2205	public boolean onTabPressed(boolean repeated) {
2206		if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
2207			return false;
2208		}
2209		if (repeated) {
2210			completionIndex++;
2211		} else {
2212			lastCompletionLength = 0;
2213			completionIndex = 0;
2214			final String content = this.binding.textinput.getText().toString();
2215			lastCompletionCursor = this.binding.textinput.getSelectionEnd();
2216			int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
2217			firstWord = start == 0;
2218			incomplete = content.substring(start, lastCompletionCursor);
2219		}
2220		List<String> completions = new ArrayList<>();
2221		for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
2222			String name = user.getName();
2223			if (name != null && name.startsWith(incomplete)) {
2224				completions.add(name + (firstWord ? ": " : " "));
2225			}
2226		}
2227		Collections.sort(completions);
2228		if (completions.size() > completionIndex) {
2229			String completion = completions.get(completionIndex).substring(incomplete.length());
2230			this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2231			this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
2232			lastCompletionLength = completion.length();
2233		} else {
2234			completionIndex = -1;
2235			this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2236			lastCompletionLength = 0;
2237		}
2238		return true;
2239	}
2240
2241	private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
2242		try {
2243			getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
2244		} catch (final SendIntentException ignored) {
2245		}
2246	}
2247
2248	@Override
2249	public void onBackendConnected() {
2250		Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
2251		String uuid = pendingConversationsUuid.pop();
2252		if (uuid != null) {
2253			Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
2254			if (conversation == null) {
2255				Log.d(Config.LOGTAG, "unable to restore activity");
2256				clearPending();
2257				return;
2258			}
2259			reInit(conversation, true);
2260		}
2261		ActivityResult activityResult = postponedActivityResult.pop();
2262		if (activityResult != null) {
2263			handleActivityResult(activityResult);
2264		}
2265	}
2266
2267	public void clearPending() {
2268		if (postponedActivityResult.pop() != null) {
2269			Log.d(Config.LOGTAG, "cleared pending intent with unhandled result left");
2270		}
2271	}
2272
2273	public static Conversation getConversation(Activity activity) {
2274		return getConversation(activity, R.id.secondary_fragment);
2275	}
2276
2277	private static Conversation getConversation(Activity activity, @IdRes int res) {
2278		final Fragment fragment = activity.getFragmentManager().findFragmentById(res);
2279		if (fragment != null && fragment instanceof ConversationFragment) {
2280			return ((ConversationFragment) fragment).getConversation();
2281		} else {
2282			return null;
2283		}
2284	}
2285
2286	public static Conversation getConversationReliable(Activity activity) {
2287		final Conversation conversation = getConversation(activity, R.id.secondary_fragment);
2288		if (conversation != null) {
2289			return conversation;
2290		}
2291		return getConversation(activity, R.id.main_fragment);
2292	}
2293
2294	public Conversation getConversation() {
2295		return conversation;
2296	}
2297}