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