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