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