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