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.FingerprintStatus;
53import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
54import eu.siacs.conversations.entities.Account;
55import eu.siacs.conversations.entities.Blockable;
56import eu.siacs.conversations.entities.Contact;
57import eu.siacs.conversations.entities.Conversation;
58import eu.siacs.conversations.entities.Message;
59import eu.siacs.conversations.entities.Transferable;
60import eu.siacs.conversations.persistance.FileBackend;
61import eu.siacs.conversations.services.XmppConnectionService;
62import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
63import eu.siacs.conversations.services.XmppConnectionService.OnConversationUpdate;
64import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
65import eu.siacs.conversations.ui.adapter.ConversationAdapter;
66import eu.siacs.conversations.utils.ExceptionHelper;
67import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
68import eu.siacs.conversations.xmpp.XmppConnection;
69import eu.siacs.conversations.xmpp.jid.InvalidJidException;
70import eu.siacs.conversations.xmpp.jid.Jid;
71
72public class ConversationActivity extends XmppActivity
73 implements OnAccountUpdate, OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast {
74
75 public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
76 public static final String CONVERSATION = "conversationUuid";
77 public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
78 public static final String TEXT = "text";
79 public static final String NICK = "nick";
80 public static final String PRIVATE_MESSAGE = "pm";
81
82 public static final int REQUEST_SEND_MESSAGE = 0x0201;
83 public static final int REQUEST_DECRYPT_PGP = 0x0202;
84 public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
85 public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
86 public static final int REQUEST_TRUST_KEYS_MENU = 0x0209;
87 public static final int REQUEST_START_DOWNLOAD = 0x0210;
88 public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
89 public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
90 public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
91 public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
92 public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
93 public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
94 private static final String STATE_OPEN_CONVERSATION = "state_open_conversation";
95 private static final String STATE_PANEL_OPEN = "state_panel_open";
96 private static final String STATE_PENDING_URI = "state_pending_uri";
97 private static final String STATE_FIRST_VISIBLE = "first_visible";
98 private static final String STATE_OFFSET_FROM_TOP = "offset_from_top";
99
100 private String mOpenConversation = null;
101 private boolean mPanelOpen = true;
102 private Pair<Integer,Integer> mScrollPosition = null;
103 final private List<Uri> mPendingImageUris = new ArrayList<>();
104 final private List<Uri> mPendingFileUris = new ArrayList<>();
105 private Uri mPendingGeoUri = null;
106 private boolean forbidProcessingPendings = false;
107 private Message mPendingDownloadableMessage = null;
108
109 private boolean conversationWasSelectedByKeyboard = false;
110
111 private View mContentView;
112
113 private List<Conversation> conversationList = new ArrayList<>();
114 private Conversation swipedConversation = null;
115 private Conversation mSelectedConversation = null;
116 private EnhancedListView listView;
117 private ConversationFragment mConversationFragment;
118
119 private ArrayAdapter<Conversation> listAdapter;
120
121 private boolean mActivityPaused = false;
122 private AtomicBoolean mRedirected = new AtomicBoolean(false);
123 private Pair<Integer, Intent> mPostponedActivityResult;
124 private boolean mUnprocessedNewIntent = false;
125
126 public Conversation getSelectedConversation() {
127 return this.mSelectedConversation;
128 }
129
130 public void setSelectedConversation(Conversation conversation) {
131 this.mSelectedConversation = conversation;
132 }
133
134 public void showConversationsOverview() {
135 if (mContentView instanceof SlidingPaneLayout) {
136 SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
137 mSlidingPaneLayout.openPane();
138 }
139 }
140
141 @Override
142 protected String getShareableUri() {
143 Conversation conversation = getSelectedConversation();
144 if (conversation != null) {
145 return conversation.getAccount().getShareableUri();
146 } else {
147 return "";
148 }
149 }
150
151 public void hideConversationsOverview() {
152 if (mContentView instanceof SlidingPaneLayout) {
153 SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
154 mSlidingPaneLayout.closePane();
155 }
156 }
157
158 public boolean isConversationsOverviewHideable() {
159 return mContentView instanceof SlidingPaneLayout;
160 }
161
162 public boolean isConversationsOverviewVisable() {
163 if (mContentView instanceof SlidingPaneLayout) {
164 SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
165 return mSlidingPaneLayout.isOpen();
166 } else {
167 return true;
168 }
169 }
170
171 @Override
172 protected void onCreate(final Bundle savedInstanceState) {
173 super.onCreate(savedInstanceState);
174 if (savedInstanceState != null) {
175 mOpenConversation = savedInstanceState.getString(STATE_OPEN_CONVERSATION, null);
176 mPanelOpen = savedInstanceState.getBoolean(STATE_PANEL_OPEN, true);
177 int pos = savedInstanceState.getInt(STATE_FIRST_VISIBLE, -1);
178 int offset = savedInstanceState.getInt(STATE_OFFSET_FROM_TOP, 1);
179 if (pos >= 0 && offset <= 0) {
180 Log.d(Config.LOGTAG,"retrieved scroll position from instanceState "+pos+":"+offset);
181 mScrollPosition = new Pair<>(pos,offset);
182 } else {
183 mScrollPosition = null;
184 }
185 String pending = savedInstanceState.getString(STATE_PENDING_URI, null);
186 if (pending != null) {
187 Log.d(Config.LOGTAG,"ConversationsActivity.onCreate() - restoring pending image uri");
188 mPendingImageUris.clear();
189 mPendingImageUris.add(Uri.parse(pending));
190 }
191 }
192
193 setContentView(R.layout.fragment_conversations_overview);
194
195 this.mConversationFragment = new ConversationFragment();
196 FragmentTransaction transaction = getFragmentManager().beginTransaction();
197 transaction.replace(R.id.selected_conversation, this.mConversationFragment, "conversation");
198 transaction.commit();
199
200 listView = (EnhancedListView) findViewById(R.id.list);
201 this.listAdapter = new ConversationAdapter(this, conversationList);
202 listView.setAdapter(this.listAdapter);
203
204 if (getActionBar() != null) {
205 getActionBar().setDisplayHomeAsUpEnabled(false);
206 getActionBar().setHomeButtonEnabled(false);
207 }
208
209 listView.setOnItemClickListener(new OnItemClickListener() {
210
211 @Override
212 public void onItemClick(AdapterView<?> arg0, View clickedView,
213 int position, long arg3) {
214 if (getSelectedConversation() != conversationList.get(position)) {
215 setSelectedConversation(conversationList.get(position));
216 ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
217 conversationWasSelectedByKeyboard = false;
218 }
219 hideConversationsOverview();
220 openConversation();
221 }
222 });
223
224 listView.setDismissCallback(new EnhancedListView.OnDismissCallback() {
225
226 @Override
227 public EnhancedListView.Undoable onDismiss(final EnhancedListView enhancedListView, final int position) {
228
229 final int index = listView.getFirstVisiblePosition();
230 View v = listView.getChildAt(0);
231 final int top = (v == null) ? 0 : (v.getTop() - listView.getPaddingTop());
232
233 try {
234 swipedConversation = listAdapter.getItem(position);
235 } catch (IndexOutOfBoundsException e) {
236 return null;
237 }
238 listAdapter.remove(swipedConversation);
239 xmppConnectionService.markRead(swipedConversation);
240
241 final boolean formerlySelected = (getSelectedConversation() == swipedConversation);
242 if (position == 0 && listAdapter.getCount() == 0) {
243 endConversation(swipedConversation, false, true);
244 return null;
245 } else if (formerlySelected) {
246 setSelectedConversation(listAdapter.getItem(0));
247 ConversationActivity.this.mConversationFragment
248 .reInit(getSelectedConversation());
249 }
250
251 return new EnhancedListView.Undoable() {
252
253 @Override
254 public void undo() {
255 listAdapter.insert(swipedConversation, position);
256 if (formerlySelected) {
257 setSelectedConversation(swipedConversation);
258 ConversationActivity.this.mConversationFragment
259 .reInit(getSelectedConversation());
260 }
261 swipedConversation = null;
262 listView.setSelectionFromTop(index + (listView.getChildCount() < position ? 1 : 0), top);
263 }
264
265 @Override
266 public void discard() {
267 if (!swipedConversation.isRead()
268 && swipedConversation.getMode() == Conversation.MODE_SINGLE) {
269 swipedConversation = null;
270 return;
271 }
272 endConversation(swipedConversation, false, false);
273 swipedConversation = null;
274 }
275
276 @Override
277 public String getTitle() {
278 if (swipedConversation.getMode() == Conversation.MODE_MULTI) {
279 return getResources().getString(R.string.title_undo_swipe_out_muc);
280 } else {
281 return getResources().getString(R.string.title_undo_swipe_out_conversation);
282 }
283 }
284 };
285 }
286 });
287 listView.enableSwipeToDismiss();
288 listView.setSwipingLayout(R.id.swipeable_item);
289 listView.setUndoStyle(EnhancedListView.UndoStyle.SINGLE_POPUP);
290 listView.setUndoHideDelay(5000);
291 listView.setRequireTouchBeforeDismiss(false);
292
293 mContentView = findViewById(R.id.content_view_spl);
294 if (mContentView == null) {
295 mContentView = findViewById(R.id.content_view_ll);
296 }
297 if (mContentView instanceof SlidingPaneLayout) {
298 SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
299 mSlidingPaneLayout.setShadowResource(R.drawable.es_slidingpane_shadow);
300 mSlidingPaneLayout.setSliderFadeColor(0);
301 mSlidingPaneLayout.setPanelSlideListener(new PanelSlideListener() {
302
303 @Override
304 public void onPanelOpened(View arg0) {
305 updateActionBarTitle();
306 invalidateOptionsMenu();
307 hideKeyboard();
308 if (xmppConnectionServiceBound) {
309 xmppConnectionService.getNotificationService()
310 .setOpenConversation(null);
311 }
312 closeContextMenu();
313 }
314
315 @Override
316 public void onPanelClosed(View arg0) {
317 listView.discardUndo();
318 openConversation();
319 }
320
321 @Override
322 public void onPanelSlide(View arg0, float arg1) {
323 // TODO Auto-generated method stub
324
325 }
326 });
327 }
328 }
329
330 @Override
331 public void switchToConversation(Conversation conversation) {
332 setSelectedConversation(conversation);
333 runOnUiThread(new Runnable() {
334 @Override
335 public void run() {
336 ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
337 openConversation();
338 }
339 });
340 }
341
342 private void updateActionBarTitle() {
343 updateActionBarTitle(isConversationsOverviewHideable() && !isConversationsOverviewVisable());
344 }
345
346 private void updateActionBarTitle(boolean titleShouldBeName) {
347 final ActionBar ab = getActionBar();
348 final Conversation conversation = getSelectedConversation();
349 if (ab != null) {
350 if (titleShouldBeName && conversation != null) {
351 ab.setDisplayHomeAsUpEnabled(true);
352 ab.setHomeButtonEnabled(true);
353 if (conversation.getMode() == Conversation.MODE_SINGLE || useSubjectToIdentifyConference()) {
354 ab.setTitle(conversation.getName());
355 } else {
356 ab.setTitle(conversation.getJid().toBareJid().toString());
357 }
358 } else {
359 ab.setDisplayHomeAsUpEnabled(false);
360 ab.setHomeButtonEnabled(false);
361 ab.setTitle(R.string.app_name);
362 }
363 }
364 }
365
366 private void openConversation() {
367 this.updateActionBarTitle();
368 this.invalidateOptionsMenu();
369 if (xmppConnectionServiceBound) {
370 final Conversation conversation = getSelectedConversation();
371 xmppConnectionService.getNotificationService().setOpenConversation(conversation);
372 sendReadMarkerIfNecessary(conversation);
373 }
374 listAdapter.notifyDataSetChanged();
375 }
376
377 public void sendReadMarkerIfNecessary(final Conversation conversation) {
378 if (!mActivityPaused && !mUnprocessedNewIntent && conversation != null) {
379 xmppConnectionService.sendReadMarker(conversation);
380 }
381 }
382
383 @Override
384 public boolean onCreateOptionsMenu(Menu menu) {
385 getMenuInflater().inflate(R.menu.conversations, menu);
386 final MenuItem menuSecure = menu.findItem(R.id.action_security);
387 final MenuItem menuArchive = menu.findItem(R.id.action_archive);
388 final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
389 final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
390 final MenuItem menuAttach = menu.findItem(R.id.action_attach_file);
391 final MenuItem menuClearHistory = menu.findItem(R.id.action_clear_history);
392 final MenuItem menuAdd = menu.findItem(R.id.action_add);
393 final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
394 final MenuItem menuMute = menu.findItem(R.id.action_mute);
395 final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
396
397 if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
398 menuArchive.setVisible(false);
399 menuMucDetails.setVisible(false);
400 menuContactDetails.setVisible(false);
401 menuSecure.setVisible(false);
402 menuInviteContact.setVisible(false);
403 menuAttach.setVisible(false);
404 menuClearHistory.setVisible(false);
405 menuMute.setVisible(false);
406 menuUnmute.setVisible(false);
407 } else {
408 menuAdd.setVisible(!isConversationsOverviewHideable());
409 if (this.getSelectedConversation() != null) {
410 if (this.getSelectedConversation().getNextEncryption() != Message.ENCRYPTION_NONE) {
411 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
412 menuSecure.setIcon(R.drawable.ic_lock_white_24dp);
413 } else {
414 menuSecure.setIcon(R.drawable.ic_action_secure);
415 }
416 }
417 if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
418 menuContactDetails.setVisible(false);
419 menuAttach.setVisible(getSelectedConversation().getAccount().httpUploadAvailable() && getSelectedConversation().getMucOptions().participating());
420 menuInviteContact.setVisible(getSelectedConversation().getMucOptions().canInvite());
421 menuSecure.setVisible((Config.supportOpenPgp() || Config.supportOmemo()) && Config.multipleEncryptionChoices()); //only if pgp is supported we have a choice
422 } else {
423 menuContactDetails.setVisible(!this.getSelectedConversation().withSelf());
424 menuMucDetails.setVisible(false);
425 menuSecure.setVisible(Config.multipleEncryptionChoices());
426 }
427 if (this.getSelectedConversation().isMuted()) {
428 menuMute.setVisible(false);
429 } else {
430 menuUnmute.setVisible(false);
431 }
432 }
433 }
434 if (Config.supportOmemo()) {
435 new Handler().post(new Runnable() {
436 @Override
437 public void run() {
438 View view = findViewById(R.id.action_security);
439 if (view != null) {
440 view.setOnLongClickListener(new View.OnLongClickListener() {
441 @Override
442 public boolean onLongClick(View v) {
443 return quickOmemoDebugger(getSelectedConversation());
444 }
445 });
446 }
447 }
448 });
449 }
450 return super.onCreateOptionsMenu(menu);
451 }
452
453 private boolean quickOmemoDebugger(Conversation c) {
454 if (c != null) {
455 boolean single = c.getMode() == Conversation.MODE_SINGLE;
456 AxolotlService axolotlService = c.getAccount().getAxolotlService();
457 Pair<AxolotlService.AxolotlCapability,Jid> capabilityJidPair = axolotlService.isConversationAxolotlCapableDetailed(c);
458 switch (capabilityJidPair.first) {
459 case MISSING_PRESENCE:
460 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();
461 return true;
462 case MISSING_KEYS:
463 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();
464 return true;
465 case WRONG_CONFIGURATION:
466 Toast.makeText(ConversationActivity.this,R.string.wrong_conference_configuration, Toast.LENGTH_SHORT).show();
467 return true;
468 case NO_MEMBERS:
469 Toast.makeText(ConversationActivity.this,R.string.this_conference_has_no_members, Toast.LENGTH_SHORT).show();
470 return true;
471 }
472 }
473 return false;
474 }
475
476 protected void selectPresenceToAttachFile(final int attachmentChoice, final int encryption) {
477 final Conversation conversation = getSelectedConversation();
478 final Account account = conversation.getAccount();
479 final OnPresenceSelected callback = new OnPresenceSelected() {
480
481 @Override
482 public void onPresenceSelected() {
483 Intent intent = new Intent();
484 boolean chooser = false;
485 String fallbackPackageId = null;
486 switch (attachmentChoice) {
487 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
488 intent.setAction(Intent.ACTION_GET_CONTENT);
489 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
490 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
491 }
492 intent.setType("image/*");
493 chooser = true;
494 break;
495 case ATTACHMENT_CHOICE_TAKE_PHOTO:
496 Uri uri = xmppConnectionService.getFileBackend().getTakePhotoUri();
497 intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
498 intent.addFlags(Intent.FLAG_GRANT_READ_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 (!Config.ONLY_INTERNAL_STORAGE && !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 (!Config.ONLY_INTERNAL_STORAGE && !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 if (!Config.ONLY_INTERNAL_STORAGE) {
1420 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1421 intent.setData(uri);
1422 sendBroadcast(intent);
1423 }
1424 } else {
1425 mPendingImageUris.clear();
1426 }
1427 } else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1428 double latitude = data.getDoubleExtra("latitude", 0);
1429 double longitude = data.getDoubleExtra("longitude", 0);
1430 this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1431 if (xmppConnectionServiceBound) {
1432 attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1433 this.mPendingGeoUri = null;
1434 }
1435 } else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1436 this.forbidProcessingPendings = !xmppConnectionServiceBound;
1437 if (xmppConnectionServiceBound) {
1438 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1439 this.mPostponedActivityResult = null;
1440 } else {
1441 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1442 }
1443
1444 }
1445 } else {
1446 mPendingImageUris.clear();
1447 mPendingFileUris.clear();
1448 if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1449 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1450 }
1451 if (requestCode == REQUEST_BATTERY_OP) {
1452 setNeverAskForBatteryOptimizationsAgain();
1453 }
1454 }
1455 }
1456
1457 private long getMaxHttpUploadSize(Conversation conversation) {
1458 final XmppConnection connection = conversation.getAccount().getXmppConnection();
1459 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
1460 }
1461
1462 private void setNeverAskForBatteryOptimizationsAgain() {
1463 getPreferences().edit().putBoolean("show_battery_optimization", false).commit();
1464 }
1465
1466 private void openBatteryOptimizationDialogIfNeeded() {
1467 if (hasAccountWithoutPush()
1468 && isOptimizingBattery()
1469 && getPreferences().getBoolean("show_battery_optimization", true)) {
1470 AlertDialog.Builder builder = new AlertDialog.Builder(this);
1471 builder.setTitle(R.string.battery_optimizations_enabled);
1472 builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1473 builder.setPositiveButton(R.string.next, new OnClickListener() {
1474 @Override
1475 public void onClick(DialogInterface dialog, int which) {
1476 Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1477 Uri uri = Uri.parse("package:" + getPackageName());
1478 intent.setData(uri);
1479 try {
1480 startActivityForResult(intent, REQUEST_BATTERY_OP);
1481 } catch (ActivityNotFoundException e) {
1482 Toast.makeText(ConversationActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1483 }
1484 }
1485 });
1486 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1487 builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1488 @Override
1489 public void onDismiss(DialogInterface dialog) {
1490 setNeverAskForBatteryOptimizationsAgain();
1491 }
1492 });
1493 }
1494 builder.create().show();
1495 }
1496 }
1497
1498 private boolean hasAccountWithoutPush() {
1499 for(Account account : xmppConnectionService.getAccounts()) {
1500 if (account.getStatus() != Account.State.DISABLED
1501 && !xmppConnectionService.getPushManagementService().availableAndUseful(account)) {
1502 return true;
1503 }
1504 }
1505 return false;
1506 }
1507
1508 private void attachLocationToConversation(Conversation conversation, Uri uri) {
1509 if (conversation == null) {
1510 return;
1511 }
1512 xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1513
1514 @Override
1515 public void success(Message message) {
1516 xmppConnectionService.sendMessage(message);
1517 }
1518
1519 @Override
1520 public void error(int errorCode, Message object) {
1521
1522 }
1523
1524 @Override
1525 public void userInputRequried(PendingIntent pi, Message object) {
1526
1527 }
1528 });
1529 }
1530
1531 private void attachFileToConversation(Conversation conversation, Uri uri) {
1532 if (conversation == null) {
1533 return;
1534 }
1535 final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1536 prepareFileToast.show();
1537 xmppConnectionService.attachFileToConversation(conversation, uri, new UiCallback<Message>() {
1538 @Override
1539 public void success(Message message) {
1540 hidePrepareFileToast(prepareFileToast);
1541 xmppConnectionService.sendMessage(message);
1542 }
1543
1544 @Override
1545 public void error(final int errorCode, Message message) {
1546 hidePrepareFileToast(prepareFileToast);
1547 runOnUiThread(new Runnable() {
1548 @Override
1549 public void run() {
1550 replaceToast(getString(errorCode));
1551 }
1552 });
1553
1554 }
1555
1556 @Override
1557 public void userInputRequried(PendingIntent pi, Message message) {
1558 hidePrepareFileToast(prepareFileToast);
1559 }
1560 });
1561 }
1562
1563 public void attachImageToConversation(Uri uri) {
1564 this.attachImageToConversation(getSelectedConversation(), uri);
1565 }
1566
1567 private void attachImageToConversation(Conversation conversation, Uri uri) {
1568 if (conversation == null) {
1569 return;
1570 }
1571 final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1572 prepareFileToast.show();
1573 xmppConnectionService.attachImageToConversation(conversation, uri,
1574 new UiCallback<Message>() {
1575
1576 @Override
1577 public void userInputRequried(PendingIntent pi, Message object) {
1578 hidePrepareFileToast(prepareFileToast);
1579 }
1580
1581 @Override
1582 public void success(Message message) {
1583 hidePrepareFileToast(prepareFileToast);
1584 xmppConnectionService.sendMessage(message);
1585 }
1586
1587 @Override
1588 public void error(final int error, Message message) {
1589 hidePrepareFileToast(prepareFileToast);
1590 runOnUiThread(new Runnable() {
1591 @Override
1592 public void run() {
1593 replaceToast(getString(error));
1594 }
1595 });
1596 }
1597 });
1598 }
1599
1600 private void hidePrepareFileToast(final Toast prepareFileToast) {
1601 if (prepareFileToast != null) {
1602 runOnUiThread(new Runnable() {
1603
1604 @Override
1605 public void run() {
1606 prepareFileToast.cancel();
1607 }
1608 });
1609 }
1610 }
1611
1612 public void updateConversationList() {
1613 xmppConnectionService
1614 .populateWithOrderedConversations(conversationList);
1615 if (swipedConversation != null) {
1616 if (swipedConversation.isRead()) {
1617 conversationList.remove(swipedConversation);
1618 } else {
1619 listView.discardUndo();
1620 }
1621 }
1622 listAdapter.notifyDataSetChanged();
1623 }
1624
1625 public void runIntent(PendingIntent pi, int requestCode) {
1626 try {
1627 this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1628 null, 0, 0, 0);
1629 } catch (final SendIntentException ignored) {
1630 }
1631 }
1632
1633 public void encryptTextMessage(Message message) {
1634 xmppConnectionService.getPgpEngine().encrypt(message,
1635 new UiCallback<Message>() {
1636
1637 @Override
1638 public void userInputRequried(PendingIntent pi,Message message) {
1639 ConversationActivity.this.runIntent(pi,ConversationActivity.REQUEST_SEND_MESSAGE);
1640 }
1641
1642 @Override
1643 public void success(Message message) {
1644 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1645 xmppConnectionService.sendMessage(message);
1646 if (mConversationFragment != null) {
1647 mConversationFragment.messageSent();
1648 }
1649 }
1650
1651 @Override
1652 public void error(final int error, Message message) {
1653 runOnUiThread(new Runnable() {
1654 @Override
1655 public void run() {
1656 Toast.makeText(ConversationActivity.this,
1657 R.string.unable_to_connect_to_keychain,
1658 Toast.LENGTH_SHORT
1659 ).show();
1660 }
1661 });
1662 }
1663 });
1664 }
1665
1666 public boolean useSendButtonToIndicateStatus() {
1667 return getPreferences().getBoolean("send_button_status", false);
1668 }
1669
1670 public boolean indicateReceived() {
1671 return getPreferences().getBoolean("indicate_received", false);
1672 }
1673
1674 public boolean useGreenBackground() {
1675 return getPreferences().getBoolean("use_green_background",true);
1676 }
1677
1678 protected boolean trustKeysIfNeeded(int requestCode) {
1679 return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1680 }
1681
1682 protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1683 AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1684 final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1685 boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1686 boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided()).isEmpty();
1687 boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets).isEmpty();
1688 boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1689 boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1690 if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1691 axolotlService.createSessionsIfNeeded(mSelectedConversation);
1692 Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1693 String[] contacts = new String[targets.size()];
1694 for(int i = 0; i < contacts.length; ++i) {
1695 contacts[i] = targets.get(i).toString();
1696 }
1697 intent.putExtra("contacts", contacts);
1698 intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1699 intent.putExtra("choice", attachmentChoice);
1700 intent.putExtra("conversation",mSelectedConversation.getUuid());
1701 startActivityForResult(intent, requestCode);
1702 return true;
1703 } else {
1704 return false;
1705 }
1706 }
1707
1708 @Override
1709 protected void refreshUiReal() {
1710 updateConversationList();
1711 if (conversationList.size() > 0) {
1712 if (!this.mConversationFragment.isAdded()) {
1713 Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1714 }
1715 ConversationActivity.this.mConversationFragment.updateMessages();
1716 updateActionBarTitle();
1717 invalidateOptionsMenu();
1718 } else {
1719 Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1720 }
1721 }
1722
1723 @Override
1724 public void onAccountUpdate() {
1725 this.refreshUi();
1726 }
1727
1728 @Override
1729 public void onConversationUpdate() {
1730 this.refreshUi();
1731 }
1732
1733 @Override
1734 public void onRosterUpdate() {
1735 this.refreshUi();
1736 }
1737
1738 @Override
1739 public void OnUpdateBlocklist(Status status) {
1740 this.refreshUi();
1741 }
1742
1743 public void unblockConversation(final Blockable conversation) {
1744 xmppConnectionService.sendUnblockRequest(conversation);
1745 }
1746
1747 public boolean enterIsSend() {
1748 return getPreferences().getBoolean("enter_is_send",false);
1749 }
1750
1751 @Override
1752 public void onShowErrorToast(final int resId) {
1753 runOnUiThread(new Runnable() {
1754 @Override
1755 public void run() {
1756 Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1757 }
1758 });
1759 }
1760
1761 public boolean highlightSelectedConversations() {
1762 return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1763 }
1764
1765 public void setMessagesLoaded() {
1766 if (mConversationFragment != null) {
1767 mConversationFragment.setMessagesLoaded();
1768 mConversationFragment.updateMessages();
1769 }
1770 }
1771}