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