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