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