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