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