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 if (Config.MAGIC_CREATE_DOMAIN != null) {
1129 startActivity(new Intent(this, WelcomeActivity.class));
1130 } else {
1131 startActivity(new Intent(this, EditAccountActivity.class));
1132 }
1133 finish();
1134 }
1135 } else if (conversationList.size() <= 0) {
1136 if (mRedirected.compareAndSet(false, true)) {
1137 Account pendingAccount = xmppConnectionService.getPendingAccount();
1138 if (pendingAccount == null) {
1139 Intent intent = new Intent(this, StartConversationActivity.class);
1140 intent.putExtra("init", true);
1141 startActivity(intent);
1142 } else {
1143 switchToAccount(pendingAccount, true);
1144 }
1145 finish();
1146 }
1147 } else if (getIntent() != null && VIEW_CONVERSATION.equals(getIntent().getType())) {
1148 clearPending();
1149 handleViewConversationIntent(getIntent());
1150 } else if (selectConversationByUuid(mOpenConverstaion)) {
1151 if (mPanelOpen) {
1152 showConversationsOverview();
1153 } else {
1154 if (isConversationsOverviewHideable()) {
1155 openConversation();
1156 updateActionBarTitle(true);
1157 }
1158 }
1159 this.mConversationFragment.reInit(getSelectedConversation());
1160 mOpenConverstaion = null;
1161 } else if (getSelectedConversation() == null) {
1162 showConversationsOverview();
1163 clearPending();
1164 setSelectedConversation(conversationList.get(0));
1165 this.mConversationFragment.reInit(getSelectedConversation());
1166 } else {
1167 this.mConversationFragment.messageListAdapter.updatePreferences();
1168 this.mConversationFragment.messagesView.invalidateViews();
1169 this.mConversationFragment.setupIme();
1170 }
1171
1172 if (this.mPostponedActivityResult != null) {
1173 this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1174 }
1175
1176 if (!forbidProcessingPendings) {
1177 for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1178 Uri foo = i.next();
1179 attachImageToConversation(getSelectedConversation(), foo);
1180 }
1181
1182 for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1183 attachFileToConversation(getSelectedConversation(), i.next());
1184 }
1185
1186 if (mPendingGeoUri != null) {
1187 attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1188 mPendingGeoUri = null;
1189 }
1190 }
1191 forbidProcessingPendings = false;
1192
1193 if (!ExceptionHelper.checkForCrash(this, this.xmppConnectionService)) {
1194 openBatteryOptimizationDialogIfNeeded();
1195 }
1196 setIntent(new Intent());
1197 }
1198
1199 private void handleViewConversationIntent(final Intent intent) {
1200 final String uuid = intent.getStringExtra(CONVERSATION);
1201 final String downloadUuid = intent.getStringExtra(MESSAGE);
1202 final String text = intent.getStringExtra(TEXT);
1203 final String nick = intent.getStringExtra(NICK);
1204 final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1205 if (selectConversationByUuid(uuid)) {
1206 this.mConversationFragment.reInit(getSelectedConversation());
1207 if (nick != null) {
1208 if (pm) {
1209 Jid jid = getSelectedConversation().getJid();
1210 try {
1211 Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1212 this.mConversationFragment.privateMessageWith(next);
1213 } catch (final InvalidJidException ignored) {
1214 //do nothing
1215 }
1216 } else {
1217 this.mConversationFragment.highlightInConference(nick);
1218 }
1219 } else {
1220 this.mConversationFragment.appendText(text);
1221 }
1222 hideConversationsOverview();
1223 openConversation();
1224 if (mContentView instanceof SlidingPaneLayout) {
1225 updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1226 }
1227 if (downloadUuid != null) {
1228 final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1229 if (message != null) {
1230 startDownloadable(message);
1231 }
1232 }
1233 }
1234 }
1235
1236 private boolean selectConversationByUuid(String uuid) {
1237 if (uuid == null) {
1238 return false;
1239 }
1240 for (Conversation aConversationList : conversationList) {
1241 if (aConversationList.getUuid().equals(uuid)) {
1242 setSelectedConversation(aConversationList);
1243 return true;
1244 }
1245 }
1246 return false;
1247 }
1248
1249 @Override
1250 protected void unregisterListeners() {
1251 super.unregisterListeners();
1252 xmppConnectionService.getNotificationService().setOpenConversation(null);
1253 }
1254
1255 @SuppressLint("NewApi")
1256 private static List<Uri> extractUriFromIntent(final Intent intent) {
1257 List<Uri> uris = new ArrayList<>();
1258 if (intent == null) {
1259 return uris;
1260 }
1261 Uri uri = intent.getData();
1262 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1263 ClipData clipData = intent.getClipData();
1264 for (int i = 0; i < clipData.getItemCount(); ++i) {
1265 uris.add(clipData.getItemAt(i).getUri());
1266 }
1267 } else {
1268 uris.add(uri);
1269 }
1270 return uris;
1271 }
1272
1273 @Override
1274 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1275 super.onActivityResult(requestCode, resultCode, data);
1276 if (resultCode == RESULT_OK) {
1277 if (requestCode == REQUEST_DECRYPT_PGP) {
1278 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1279 } else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1280 // the user chose OpenPGP for encryption and selected his key in the PGP provider
1281 if (xmppConnectionServiceBound) {
1282 if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1283 // associate selected PGP keyId with the account
1284 mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1285 // we need to announce the key as described in XEP-027
1286 announcePgp(mSelectedConversation.getAccount(), null);
1287 } else {
1288 choosePgpSignId(mSelectedConversation.getAccount());
1289 }
1290 this.mPostponedActivityResult = null;
1291 } else {
1292 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1293 }
1294 } else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1295 if (xmppConnectionServiceBound) {
1296 announcePgp(mSelectedConversation.getAccount(), mSelectedConversation);
1297 this.mPostponedActivityResult = null;
1298 } else {
1299 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1300 }
1301 } else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1302 mPendingImageUris.clear();
1303 mPendingImageUris.addAll(extractUriFromIntent(data));
1304 if (xmppConnectionServiceBound) {
1305 for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1306 attachImageToConversation(getSelectedConversation(), i.next());
1307 }
1308 }
1309 } else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1310 final List<Uri> uris = extractUriFromIntent(data);
1311 final Conversation c = getSelectedConversation();
1312 final OnPresenceSelected callback = new OnPresenceSelected() {
1313 @Override
1314 public void onPresenceSelected() {
1315 mPendingFileUris.clear();
1316 mPendingFileUris.addAll(uris);
1317 if (xmppConnectionServiceBound) {
1318 for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1319 attachFileToConversation(c, i.next());
1320 }
1321 }
1322 }
1323 };
1324 if (c == null || c.getMode() == Conversation.MODE_MULTI
1325 || FileBackend.allFilesUnderSize(this, uris, getMaxHttpUploadSize(c))
1326 || c.getNextEncryption() == Message.ENCRYPTION_OTR) {
1327 callback.onPresenceSelected();
1328 } else {
1329 selectPresence(c, callback);
1330 }
1331 } else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1332 if (mPendingImageUris.size() == 1) {
1333 Uri uri = mPendingImageUris.get(0);
1334 if (xmppConnectionServiceBound) {
1335 attachImageToConversation(getSelectedConversation(), uri);
1336 mPendingImageUris.clear();
1337 }
1338 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1339 intent.setData(uri);
1340 sendBroadcast(intent);
1341 } else {
1342 mPendingImageUris.clear();
1343 }
1344 } else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1345 double latitude = data.getDoubleExtra("latitude", 0);
1346 double longitude = data.getDoubleExtra("longitude", 0);
1347 this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1348 if (xmppConnectionServiceBound) {
1349 attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1350 this.mPendingGeoUri = null;
1351 }
1352 } else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1353 this.forbidProcessingPendings = !xmppConnectionServiceBound;
1354 if (xmppConnectionServiceBound) {
1355 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1356 this.mPostponedActivityResult = null;
1357 } else {
1358 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1359 }
1360
1361 }
1362 } else {
1363 mPendingImageUris.clear();
1364 mPendingFileUris.clear();
1365 if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1366 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1367 }
1368 if (requestCode == REQUEST_BATTERY_OP) {
1369 setNeverAskForBatteryOptimizationsAgain();
1370 }
1371 }
1372 }
1373
1374 private long getMaxHttpUploadSize(Conversation conversation) {
1375 return conversation.getAccount().getXmppConnection().getFeatures().getMaxHttpUploadSize();
1376 }
1377
1378 private void setNeverAskForBatteryOptimizationsAgain() {
1379 getPreferences().edit().putBoolean("show_battery_optimization", false).commit();
1380 }
1381
1382 private void openBatteryOptimizationDialogIfNeeded() {
1383 if (hasAccountWithoutPush()
1384 && isOptimizingBattery()
1385 && getPreferences().getBoolean("show_battery_optimization", true)) {
1386 AlertDialog.Builder builder = new AlertDialog.Builder(this);
1387 builder.setTitle(R.string.battery_optimizations_enabled);
1388 builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1389 builder.setPositiveButton(R.string.next, new OnClickListener() {
1390 @Override
1391 public void onClick(DialogInterface dialog, int which) {
1392 Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1393 Uri uri = Uri.parse("package:" + getPackageName());
1394 intent.setData(uri);
1395 startActivityForResult(intent, REQUEST_BATTERY_OP);
1396 }
1397 });
1398 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1399 builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1400 @Override
1401 public void onDismiss(DialogInterface dialog) {
1402 setNeverAskForBatteryOptimizationsAgain();
1403 }
1404 });
1405 }
1406 builder.create().show();
1407 }
1408 }
1409
1410 private boolean hasAccountWithoutPush() {
1411 for(Account account : xmppConnectionService.getAccounts()) {
1412 if (account.getStatus() != Account.State.DISABLED
1413 && !xmppConnectionService.getPushManagementService().available(account)) {
1414 return true;
1415 }
1416 }
1417 return false;
1418 }
1419
1420 private void attachLocationToConversation(Conversation conversation, Uri uri) {
1421 if (conversation == null) {
1422 return;
1423 }
1424 xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1425
1426 @Override
1427 public void success(Message message) {
1428 xmppConnectionService.sendMessage(message);
1429 }
1430
1431 @Override
1432 public void error(int errorCode, Message object) {
1433
1434 }
1435
1436 @Override
1437 public void userInputRequried(PendingIntent pi, Message object) {
1438
1439 }
1440 });
1441 }
1442
1443 private void attachFileToConversation(Conversation conversation, Uri uri) {
1444 if (conversation == null) {
1445 return;
1446 }
1447 final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1448 prepareFileToast.show();
1449 xmppConnectionService.attachFileToConversation(conversation, uri, new UiCallback<Message>() {
1450 @Override
1451 public void success(Message message) {
1452 hidePrepareFileToast(prepareFileToast);
1453 xmppConnectionService.sendMessage(message);
1454 }
1455
1456 @Override
1457 public void error(int errorCode, Message message) {
1458 hidePrepareFileToast(prepareFileToast);
1459 displayErrorDialog(errorCode);
1460 }
1461
1462 @Override
1463 public void userInputRequried(PendingIntent pi, Message message) {
1464
1465 }
1466 });
1467 }
1468
1469 private void attachImageToConversation(Conversation conversation, Uri uri) {
1470 if (conversation == null) {
1471 return;
1472 }
1473 final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1474 prepareFileToast.show();
1475 xmppConnectionService.attachImageToConversation(conversation, uri,
1476 new UiCallback<Message>() {
1477
1478 @Override
1479 public void userInputRequried(PendingIntent pi, Message object) {
1480 hidePrepareFileToast(prepareFileToast);
1481 }
1482
1483 @Override
1484 public void success(Message message) {
1485 hidePrepareFileToast(prepareFileToast);
1486 xmppConnectionService.sendMessage(message);
1487 }
1488
1489 @Override
1490 public void error(int error, Message message) {
1491 hidePrepareFileToast(prepareFileToast);
1492 displayErrorDialog(error);
1493 }
1494 });
1495 }
1496
1497 private void hidePrepareFileToast(final Toast prepareFileToast) {
1498 if (prepareFileToast != null) {
1499 runOnUiThread(new Runnable() {
1500
1501 @Override
1502 public void run() {
1503 prepareFileToast.cancel();
1504 }
1505 });
1506 }
1507 }
1508
1509 public void updateConversationList() {
1510 xmppConnectionService
1511 .populateWithOrderedConversations(conversationList);
1512 if (swipedConversation != null) {
1513 if (swipedConversation.isRead()) {
1514 conversationList.remove(swipedConversation);
1515 } else {
1516 listView.discardUndo();
1517 }
1518 }
1519 listAdapter.notifyDataSetChanged();
1520 }
1521
1522 public void runIntent(PendingIntent pi, int requestCode) {
1523 try {
1524 this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1525 null, 0, 0, 0);
1526 } catch (final SendIntentException ignored) {
1527 }
1528 }
1529
1530 public void encryptTextMessage(Message message) {
1531 xmppConnectionService.getPgpEngine().encrypt(message,
1532 new UiCallback<Message>() {
1533
1534 @Override
1535 public void userInputRequried(PendingIntent pi,
1536 Message message) {
1537 ConversationActivity.this.runIntent(pi,
1538 ConversationActivity.REQUEST_SEND_MESSAGE);
1539 }
1540
1541 @Override
1542 public void success(Message message) {
1543 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1544 xmppConnectionService.sendMessage(message);
1545 }
1546
1547 @Override
1548 public void error(int error, Message message) {
1549
1550 }
1551 });
1552 }
1553
1554 public boolean useSendButtonToIndicateStatus() {
1555 return getPreferences().getBoolean("send_button_status", false);
1556 }
1557
1558 public boolean indicateReceived() {
1559 return getPreferences().getBoolean("indicate_received", false);
1560 }
1561
1562 public boolean useWhiteBackground() {
1563 return getPreferences().getBoolean("use_white_background",false);
1564 }
1565
1566 protected boolean trustKeysIfNeeded(int requestCode) {
1567 return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1568 }
1569
1570 protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1571 AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1572 final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1573 boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1574 boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED).isEmpty();
1575 boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED, targets).isEmpty();
1576 boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1577 boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1578 if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1579 axolotlService.createSessionsIfNeeded(mSelectedConversation);
1580 Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1581 String[] contacts = new String[targets.size()];
1582 for(int i = 0; i < contacts.length; ++i) {
1583 contacts[i] = targets.get(i).toString();
1584 }
1585 intent.putExtra("contacts", contacts);
1586 intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1587 intent.putExtra("choice", attachmentChoice);
1588 intent.putExtra("conversation",mSelectedConversation.getUuid());
1589 startActivityForResult(intent, requestCode);
1590 return true;
1591 } else {
1592 return false;
1593 }
1594 }
1595
1596 @Override
1597 protected void refreshUiReal() {
1598 updateConversationList();
1599 if (conversationList.size() > 0) {
1600 if (!this.mConversationFragment.isAdded()) {
1601 Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1602 }
1603 ConversationActivity.this.mConversationFragment.updateMessages();
1604 updateActionBarTitle();
1605 invalidateOptionsMenu();
1606 } else {
1607 Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1608 }
1609 }
1610
1611 @Override
1612 public void onAccountUpdate() {
1613 this.refreshUi();
1614 }
1615
1616 @Override
1617 public void onConversationUpdate() {
1618 this.refreshUi();
1619 }
1620
1621 @Override
1622 public void onRosterUpdate() {
1623 this.refreshUi();
1624 }
1625
1626 @Override
1627 public void OnUpdateBlocklist(Status status) {
1628 this.refreshUi();
1629 }
1630
1631 public void unblockConversation(final Blockable conversation) {
1632 xmppConnectionService.sendUnblockRequest(conversation);
1633 }
1634
1635 public boolean enterIsSend() {
1636 return getPreferences().getBoolean("enter_is_send",false);
1637 }
1638
1639 @Override
1640 public void onShowErrorToast(final int resId) {
1641 runOnUiThread(new Runnable() {
1642 @Override
1643 public void run() {
1644 Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1645 }
1646 });
1647 }
1648
1649 public boolean highlightSelectedConversations() {
1650 return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1651 }
1652
1653 public void setMessagesLoaded() {
1654 if (mConversationFragment != null) {
1655 mConversationFragment.setMessagesLoaded();
1656 mConversationFragment.updateMessages();
1657 }
1658 }
1659}