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 final AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
460 if (axolotlService == null || !axolotlService.isConversationAxolotlCapable(conversation)) {
461 axolotl.setEnabled(false);
462 }
463 switch (conversation.getNextEncryption()) {
464 case Message.ENCRYPTION_NONE:
465 none.setChecked(true);
466 break;
467 case Message.ENCRYPTION_PGP:
468 pgp.setChecked(true);
469 break;
470 case Message.ENCRYPTION_AXOLOTL:
471 axolotl.setChecked(true);
472 break;
473 default:
474 none.setChecked(true);
475 break;
476 }
477 }
478
479 protected void selectPresenceToAttachFile(final int attachmentChoice, final int encryption) {
480 final Conversation conversation = getSelectedConversation();
481 final Account account = conversation.getAccount();
482 final OnPresenceSelected callback = () -> {
483 Intent intent = new Intent();
484 boolean chooser = false;
485 String fallbackPackageId = null;
486 switch (attachmentChoice) {
487 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
488 intent.setAction(Intent.ACTION_GET_CONTENT);
489 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
490 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
491 }
492 intent.setType("image/*");
493 chooser = true;
494 break;
495 case ATTACHMENT_CHOICE_RECORD_VIDEO:
496 intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
497 break;
498 case ATTACHMENT_CHOICE_TAKE_PHOTO:
499 Uri uri = xmppConnectionService.getFileBackend().getTakePhotoUri();
500 mPendingImageUris.clear();
501 mPendingImageUris.add(uri);
502 intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
503 intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
504 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
505 intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
506 break;
507 case ATTACHMENT_CHOICE_CHOOSE_FILE:
508 chooser = true;
509 intent.setType("*/*");
510 intent.addCategory(Intent.CATEGORY_OPENABLE);
511 intent.setAction(Intent.ACTION_GET_CONTENT);
512 break;
513 case ATTACHMENT_CHOICE_RECORD_VOICE:
514 intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
515 fallbackPackageId = "eu.siacs.conversations.voicerecorder";
516 break;
517 case ATTACHMENT_CHOICE_LOCATION:
518 intent.setAction("eu.siacs.conversations.location.request");
519 fallbackPackageId = "eu.siacs.conversations.sharelocation";
520 break;
521 }
522 if (intent.resolveActivity(getPackageManager()) != null) {
523 if (chooser) {
524 startActivityForResult(
525 Intent.createChooser(intent, getString(R.string.perform_action_with)),
526 attachmentChoice);
527 } else {
528 startActivityForResult(intent, attachmentChoice);
529 }
530 } else if (fallbackPackageId != null) {
531 startActivity(getInstallApkIntent(fallbackPackageId));
532 }
533 };
534 if (account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) {
535 conversation.setNextCounterpart(null);
536 callback.onPresenceSelected();
537 } else {
538 selectPresence(conversation, callback);
539 }
540 }
541
542 private Intent getInstallApkIntent(final String packageId) {
543 Intent intent = new Intent(Intent.ACTION_VIEW);
544 intent.setData(Uri.parse("market://details?id=" + packageId));
545 if (intent.resolveActivity(getPackageManager()) != null) {
546 return intent;
547 } else {
548 intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
549 return intent;
550 }
551 }
552
553 public void attachFile(final int attachmentChoice) {
554 if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
555 if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(attachmentChoice)) {
556 return;
557 }
558 }
559 final ConversationFragment.SendButtonAction action;
560 switch (attachmentChoice) {
561 case ATTACHMENT_CHOICE_LOCATION:
562 action = ConversationFragment.SendButtonAction.SEND_LOCATION;
563 break;
564 case ATTACHMENT_CHOICE_RECORD_VOICE:
565 action = ConversationFragment.SendButtonAction.RECORD_VOICE;
566 break;
567 case ATTACHMENT_CHOICE_RECORD_VIDEO:
568 action = ConversationFragment.SendButtonAction.RECORD_VIDEO;
569 break;
570 case ATTACHMENT_CHOICE_TAKE_PHOTO:
571 action = ConversationFragment.SendButtonAction.TAKE_PHOTO;
572 break;
573 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
574 action = ConversationFragment.SendButtonAction.CHOOSE_PICTURE;
575 break;
576 default:
577 action = null;
578 break;
579 }
580 if (action != null) {
581 getPreferences().edit().putString(RECENTLY_USED_QUICK_ACTION,action.toString()).apply();
582 }
583 final Conversation conversation = getSelectedConversation();
584 final int encryption = conversation.getNextEncryption();
585 final int mode = conversation.getMode();
586 if (encryption == Message.ENCRYPTION_PGP) {
587 if (hasPgp()) {
588 if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
589 xmppConnectionService.getPgpEngine().hasKey(
590 conversation.getContact(),
591 new UiCallback<Contact>() {
592
593 @Override
594 public void userInputRequried(PendingIntent pi, Contact contact) {
595 ConversationActivity.this.runIntent(pi, attachmentChoice);
596 }
597
598 @Override
599 public void success(Contact contact) {
600 selectPresenceToAttachFile(attachmentChoice, encryption);
601 }
602
603 @Override
604 public void error(int error, Contact contact) {
605 replaceToast(getString(error));
606 }
607 });
608 } else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
609 if (!conversation.getMucOptions().everybodyHasKeys()) {
610 Toast warning = Toast
611 .makeText(this,
612 R.string.missing_public_keys,
613 Toast.LENGTH_LONG);
614 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
615 warning.show();
616 }
617 selectPresenceToAttachFile(attachmentChoice, encryption);
618 } else {
619 final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
620 .findFragmentByTag("conversation");
621 if (fragment != null) {
622 fragment.showNoPGPKeyDialog(false,
623 new OnClickListener() {
624
625 @Override
626 public void onClick(DialogInterface dialog,
627 int which) {
628 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
629 xmppConnectionService.updateConversation(conversation);
630 selectPresenceToAttachFile(attachmentChoice, Message.ENCRYPTION_NONE);
631 }
632 });
633 }
634 }
635 } else {
636 showInstallPgpDialog();
637 }
638 } else {
639 if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
640 selectPresenceToAttachFile(attachmentChoice, encryption);
641 }
642 }
643 }
644
645 @Override
646 public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
647 if (grantResults.length > 0)
648 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
649 if (requestCode == REQUEST_START_DOWNLOAD) {
650 if (this.mPendingDownloadableMessage != null) {
651 startDownloadable(this.mPendingDownloadableMessage);
652 }
653 } else if (requestCode == REQUEST_ADD_EDITOR_CONTENT) {
654 if (this.mPendingEditorContent != null) {
655 attachImageToConversation(this.mPendingEditorContent);
656 }
657 } else {
658 attachFile(requestCode);
659 }
660 } else {
661 Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
662 }
663 }
664
665 public void startDownloadable(Message message) {
666 if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(ConversationActivity.REQUEST_START_DOWNLOAD)) {
667 this.mPendingDownloadableMessage = message;
668 return;
669 }
670 Transferable transferable = message.getTransferable();
671 if (transferable != null) {
672 if (!transferable.start()) {
673 Toast.makeText(this, R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
674 }
675 } else if (message.treatAsDownloadable()) {
676 xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
677 }
678 }
679
680 @Override
681 public boolean onOptionsItemSelected(final MenuItem item) {
682 if (item.getItemId() == android.R.id.home) {
683 showConversationsOverview();
684 return true;
685 } else if (item.getItemId() == R.id.action_add) {
686 startActivity(new Intent(this, StartConversationActivity.class));
687 return true;
688 } else if (getSelectedConversation() != null) {
689 switch (item.getItemId()) {
690 case R.id.encryption_choice_axolotl:
691 case R.id.encryption_choice_pgp:
692 case R.id.encryption_choice_none:
693 handleEncryptionSelection(item);
694 break;
695 case R.id.attach_choose_picture:
696 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
697 break;
698 case R.id.attach_take_picture:
699 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
700 break;
701 case R.id.attach_record_video:
702 attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
703 break;
704 case R.id.attach_choose_file:
705 attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
706 break;
707 case R.id.attach_record_voice:
708 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
709 break;
710 case R.id.attach_location:
711 attachFile(ATTACHMENT_CHOICE_LOCATION);
712 break;
713 case R.id.action_archive:
714 this.endConversation(getSelectedConversation());
715 break;
716 case R.id.action_contact_details:
717 switchToContactDetails(getSelectedConversation().getContact());
718 break;
719 case R.id.action_muc_details:
720 Intent intent = new Intent(this,
721 ConferenceDetailsActivity.class);
722 intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
723 intent.putExtra("uuid", getSelectedConversation().getUuid());
724 startActivity(intent);
725 break;
726 case R.id.action_invite:
727 inviteToConversation(getSelectedConversation());
728 break;
729 case R.id.action_clear_history:
730 clearHistoryDialog(getSelectedConversation());
731 break;
732 case R.id.action_mute:
733 muteConversationDialog(getSelectedConversation());
734 break;
735 case R.id.action_unmute:
736 unmuteConversation(getSelectedConversation());
737 break;
738 case R.id.action_block:
739 BlockContactDialog.show(this, getSelectedConversation());
740 break;
741 case R.id.action_unblock:
742 BlockContactDialog.show(this, getSelectedConversation());
743 break;
744 default:
745 break;
746 }
747 return super.onOptionsItemSelected(item);
748 } else {
749 return super.onOptionsItemSelected(item);
750 }
751 }
752
753 public void endConversation(Conversation conversation) {
754 endConversation(conversation, true, true);
755 }
756
757 public void endConversation(Conversation conversation, boolean showOverview, boolean reinit) {
758 if (showOverview) {
759 showConversationsOverview();
760 }
761 xmppConnectionService.archiveConversation(conversation);
762 if (reinit) {
763 if (conversationList.size() > 0) {
764 setSelectedConversation(conversationList.get(0));
765 this.mConversationFragment.reInit(getSelectedConversation());
766 } else {
767 setSelectedConversation(null);
768 if (mRedirected.compareAndSet(false, true)) {
769 Intent intent = new Intent(this, StartConversationActivity.class);
770 intent.putExtra("init", true);
771 startActivity(intent);
772 finish();
773 }
774 }
775 }
776 }
777
778 @SuppressLint("InflateParams")
779 protected void clearHistoryDialog(final Conversation conversation) {
780 AlertDialog.Builder builder = new AlertDialog.Builder(this);
781 builder.setTitle(getString(R.string.clear_conversation_history));
782 final View dialogView = getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
783 final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox);
784 builder.setView(dialogView);
785 builder.setNegativeButton(getString(R.string.cancel), null);
786 builder.setPositiveButton(getString(R.string.delete_messages),
787 (dialog, which) -> {
788 ConversationActivity.this.xmppConnectionService.clearConversationHistory(conversation);
789 if (endConversationCheckBox.isChecked()) {
790 endConversation(conversation);
791 } else {
792 updateConversationList();
793 ConversationActivity.this.mConversationFragment.updateMessages();
794 }
795 });
796 builder.create().show();
797 }
798
799 private void handleEncryptionSelection(MenuItem item) {
800 Conversation conversation = getSelectedConversation();
801 if (conversation == null) {
802 return;
803 }
804 final ConversationFragment fragment = (ConversationFragment) getFragmentManager().findFragmentByTag("conversation");
805 switch (item.getItemId()) {
806 case R.id.encryption_choice_none:
807 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
808 item.setChecked(true);
809 break;
810 case R.id.encryption_choice_pgp:
811 if (hasPgp()) {
812 if (conversation.getAccount().getPgpSignature() != null) {
813 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
814 item.setChecked(true);
815 } else {
816 announcePgp(conversation.getAccount(), conversation,null, onOpenPGPKeyPublished);
817 }
818 } else {
819 showInstallPgpDialog();
820 }
821 break;
822 case R.id.encryption_choice_axolotl:
823 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
824 + "Enabled axolotl for Contact " + conversation.getContact().getJid());
825 conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
826 item.setChecked(true);
827 break;
828 default:
829 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
830 break;
831 }
832 xmppConnectionService.updateConversation(conversation);
833 fragment.updateChatMsgHint();
834 invalidateOptionsMenu();
835 refreshUi();
836 }
837
838 protected void muteConversationDialog(final Conversation conversation) {
839 AlertDialog.Builder builder = new AlertDialog.Builder(this);
840 builder.setTitle(R.string.disable_notifications);
841 final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
842 builder.setItems(R.array.mute_options_descriptions,
843 new OnClickListener() {
844
845 @Override
846 public void onClick(final DialogInterface dialog, final int which) {
847 final long till;
848 if (durations[which] == -1) {
849 till = Long.MAX_VALUE;
850 } else {
851 till = System.currentTimeMillis() + (durations[which] * 1000);
852 }
853 conversation.setMutedTill(till);
854 ConversationActivity.this.xmppConnectionService.updateConversation(conversation);
855 updateConversationList();
856 ConversationActivity.this.mConversationFragment.updateMessages();
857 invalidateOptionsMenu();
858 }
859 });
860 builder.create().show();
861 }
862
863 public void unmuteConversation(final Conversation conversation) {
864 conversation.setMutedTill(0);
865 this.xmppConnectionService.updateConversation(conversation);
866 updateConversationList();
867 ConversationActivity.this.mConversationFragment.updateMessages();
868 invalidateOptionsMenu();
869 }
870
871 @Override
872 public void onBackPressed() {
873 if (!isConversationsOverviewVisable()) {
874 showConversationsOverview();
875 } else {
876 super.onBackPressed();
877 }
878 }
879
880 @Override
881 public boolean onKeyUp(int key, KeyEvent event) {
882 int rotation = getWindowManager().getDefaultDisplay().getRotation();
883 final int upKey;
884 final int downKey;
885 switch (rotation) {
886 case Surface.ROTATION_90:
887 upKey = KeyEvent.KEYCODE_DPAD_LEFT;
888 downKey = KeyEvent.KEYCODE_DPAD_RIGHT;
889 break;
890 case Surface.ROTATION_180:
891 upKey = KeyEvent.KEYCODE_DPAD_DOWN;
892 downKey = KeyEvent.KEYCODE_DPAD_UP;
893 break;
894 case Surface.ROTATION_270:
895 upKey = KeyEvent.KEYCODE_DPAD_RIGHT;
896 downKey = KeyEvent.KEYCODE_DPAD_LEFT;
897 break;
898 case Surface.ROTATION_0:
899 default:
900 upKey = KeyEvent.KEYCODE_DPAD_UP;
901 downKey = KeyEvent.KEYCODE_DPAD_DOWN;
902 }
903 final boolean modifier = event.isCtrlPressed() || (event.getMetaState() & KeyEvent.META_ALT_LEFT_ON) != 0;
904 if (modifier && key == KeyEvent.KEYCODE_TAB && isConversationsOverviewHideable()) {
905 toggleConversationsOverview();
906 return true;
907 } else if (modifier && key == KeyEvent.KEYCODE_SPACE) {
908 startActivity(new Intent(this, StartConversationActivity.class));
909 return true;
910 } else if (modifier && key == downKey) {
911 if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
912 showConversationsOverview();
913 ;
914 }
915 return selectDownConversation();
916 } else if (modifier && key == upKey) {
917 if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
918 showConversationsOverview();
919 }
920 return selectUpConversation();
921 } else if (modifier && key == KeyEvent.KEYCODE_1) {
922 return openConversationByIndex(0);
923 } else if (modifier && key == KeyEvent.KEYCODE_2) {
924 return openConversationByIndex(1);
925 } else if (modifier && key == KeyEvent.KEYCODE_3) {
926 return openConversationByIndex(2);
927 } else if (modifier && key == KeyEvent.KEYCODE_4) {
928 return openConversationByIndex(3);
929 } else if (modifier && key == KeyEvent.KEYCODE_5) {
930 return openConversationByIndex(4);
931 } else if (modifier && key == KeyEvent.KEYCODE_6) {
932 return openConversationByIndex(5);
933 } else if (modifier && key == KeyEvent.KEYCODE_7) {
934 return openConversationByIndex(6);
935 } else if (modifier && key == KeyEvent.KEYCODE_8) {
936 return openConversationByIndex(7);
937 } else if (modifier && key == KeyEvent.KEYCODE_9) {
938 return openConversationByIndex(8);
939 } else if (modifier && key == KeyEvent.KEYCODE_0) {
940 return openConversationByIndex(9);
941 } else {
942 return super.onKeyUp(key, event);
943 }
944 }
945
946 private void toggleConversationsOverview() {
947 if (isConversationsOverviewVisable()) {
948 hideConversationsOverview();
949 if (mConversationFragment != null) {
950 mConversationFragment.setFocusOnInputField();
951 }
952 } else {
953 showConversationsOverview();
954 }
955 }
956
957 private boolean selectUpConversation() {
958 if (this.mSelectedConversation != null) {
959 int index = this.conversationList.indexOf(this.mSelectedConversation);
960 if (index > 0) {
961 return openConversationByIndex(index - 1);
962 }
963 }
964 return false;
965 }
966
967 private boolean selectDownConversation() {
968 if (this.mSelectedConversation != null) {
969 int index = this.conversationList.indexOf(this.mSelectedConversation);
970 if (index != -1 && index < this.conversationList.size() - 1) {
971 return openConversationByIndex(index + 1);
972 }
973 }
974 return false;
975 }
976
977 private boolean openConversationByIndex(int index) {
978 try {
979 this.conversationWasSelectedByKeyboard = true;
980 this.mConversationFragment.stopScrolling();
981 setSelectedConversation(this.conversationList.get(index));
982 this.mConversationFragment.reInit(getSelectedConversation());
983 if (index > listView.getLastVisiblePosition() - 1 || index < listView.getFirstVisiblePosition() + 1) {
984 this.listView.setSelection(index);
985 }
986 openConversation();
987 return true;
988 } catch (IndexOutOfBoundsException e) {
989 return false;
990 }
991 }
992
993 @Override
994 protected void onNewIntent(final Intent intent) {
995 if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
996 mOpenConversation = null;
997 mUnprocessedNewIntent = true;
998 if (xmppConnectionServiceBound) {
999 handleViewConversationIntent(intent);
1000 intent.setAction(Intent.ACTION_MAIN);
1001 } else {
1002 setIntent(intent);
1003 }
1004 }
1005 }
1006
1007 @Override
1008 public void onStart() {
1009 super.onStart();
1010 this.mRedirected.set(false);
1011 if (this.xmppConnectionServiceBound) {
1012 this.onBackendConnected();
1013 }
1014 if (conversationList.size() >= 1) {
1015 this.onConversationUpdate();
1016 }
1017 }
1018
1019 @Override
1020 public void onPause() {
1021 listView.discardUndo();
1022 super.onPause();
1023 this.mActivityPaused = true;
1024 }
1025
1026 @Override
1027 public void onResume() {
1028 super.onResume();
1029 final int theme = findTheme();
1030 final boolean usingEnterKey = usingEnterKey();
1031 if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
1032 recreate();
1033 }
1034 this.mActivityPaused = false;
1035 if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
1036 sendReadMarkerIfNecessary(getSelectedConversation());
1037 }
1038 new Handler().post(() -> {
1039 showSoundRecorderAttachment = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION).resolveActivity(getPackageManager()) != null;
1040 showLocationAttachment = new Intent("eu.siacs.conversations.location.request").resolveActivity(getPackageManager()) != null;
1041 invalidateOptionsMenu();
1042 });
1043 }
1044
1045 @Override
1046 public void onSaveInstanceState(final Bundle savedInstanceState) {
1047 Conversation conversation = getSelectedConversation();
1048 if (conversation != null) {
1049 savedInstanceState.putString(STATE_OPEN_CONVERSATION, conversation.getUuid());
1050 Pair<Integer,Integer> scrollPosition = mConversationFragment.getScrollPosition();
1051 if (scrollPosition != null) {
1052 savedInstanceState.putInt(STATE_FIRST_VISIBLE, scrollPosition.first);
1053 savedInstanceState.putInt(STATE_OFFSET_FROM_TOP, scrollPosition.second);
1054 }
1055 } else {
1056 savedInstanceState.remove(STATE_OPEN_CONVERSATION);
1057 }
1058 savedInstanceState.putBoolean(STATE_PANEL_OPEN, isConversationsOverviewVisable());
1059 if (this.mPendingImageUris.size() >= 1) {
1060 Log.d(Config.LOGTAG,"ConversationsActivity.onSaveInstanceState() - saving pending image uri");
1061 savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1062 } else {
1063 savedInstanceState.remove(STATE_PENDING_URI);
1064 }
1065 super.onSaveInstanceState(savedInstanceState);
1066 }
1067
1068 private void clearPending() {
1069 mPendingImageUris.clear();
1070 mPendingFileUris.clear();
1071 mPendingGeoUri = null;
1072 mPostponedActivityResult = null;
1073 }
1074
1075 private void redirectToStartConversationActivity(boolean noAnimation) {
1076 Account pendingAccount = xmppConnectionService.getPendingAccount();
1077 if (pendingAccount == null) {
1078 Intent startConversationActivity = new Intent(this, StartConversationActivity.class);
1079 startConversationActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
1080 if (noAnimation) {
1081 startConversationActivity.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
1082 }
1083 startConversationActivity.putExtra("init", true);
1084 startActivity(startConversationActivity);
1085 if (noAnimation) {
1086 overridePendingTransition(0,0);
1087 }
1088 } else {
1089 switchToAccount(pendingAccount, true);
1090 }
1091 }
1092
1093 @Override
1094 void onBackendConnected() {
1095 this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1096 updateConversationList();
1097
1098 if (mPendingConferenceInvite != null) {
1099 if (mPendingConferenceInvite.execute(this)) {
1100 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
1101 mToast.show();
1102 }
1103 mPendingConferenceInvite = null;
1104 }
1105
1106 final Intent intent = getIntent();
1107
1108 if (xmppConnectionService.getAccounts().size() == 0) {
1109 if (mRedirected.compareAndSet(false, true)) {
1110 if (Config.X509_VERIFICATION) {
1111 Intent redirectionIntent = new Intent(this, ManageAccountActivity.class);
1112 redirectionIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
1113 startActivity(redirectionIntent);
1114 overridePendingTransition(0,0);
1115 } else if (Config.MAGIC_CREATE_DOMAIN != null) {
1116 WelcomeActivity.launch(this);
1117 } else {
1118 Intent editAccount = new Intent(this, EditAccountActivity.class);
1119 editAccount.putExtra("init",true);
1120 editAccount.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
1121 startActivity(editAccount);
1122 overridePendingTransition(0,0);
1123 }
1124 }
1125 } else if (conversationList.size() <= 0) {
1126 if (mRedirected.compareAndSet(false, true)) {
1127 redirectToStartConversationActivity(true);
1128 }
1129 } else if (selectConversationByUuid(mOpenConversation)) {
1130 if (mPanelOpen) {
1131 showConversationsOverview();
1132 } else {
1133 if (isConversationsOverviewHideable()) {
1134 openConversation();
1135 updateActionBarTitle(true);
1136 }
1137 }
1138 if (this.mConversationFragment.reInit(getSelectedConversation())) {
1139 Log.d(Config.LOGTAG,"setting scroll position on fragment");
1140 this.mConversationFragment.setScrollPosition(mScrollPosition);
1141 }
1142 mOpenConversation = null;
1143 } else if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1144 clearPending();
1145 handleViewConversationIntent(intent);
1146 intent.setAction(Intent.ACTION_MAIN);
1147 } else if (getSelectedConversation() == null) {
1148 reInitLatestConversation();
1149 } else {
1150 this.mConversationFragment.messageListAdapter.updatePreferences();
1151 this.mConversationFragment.messagesView.invalidateViews();
1152 this.mConversationFragment.setupIme();
1153 }
1154
1155 if (this.mPostponedActivityResult != null) {
1156 this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1157 }
1158
1159 final boolean stopping = isStopping();
1160
1161 if (!forbidProcessingPendings) {
1162 for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1163 Uri foo = i.next();
1164 Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching image to conversations. stopping="+Boolean.toString(stopping));
1165 attachImageToConversation(getSelectedConversation(), foo);
1166 }
1167
1168 for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1169 Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching file to conversations. stopping="+Boolean.toString(stopping));
1170 attachFileToConversation(getSelectedConversation(), i.next());
1171 }
1172
1173 if (mPendingGeoUri != null) {
1174 attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1175 mPendingGeoUri = null;
1176 }
1177 }
1178 forbidProcessingPendings = false;
1179
1180 if (!ExceptionHelper.checkForCrash(this, this.xmppConnectionService) && !mRedirected.get()) {
1181 openBatteryOptimizationDialogIfNeeded();
1182 }
1183 if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
1184 xmppConnectionService.getNotificationService().setOpenConversation(null);
1185 } else {
1186 xmppConnectionService.getNotificationService().setOpenConversation(getSelectedConversation());
1187 }
1188 }
1189
1190 private boolean isStopping() {
1191 if (Build.VERSION.SDK_INT >= 17) {
1192 return isFinishing() || isDestroyed();
1193 } else {
1194 return isFinishing();
1195 }
1196 }
1197
1198 private void reInitLatestConversation() {
1199 showConversationsOverview();
1200 clearPending();
1201 setSelectedConversation(conversationList.get(0));
1202 this.mConversationFragment.reInit(getSelectedConversation());
1203 }
1204
1205 private void handleViewConversationIntent(final Intent intent) {
1206 final String uuid = intent.getStringExtra(CONVERSATION);
1207 final String downloadUuid = intent.getStringExtra(EXTRA_DOWNLOAD_UUID);
1208 final String text = intent.getStringExtra(TEXT);
1209 final String nick = intent.getStringExtra(NICK);
1210 final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1211 this.mConversationFragment.stopScrolling();
1212 if (selectConversationByUuid(uuid)) {
1213 this.mConversationFragment.reInit(getSelectedConversation());
1214 if (nick != null) {
1215 if (pm) {
1216 Jid jid = getSelectedConversation().getJid();
1217 try {
1218 Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1219 this.mConversationFragment.privateMessageWith(next);
1220 } catch (final InvalidJidException ignored) {
1221 //do nothing
1222 }
1223 } else {
1224 this.mConversationFragment.highlightInConference(nick);
1225 }
1226 } else {
1227 this.mConversationFragment.appendText(text);
1228 }
1229 hideConversationsOverview();
1230 mUnprocessedNewIntent = false;
1231 openConversation();
1232 if (mContentView instanceof SlidingPaneLayout) {
1233 updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1234 }
1235 if (downloadUuid != null) {
1236 final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1237 if (message != null) {
1238 startDownloadable(message);
1239 }
1240 }
1241 } else {
1242 mUnprocessedNewIntent = false;
1243 }
1244 }
1245
1246 private boolean selectConversationByUuid(String uuid) {
1247 if (uuid == null) {
1248 return false;
1249 }
1250 for (Conversation aConversationList : conversationList) {
1251 if (aConversationList.getUuid().equals(uuid)) {
1252 setSelectedConversation(aConversationList);
1253 return true;
1254 }
1255 }
1256 return false;
1257 }
1258
1259 @Override
1260 protected void unregisterListeners() {
1261 super.unregisterListeners();
1262 xmppConnectionService.getNotificationService().setOpenConversation(null);
1263 }
1264
1265 @SuppressLint("NewApi")
1266 private static List<Uri> extractUriFromIntent(final Intent intent) {
1267 List<Uri> uris = new ArrayList<>();
1268 if (intent == null) {
1269 return uris;
1270 }
1271 Uri uri = intent.getData();
1272 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1273 final ClipData clipData = intent.getClipData();
1274 if (clipData != null) {
1275 for (int i = 0; i < clipData.getItemCount(); ++i) {
1276 uris.add(clipData.getItemAt(i).getUri());
1277 }
1278 }
1279 } else {
1280 uris.add(uri);
1281 }
1282 return uris;
1283 }
1284
1285 @Override
1286 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1287 super.onActivityResult(requestCode, resultCode, data);
1288 if (resultCode == RESULT_OK) {
1289 if (requestCode == REQUEST_DECRYPT_PGP) {
1290 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1291 } else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1292 // the user chose OpenPGP for encryption and selected his key in the PGP provider
1293 if (xmppConnectionServiceBound) {
1294 if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1295 // associate selected PGP keyId with the account
1296 mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1297 // we need to announce the key as described in XEP-027
1298 announcePgp(mSelectedConversation.getAccount(), null, null, onOpenPGPKeyPublished);
1299 } else {
1300 choosePgpSignId(mSelectedConversation.getAccount());
1301 }
1302 this.mPostponedActivityResult = null;
1303 } else {
1304 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1305 }
1306 } else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1307 if (xmppConnectionServiceBound) {
1308 announcePgp(mSelectedConversation.getAccount(), mSelectedConversation,data, onOpenPGPKeyPublished);
1309 this.mPostponedActivityResult = null;
1310 } else {
1311 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1312 }
1313 } else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1314 mPendingImageUris.clear();
1315 mPendingImageUris.addAll(extractUriFromIntent(data));
1316 if (xmppConnectionServiceBound) {
1317 for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1318 Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. CHOOSE_IMAGE");
1319 attachImageToConversation(getSelectedConversation(), i.next());
1320 }
1321 }
1322 } else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE || requestCode == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1323 final List<Uri> uris = extractUriFromIntent(data);
1324 Log.d(Config.LOGTAG,"uris "+uris.toString());
1325 final Conversation c = getSelectedConversation();
1326 final OnPresenceSelected callback = new OnPresenceSelected() {
1327 @Override
1328 public void onPresenceSelected() {
1329 mPendingFileUris.clear();
1330 mPendingFileUris.addAll(uris);
1331 if (xmppConnectionServiceBound) {
1332 for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1333 Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO");
1334 attachFileToConversation(c, i.next());
1335 }
1336 }
1337 }
1338 };
1339 if (c == null || c.getMode() == Conversation.MODE_MULTI
1340 || FileBackend.allFilesUnderSize(this, uris, getMaxHttpUploadSize(c))) {
1341 callback.onPresenceSelected();
1342 } else {
1343 selectPresence(c, callback);
1344 }
1345 } else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1346 if (mPendingImageUris.size() == 1) {
1347 Uri uri = FileBackend.getIndexableTakePhotoUri(mPendingImageUris.get(0));
1348 mPendingImageUris.set(0, uri);
1349 if (xmppConnectionServiceBound) {
1350 Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. TAKE_PHOTO");
1351 attachImageToConversation(getSelectedConversation(), uri);
1352 mPendingImageUris.clear();
1353 }
1354 if (!Config.ONLY_INTERNAL_STORAGE) {
1355 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1356 intent.setData(uri);
1357 sendBroadcast(intent);
1358 }
1359 } else {
1360 mPendingImageUris.clear();
1361 }
1362 } else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1363 double latitude = data.getDoubleExtra("latitude", 0);
1364 double longitude = data.getDoubleExtra("longitude", 0);
1365 this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1366 if (xmppConnectionServiceBound) {
1367 attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1368 this.mPendingGeoUri = null;
1369 }
1370 } else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1371 this.forbidProcessingPendings = true;
1372 if (xmppConnectionServiceBound) {
1373 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1374 this.mPostponedActivityResult = null;
1375 } else {
1376 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1377 }
1378
1379 }
1380 } else {
1381 mPendingImageUris.clear();
1382 mPendingFileUris.clear();
1383 if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1384 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1385 }
1386 if (requestCode == REQUEST_BATTERY_OP) {
1387 setNeverAskForBatteryOptimizationsAgain();
1388 }
1389 }
1390 }
1391
1392 private long getMaxHttpUploadSize(Conversation conversation) {
1393 final XmppConnection connection = conversation.getAccount().getXmppConnection();
1394 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
1395 }
1396
1397 private String getBatteryOptimizationPreferenceKey() {
1398 @SuppressLint("HardwareIds") String device = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
1399 return "show_battery_optimization"+(device == null ? "" : device);
1400 }
1401
1402 private void setNeverAskForBatteryOptimizationsAgain() {
1403 getPreferences().edit().putBoolean(getBatteryOptimizationPreferenceKey(), false).apply();
1404 }
1405
1406 private void openBatteryOptimizationDialogIfNeeded() {
1407 if (hasAccountWithoutPush()
1408 && isOptimizingBattery()
1409 && getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
1410 AlertDialog.Builder builder = new AlertDialog.Builder(this);
1411 builder.setTitle(R.string.battery_optimizations_enabled);
1412 builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1413 builder.setPositiveButton(R.string.next, (dialog, which) -> {
1414 Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1415 Uri uri = Uri.parse("package:" + getPackageName());
1416 intent.setData(uri);
1417 try {
1418 startActivityForResult(intent, REQUEST_BATTERY_OP);
1419 } catch (ActivityNotFoundException e) {
1420 Toast.makeText(ConversationActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1421 }
1422 });
1423 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1424 builder.setOnDismissListener(dialog -> setNeverAskForBatteryOptimizationsAgain());
1425 }
1426 AlertDialog dialog = builder.create();
1427 dialog.setCanceledOnTouchOutside(false);
1428 dialog.show();
1429 }
1430 }
1431
1432 private boolean hasAccountWithoutPush() {
1433 for(Account account : xmppConnectionService.getAccounts()) {
1434 if (account.getStatus() == Account.State.ONLINE && !xmppConnectionService.getPushManagementService().available(account)) {
1435 return true;
1436 }
1437 }
1438 return false;
1439 }
1440
1441 private void attachLocationToConversation(Conversation conversation, Uri uri) {
1442 if (conversation == null) {
1443 return;
1444 }
1445 xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1446
1447 @Override
1448 public void success(Message message) {
1449 xmppConnectionService.sendMessage(message);
1450 }
1451
1452 @Override
1453 public void error(int errorCode, Message object) {
1454
1455 }
1456
1457 @Override
1458 public void userInputRequried(PendingIntent pi, Message object) {
1459
1460 }
1461 });
1462 }
1463
1464 private void attachFileToConversation(Conversation conversation, Uri uri) {
1465 if (conversation == null) {
1466 return;
1467 }
1468 final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1469 prepareFileToast.show();
1470 delegateUriPermissionsToService(uri);
1471 xmppConnectionService.attachFileToConversation(conversation, uri, new UiInformableCallback<Message>() {
1472 @Override
1473 public void inform(final String text) {
1474 hidePrepareFileToast(prepareFileToast);
1475 runOnUiThread(new Runnable() {
1476 @Override
1477 public void run() {
1478 replaceToast(text);
1479 }
1480 });
1481 }
1482
1483 @Override
1484 public void success(Message message) {
1485 runOnUiThread(new Runnable() {
1486 @Override
1487 public void run() {
1488 hideToast();
1489 }
1490 });
1491 hidePrepareFileToast(prepareFileToast);
1492 xmppConnectionService.sendMessage(message);
1493 }
1494
1495 @Override
1496 public void error(final int errorCode, Message message) {
1497 hidePrepareFileToast(prepareFileToast);
1498 runOnUiThread(new Runnable() {
1499 @Override
1500 public void run() {
1501 replaceToast(getString(errorCode));
1502 }
1503 });
1504
1505 }
1506
1507 @Override
1508 public void userInputRequried(PendingIntent pi, Message message) {
1509 hidePrepareFileToast(prepareFileToast);
1510 }
1511 });
1512 }
1513
1514 public void attachImageToConversation(Uri uri) {
1515 this.attachImageToConversation(getSelectedConversation(), uri);
1516 }
1517
1518 private void attachImageToConversation(Conversation conversation, Uri uri) {
1519 if (conversation == null) {
1520 return;
1521 }
1522 final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1523 prepareFileToast.show();
1524 delegateUriPermissionsToService(uri);
1525 xmppConnectionService.attachImageToConversation(conversation, uri,
1526 new UiCallback<Message>() {
1527
1528 @Override
1529 public void userInputRequried(PendingIntent pi, Message object) {
1530 hidePrepareFileToast(prepareFileToast);
1531 }
1532
1533 @Override
1534 public void success(Message message) {
1535 hidePrepareFileToast(prepareFileToast);
1536 xmppConnectionService.sendMessage(message);
1537 }
1538
1539 @Override
1540 public void error(final int error, Message message) {
1541 hidePrepareFileToast(prepareFileToast);
1542 runOnUiThread(new Runnable() {
1543 @Override
1544 public void run() {
1545 replaceToast(getString(error));
1546 }
1547 });
1548 }
1549 });
1550 }
1551
1552 private void hidePrepareFileToast(final Toast prepareFileToast) {
1553 if (prepareFileToast != null) {
1554 runOnUiThread(new Runnable() {
1555
1556 @Override
1557 public void run() {
1558 prepareFileToast.cancel();
1559 }
1560 });
1561 }
1562 }
1563
1564 public void updateConversationList() {
1565 xmppConnectionService.populateWithOrderedConversations(conversationList);
1566 if (!conversationList.contains(mSelectedConversation)) {
1567 mSelectedConversation = null;
1568 }
1569 if (swipedConversation != null) {
1570 if (swipedConversation.isRead()) {
1571 conversationList.remove(swipedConversation);
1572 } else {
1573 listView.discardUndo();
1574 }
1575 }
1576 listAdapter.notifyDataSetChanged();
1577 }
1578
1579 public void runIntent(PendingIntent pi, int requestCode) {
1580 try {
1581 this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1582 null, 0, 0, 0);
1583 } catch (final SendIntentException ignored) {
1584 }
1585 }
1586
1587 public void encryptTextMessage(Message message) {
1588 xmppConnectionService.getPgpEngine().encrypt(message,
1589 new UiCallback<Message>() {
1590
1591 @Override
1592 public void userInputRequried(PendingIntent pi,Message message) {
1593 ConversationActivity.this.runIntent(pi,ConversationActivity.REQUEST_SEND_MESSAGE);
1594 }
1595
1596 @Override
1597 public void success(Message message) {
1598 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1599 xmppConnectionService.sendMessage(message);
1600 runOnUiThread(new Runnable() {
1601 @Override
1602 public void run() {
1603 mConversationFragment.messageSent();
1604 }
1605 });
1606 }
1607
1608 @Override
1609 public void error(final int error, Message message) {
1610 runOnUiThread(new Runnable() {
1611 @Override
1612 public void run() {
1613 mConversationFragment.doneSendingPgpMessage();
1614 Toast.makeText(ConversationActivity.this,
1615 R.string.unable_to_connect_to_keychain,
1616 Toast.LENGTH_SHORT
1617 ).show();
1618 }
1619 });
1620
1621 }
1622 });
1623 }
1624
1625 public boolean useSendButtonToIndicateStatus() {
1626 return getPreferences().getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
1627 }
1628
1629 public boolean indicateReceived() {
1630 return getPreferences().getBoolean("indicate_received", getResources().getBoolean(R.bool.indicate_received));
1631 }
1632
1633 public boolean useGreenBackground() {
1634 return getPreferences().getBoolean("use_green_background",getResources().getBoolean(R.bool.use_green_background));
1635 }
1636
1637 protected boolean trustKeysIfNeeded(int requestCode) {
1638 return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1639 }
1640
1641 protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1642 AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1643 final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1644 boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1645 boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided()).isEmpty();
1646 boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets).isEmpty();
1647 boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1648 boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1649 if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1650 axolotlService.createSessionsIfNeeded(mSelectedConversation);
1651 Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1652 String[] contacts = new String[targets.size()];
1653 for(int i = 0; i < contacts.length; ++i) {
1654 contacts[i] = targets.get(i).toString();
1655 }
1656 intent.putExtra("contacts", contacts);
1657 intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1658 intent.putExtra("choice", attachmentChoice);
1659 intent.putExtra("conversation",mSelectedConversation.getUuid());
1660 startActivityForResult(intent, requestCode);
1661 return true;
1662 } else {
1663 return false;
1664 }
1665 }
1666
1667 @Override
1668 protected void refreshUiReal() {
1669 updateConversationList();
1670 if (conversationList.size() > 0) {
1671 if (!this.mConversationFragment.isAdded()) {
1672 Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1673 }
1674 if (getSelectedConversation() == null) {
1675 reInitLatestConversation();
1676 } else {
1677 ConversationActivity.this.mConversationFragment.updateMessages();
1678 updateActionBarTitle();
1679 invalidateOptionsMenu();
1680 }
1681 } else {
1682 if (!isStopping() && mRedirected.compareAndSet(false, true)) {
1683 redirectToStartConversationActivity(false);
1684 }
1685 Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1686 }
1687 }
1688
1689 @Override
1690 public void onAccountUpdate() {
1691 this.refreshUi();
1692 }
1693
1694 @Override
1695 public void onConversationUpdate() {
1696 this.refreshUi();
1697 }
1698
1699 @Override
1700 public void onRosterUpdate() {
1701 this.refreshUi();
1702 }
1703
1704 @Override
1705 public void OnUpdateBlocklist(Status status) {
1706 this.refreshUi();
1707 }
1708
1709 public void unblockConversation(final Blockable conversation) {
1710 xmppConnectionService.sendUnblockRequest(conversation);
1711 }
1712
1713 public boolean enterIsSend() {
1714 return getPreferences().getBoolean("enter_is_send",getResources().getBoolean(R.bool.enter_is_send));
1715 }
1716
1717 @Override
1718 public void onShowErrorToast(final int resId) {
1719 runOnUiThread(new Runnable() {
1720 @Override
1721 public void run() {
1722 Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1723 }
1724 });
1725 }
1726
1727 public boolean highlightSelectedConversations() {
1728 return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1729 }
1730}