1/*
2 * Copyright (c) 2018, Daniel Gultsch All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without modification,
5 * are permitted provided that the following conditions are met:
6 *
7 * 1. Redistributions of source code must retain the above copyright notice, this
8 * list of conditions and the following disclaimer.
9 *
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation and/or
12 * other materials provided with the distribution.
13 *
14 * 3. Neither the name of the copyright holder nor the names of its contributors
15 * may be used to endorse or promote products derived from this software without
16 * specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
22 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30package eu.siacs.conversations.ui;
31
32
33import android.annotation.SuppressLint;
34import android.app.Fragment;
35import android.app.FragmentManager;
36import android.app.FragmentTransaction;
37import android.content.ActivityNotFoundException;
38import android.content.Context;
39import android.content.Intent;
40import android.databinding.DataBindingUtil;
41import android.net.Uri;
42import android.os.Build;
43import android.os.Bundle;
44import android.provider.Settings;
45import android.support.annotation.IdRes;
46import android.support.v7.app.ActionBar;
47import android.support.v7.app.AlertDialog;
48import android.util.Log;
49import android.view.Menu;
50import android.view.MenuItem;
51import android.widget.Toast;
52
53import java.util.concurrent.atomic.AtomicBoolean;
54
55import eu.siacs.conversations.Config;
56import eu.siacs.conversations.R;
57import eu.siacs.conversations.databinding.ActivityConversationsBinding;
58import eu.siacs.conversations.entities.Account;
59import eu.siacs.conversations.entities.Conversation;
60import eu.siacs.conversations.services.XmppConnectionService;
61import eu.siacs.conversations.ui.interfaces.OnConversationArchived;
62import eu.siacs.conversations.ui.interfaces.OnConversationRead;
63import eu.siacs.conversations.ui.interfaces.OnConversationSelected;
64import eu.siacs.conversations.ui.interfaces.OnConversationsListItemUpdated;
65import eu.siacs.conversations.ui.service.EmojiService;
66import eu.siacs.conversations.ui.util.PendingItem;
67import eu.siacs.conversations.utils.ExceptionHelper;
68import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
69
70import static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP;
71
72public class ConversationActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast {
73
74 public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
75 public static final String EXTRA_CONVERSATION = "conversationUuid";
76 public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
77 public static final String EXTRA_TEXT = "text";
78 public static final String EXTRA_NICK = "nick";
79 public static final String EXTRA_IS_PRIVATE_MESSAGE = "pm";
80
81
82 //secondary fragment (when holding the conversation, must be initialized before refreshing the overview fragment
83 private static final @IdRes
84 int[] FRAGMENT_ID_NOTIFICATION_ORDER = {R.id.secondary_fragment, R.id.main_fragment};
85 private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
86 private ActivityConversationsBinding binding;
87 private boolean mActivityPaused = true;
88 private AtomicBoolean mRedirectInProcess = new AtomicBoolean(false);
89
90 private static boolean isViewIntent(Intent i) {
91 return i != null && ACTION_VIEW_CONVERSATION.equals(i.getAction()) && i.hasExtra(EXTRA_CONVERSATION);
92 }
93
94 private static Intent createLauncherIntent(Context context) {
95 final Intent intent = new Intent(context, ConversationActivity.class);
96 intent.setAction(Intent.ACTION_MAIN);
97 intent.addCategory(Intent.CATEGORY_LAUNCHER);
98 return intent;
99 }
100
101 @Override
102 protected void refreshUiReal() {
103 for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
104 refreshFragment(id);
105 }
106 }
107
108 @Override
109 void onBackendConnected() {
110 if (performRedirectIfNecessary(true)) {
111 return;
112 }
113 xmppConnectionService.getNotificationService().setIsInForeground(true);
114 Intent intent = pendingViewIntent.pop();
115 if (intent != null) {
116 if (processViewIntent(intent)) {
117 if (binding.secondaryFragment != null) {
118 notifyFragmentOfBackendConnected(R.id.main_fragment);
119 }
120 invalidateActionBarTitle();
121 return;
122 }
123 }
124 for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
125 notifyFragmentOfBackendConnected(id);
126 }
127 invalidateActionBarTitle();
128 if (binding.secondaryFragment != null && ConversationFragment.getConversation(this) == null) {
129 Conversation conversation = ConversationsOverviewFragment.getSuggestion(this);
130 if (conversation != null) {
131 openConversation(conversation, null);
132 }
133 }
134 showDialogsIfMainIsOverview();
135 }
136
137 private boolean performRedirectIfNecessary(boolean noAnimation) {
138 return performRedirectIfNecessary(null, noAnimation);
139 }
140
141 private boolean performRedirectIfNecessary(final Conversation ignore, final boolean noAnimation) {
142 if (xmppConnectionService == null) {
143 return false;
144 }
145 boolean isConversationsListEmpty = xmppConnectionService.isConversationsListEmpty(ignore);
146 if (isConversationsListEmpty && mRedirectInProcess.compareAndSet(false, true)) {
147 final Intent intent = getRedirectionIntent(noAnimation);
148 runOnUiThread(() -> {
149 startActivity(intent);
150 if (noAnimation) {
151 overridePendingTransition(0, 0);
152 }
153 });
154 }
155 return mRedirectInProcess.get();
156 }
157
158 private Intent getRedirectionIntent(boolean noAnimation) {
159 Account pendingAccount = xmppConnectionService.getPendingAccount();
160 Intent intent;
161 if (pendingAccount != null) {
162 intent = new Intent(this, EditAccountActivity.class);
163 intent.putExtra("jid", pendingAccount.getJid().toBareJid().toString());
164 } else {
165 if (xmppConnectionService.getAccounts().size() == 0) {
166 if (Config.X509_VERIFICATION) {
167 intent = new Intent(this, ManageAccountActivity.class);
168 } else if (Config.MAGIC_CREATE_DOMAIN != null) {
169 intent = new Intent(this, WelcomeActivity.class);
170 WelcomeActivity.addInviteUri(intent, getIntent());
171 } else {
172 intent = new Intent(this, EditAccountActivity.class);
173 }
174 } else {
175 intent = new Intent(this, StartConversationActivity.class);
176 }
177 }
178 intent.putExtra("init", true);
179 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
180 if (noAnimation) {
181 intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
182 }
183 return intent;
184 }
185
186 private void showDialogsIfMainIsOverview() {
187 if (xmppConnectionService == null) {
188 return;
189 }
190 final Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
191 if (fragment != null && fragment instanceof ConversationsOverviewFragment) {
192 if (ExceptionHelper.checkForCrash(this)) {
193 return;
194 }
195 openBatteryOptimizationDialogIfNeeded();
196 }
197 }
198
199 private String getBatteryOptimizationPreferenceKey() {
200 @SuppressLint("HardwareIds") String device = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
201 return "show_battery_optimization" + (device == null ? "" : device);
202 }
203
204 private void setNeverAskForBatteryOptimizationsAgain() {
205 getPreferences().edit().putBoolean(getBatteryOptimizationPreferenceKey(), false).apply();
206 }
207
208 private void openBatteryOptimizationDialogIfNeeded() {
209 if (hasAccountWithoutPush()
210 && isOptimizingBattery()
211 && getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
212 AlertDialog.Builder builder = new AlertDialog.Builder(this);
213 builder.setTitle(R.string.battery_optimizations_enabled);
214 builder.setMessage(R.string.battery_optimizations_enabled_dialog);
215 builder.setPositiveButton(R.string.next, (dialog, which) -> {
216 Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
217 Uri uri = Uri.parse("package:" + getPackageName());
218 intent.setData(uri);
219 try {
220 startActivityForResult(intent, REQUEST_BATTERY_OP);
221 } catch (ActivityNotFoundException e) {
222 Toast.makeText(this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
223 }
224 });
225 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
226 builder.setOnDismissListener(dialog -> setNeverAskForBatteryOptimizationsAgain());
227 }
228 AlertDialog dialog = builder.create();
229 dialog.setCanceledOnTouchOutside(false);
230 dialog.show();
231 }
232 }
233
234 private boolean hasAccountWithoutPush() {
235 for (Account account : xmppConnectionService.getAccounts()) {
236 if (account.getStatus() == Account.State.ONLINE && !xmppConnectionService.getPushManagementService().available(account)) {
237 return true;
238 }
239 }
240 return false;
241 }
242
243 private void notifyFragmentOfBackendConnected(@IdRes int id) {
244 final Fragment fragment = getFragmentManager().findFragmentById(id);
245 if (fragment != null && fragment instanceof XmppFragment) {
246 ((XmppFragment) fragment).onBackendConnected();
247 }
248 }
249
250 private void refreshFragment(@IdRes int id) {
251 final Fragment fragment = getFragmentManager().findFragmentById(id);
252 if (fragment != null && fragment instanceof XmppFragment) {
253 ((XmppFragment) fragment).refresh();
254 }
255 }
256
257 private boolean processViewIntent(Intent intent) {
258 Log.d(Config.LOGTAG,"process view intent");
259 String uuid = intent.getStringExtra(EXTRA_CONVERSATION);
260 Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null;
261 if (conversation == null) {
262 Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid);
263 return false;
264 }
265 openConversation(conversation, intent.getExtras());
266 return true;
267 }
268
269 @Override
270 public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
271 UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults);
272 }
273
274 @Override
275 public void onActivityResult(int requestCode, int resultCode, final Intent data) {
276 if (resultCode == RESULT_OK) {
277 handlePositiveActivityResult(requestCode, data);
278 } else {
279 handleNegativeActivityResult(requestCode);
280 }
281 }
282
283 private void handleNegativeActivityResult(int requestCode) {
284 switch (requestCode) {
285 case REQUEST_DECRYPT_PGP:
286 Conversation conversation = ConversationFragment.getConversationReliable(this);
287 if (conversation == null) {
288 break;
289 }
290 conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
291 break;
292 case REQUEST_BATTERY_OP:
293 setNeverAskForBatteryOptimizationsAgain();
294 break;
295 }
296 }
297
298 private void handlePositiveActivityResult(int requestCode, final Intent data) {
299 switch (requestCode) {
300 case REQUEST_DECRYPT_PGP:
301 Conversation conversation = ConversationFragment.getConversationReliable(this);
302 if (conversation == null) {
303 break;
304 }
305 conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
306 break;
307 }
308 }
309
310 @Override
311 protected void onCreate(final Bundle savedInstanceState) {
312 super.onCreate(savedInstanceState);
313 new EmojiService(this).init();
314 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
315 this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
316 this.getFragmentManager().addOnBackStackChangedListener(this::showDialogsIfMainIsOverview);
317 this.initializeFragments();
318 this.invalidateActionBarTitle();
319 final Intent intent;
320 if (savedInstanceState == null) {
321 intent = getIntent();
322 } else {
323 intent = savedInstanceState.getParcelable("intent");
324 }
325 if (isViewIntent(intent)) {
326 pendingViewIntent.push(intent);
327 setIntent(createLauncherIntent(this));
328 }
329 }
330
331 @Override
332 public boolean onCreateOptionsMenu(Menu menu) {
333 getMenuInflater().inflate(R.menu.activity_conversations, menu);
334 MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
335 if (qrCodeScanMenuItem != null) {
336 Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
337 boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
338 && fragment != null
339 && fragment instanceof ConversationsOverviewFragment;
340 qrCodeScanMenuItem.setVisible(visible);
341 }
342 return super.onCreateOptionsMenu(menu);
343 }
344
345 @Override
346 public void onConversationSelected(Conversation conversation) {
347 if (ConversationFragment.getConversation(this) == conversation) {
348 Log.d(Config.LOGTAG,"ignore onConversationSelected() because conversation is already open");
349 return;
350 }
351 openConversation(conversation, null);
352 }
353
354 private void openConversation(Conversation conversation, Bundle extras) {
355 ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment);
356 final boolean mainNeedsRefresh;
357 if (conversationFragment == null) {
358 mainNeedsRefresh = false;
359 Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
360 if (mainFragment != null && mainFragment instanceof ConversationFragment) {
361 conversationFragment = (ConversationFragment) mainFragment;
362 } else {
363 conversationFragment = new ConversationFragment();
364 FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
365 fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
366 fragmentTransaction.addToBackStack(null);
367 fragmentTransaction.commit();
368 }
369 } else {
370 mainNeedsRefresh = true;
371 }
372 conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras);
373 if (mainNeedsRefresh) {
374 refreshFragment(R.id.main_fragment);
375 } else {
376 invalidateActionBarTitle();
377 }
378 }
379
380 @Override
381 public boolean onOptionsItemSelected(MenuItem item) {
382 switch (item.getItemId()) {
383 case android.R.id.home:
384 FragmentManager fm = getFragmentManager();
385 if (fm.getBackStackEntryCount() > 0) {
386 fm.popBackStack();
387 return true;
388 }
389 break;
390 case R.id.action_scan_qr_code:
391 UriHandlerActivity.scan(this);
392 return true;
393 }
394 return super.onOptionsItemSelected(item);
395 }
396
397 @Override
398 public void onSaveInstanceState(Bundle savedInstanceState) {
399 Intent pendingIntent = pendingViewIntent.pop();
400 savedInstanceState.putParcelable("intent", pendingIntent == null ? pendingIntent : getIntent());
401 super.onSaveInstanceState(savedInstanceState);
402 }
403
404 @Override
405 protected void onStart() {
406 final int theme = findTheme();
407 if (this.mTheme != theme) {
408 this.mSkipBackgroundBinding = true;
409 recreate();
410 } else {
411 this.mSkipBackgroundBinding = false;
412 }
413 mRedirectInProcess.set(false);
414 super.onStart();
415 }
416
417 @Override
418 protected void onNewIntent(final Intent intent) {
419 if (isViewIntent(intent)) {
420 if (xmppConnectionService != null) {
421 processViewIntent(intent);
422 } else {
423 pendingViewIntent.push(intent);
424 }
425 }
426 setIntent(createLauncherIntent(this));
427 }
428
429 @Override
430 public void onPause() {
431 this.mActivityPaused = true;
432 super.onPause();
433 }
434
435 @Override
436 public void onResume() {
437 super.onResume();
438 this.mActivityPaused = false;
439 }
440
441 private void initializeFragments() {
442 FragmentTransaction transaction = getFragmentManager().beginTransaction();
443 Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
444 Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
445 if (mainFragment != null) {
446 Log.d(Config.LOGTAG, "initializeFragment(). main fragment exists");
447 if (binding.secondaryFragment != null) {
448 if (mainFragment instanceof ConversationFragment) {
449 Log.d(Config.LOGTAG, "gained secondary fragment. moving...");
450 getFragmentManager().popBackStack();
451 transaction.remove(mainFragment);
452 transaction.commit();
453 getFragmentManager().executePendingTransactions();
454 transaction = getFragmentManager().beginTransaction();
455 transaction.replace(R.id.secondary_fragment, mainFragment);
456 transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
457 transaction.commit();
458 return;
459 }
460 } else {
461 if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
462 Log.d(Config.LOGTAG, "lost secondary fragment. moving...");
463 transaction.remove(secondaryFragment);
464 transaction.commit();
465 getFragmentManager().executePendingTransactions();
466 transaction = getFragmentManager().beginTransaction();
467 transaction.replace(R.id.main_fragment, secondaryFragment);
468 transaction.addToBackStack(null);
469 transaction.commit();
470 return;
471 }
472 }
473 } else {
474 transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
475 }
476 if (binding.secondaryFragment != null && secondaryFragment == null) {
477 transaction.replace(R.id.secondary_fragment, new ConversationFragment());
478 }
479 transaction.commit();
480 }
481
482 private void invalidateActionBarTitle() {
483 final ActionBar actionBar = getSupportActionBar();
484 if (actionBar != null) {
485 Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
486 if (mainFragment != null && mainFragment instanceof ConversationFragment) {
487 final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
488 if (conversation != null) {
489 actionBar.setTitle(conversation.getName());
490 actionBar.setDisplayHomeAsUpEnabled(true);
491 return;
492 }
493 }
494 actionBar.setTitle(R.string.app_name);
495 actionBar.setDisplayHomeAsUpEnabled(false);
496 }
497 }
498
499 @Override
500 public void onConversationArchived(Conversation conversation) {
501 if (performRedirectIfNecessary(conversation, false)) {
502 return;
503 }
504 Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
505 if (mainFragment != null && mainFragment instanceof ConversationFragment) {
506 getFragmentManager().popBackStack();
507 return;
508 }
509 Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
510 if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
511 if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
512 Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
513 if (suggestion != null) {
514 openConversation(suggestion, null);
515 return;
516 }
517 }
518 }
519 }
520
521 @Override
522 public void onConversationsListItemUpdated() {
523 Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
524 if (fragment != null && fragment instanceof ConversationsOverviewFragment) {
525 ((ConversationsOverviewFragment) fragment).refresh();
526 }
527 }
528
529 @Override
530 public void onConversationRead(Conversation conversation) {
531 if (!mActivityPaused && pendingViewIntent.peek() == null) {
532 xmppConnectionService.sendReadMarker(conversation);
533 } else {
534 Log.d(Config.LOGTAG,"ignoring read callback. mActivityPaused="+Boolean.toString(mActivityPaused));
535 }
536 }
537
538 @Override
539 public void onAccountUpdate() {
540 this.refreshUi();
541 }
542
543 @Override
544 public void onConversationUpdate() {
545 if (performRedirectIfNecessary(false)) {
546 return;
547 }
548 this.refreshUi();
549 }
550
551 @Override
552 public void onRosterUpdate() {
553 this.refreshUi();
554 }
555
556 @Override
557 public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
558 this.refreshUi();
559 }
560
561 @Override
562 public void onShowErrorToast(int resId) {
563 runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
564 }
565}