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