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 Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
188 if (fragment != null && fragment instanceof ConversationsOverviewFragment) {
189 if (ExceptionHelper.checkForCrash(this, this.xmppConnectionService)) {
190 return;
191 }
192 openBatteryOptimizationDialogIfNeeded();
193 }
194 }
195
196 private String getBatteryOptimizationPreferenceKey() {
197 @SuppressLint("HardwareIds") String device = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
198 return "show_battery_optimization" + (device == null ? "" : device);
199 }
200
201 private void setNeverAskForBatteryOptimizationsAgain() {
202 getPreferences().edit().putBoolean(getBatteryOptimizationPreferenceKey(), false).apply();
203 }
204
205 private void openBatteryOptimizationDialogIfNeeded() {
206 if (hasAccountWithoutPush()
207 && isOptimizingBattery()
208 && getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
209 AlertDialog.Builder builder = new AlertDialog.Builder(this);
210 builder.setTitle(R.string.battery_optimizations_enabled);
211 builder.setMessage(R.string.battery_optimizations_enabled_dialog);
212 builder.setPositiveButton(R.string.next, (dialog, which) -> {
213 Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
214 Uri uri = Uri.parse("package:" + getPackageName());
215 intent.setData(uri);
216 try {
217 startActivityForResult(intent, REQUEST_BATTERY_OP);
218 } catch (ActivityNotFoundException e) {
219 Toast.makeText(this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
220 }
221 });
222 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
223 builder.setOnDismissListener(dialog -> setNeverAskForBatteryOptimizationsAgain());
224 }
225 AlertDialog dialog = builder.create();
226 dialog.setCanceledOnTouchOutside(false);
227 dialog.show();
228 }
229 }
230
231 private boolean hasAccountWithoutPush() {
232 for (Account account : xmppConnectionService.getAccounts()) {
233 if (account.getStatus() == Account.State.ONLINE && !xmppConnectionService.getPushManagementService().available(account)) {
234 return true;
235 }
236 }
237 return false;
238 }
239
240 private void notifyFragmentOfBackendConnected(@IdRes int id) {
241 final Fragment fragment = getFragmentManager().findFragmentById(id);
242 if (fragment != null && fragment instanceof XmppFragment) {
243 ((XmppFragment) fragment).onBackendConnected();
244 }
245 }
246
247 private void refreshFragment(@IdRes int id) {
248 final Fragment fragment = getFragmentManager().findFragmentById(id);
249 if (fragment != null && fragment instanceof XmppFragment) {
250 ((XmppFragment) fragment).refresh();
251 }
252 }
253
254 private boolean processViewIntent(Intent intent) {
255 String uuid = intent.getStringExtra(EXTRA_CONVERSATION);
256 Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null;
257 if (conversation == null) {
258 Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid);
259 return false;
260 }
261 openConversation(conversation, intent.getExtras());
262 return true;
263 }
264
265 @Override
266 public void onActivityResult(int requestCode, int resultCode, final Intent data) {
267 Log.d(Config.LOGTAG,"on activity result");
268 if (resultCode == RESULT_OK) {
269 handlePositiveActivityResult(requestCode, data);
270 } else {
271 handleNegativeActivityResult(requestCode);
272 }
273 }
274
275 private void handleNegativeActivityResult(int requestCode) {
276 switch (requestCode) {
277 case REQUEST_DECRYPT_PGP:
278 Conversation conversation = ConversationFragment.getConversationReliable(this);
279 if (conversation == null) {
280 break;
281 }
282 conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
283 break;
284 case REQUEST_BATTERY_OP:
285 setNeverAskForBatteryOptimizationsAgain();
286 break;
287 }
288 }
289
290 private void handlePositiveActivityResult(int requestCode, final Intent data) {
291 switch (requestCode) {
292 case REQUEST_DECRYPT_PGP:
293 Conversation conversation = ConversationFragment.getConversationReliable(this);
294 if (conversation == null) {
295 break;
296 }
297 conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
298 break;
299 }
300 }
301
302 @Override
303 protected void onCreate(final Bundle savedInstanceState) {
304 super.onCreate(savedInstanceState);
305 new EmojiService(this).init();
306 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
307 this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
308 this.getFragmentManager().addOnBackStackChangedListener(this::showDialogsIfMainIsOverview);
309 this.initializeFragments();
310 this.invalidateActionBarTitle();
311 final Intent intent = getIntent();
312 if (isViewIntent(intent)) {
313 pendingViewIntent.push(intent);
314 setIntent(createLauncherIntent(this));
315 }
316 }
317
318 @Override
319 public boolean onCreateOptionsMenu(Menu menu) {
320 getMenuInflater().inflate(R.menu.activity_conversations, menu);
321 MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
322 if (qrCodeScanMenuItem != null) {
323 Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
324 boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
325 && fragment != null
326 && fragment instanceof ConversationsOverviewFragment;
327 qrCodeScanMenuItem.setVisible(visible);
328 }
329 return super.onCreateOptionsMenu(menu);
330 }
331
332 @Override
333 public void onConversationSelected(Conversation conversation) {
334 openConversation(conversation, null);
335 }
336
337 private void openConversation(Conversation conversation, Bundle extras) {
338 ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment);
339 final boolean mainNeedsRefresh;
340 if (conversationFragment == null) {
341 mainNeedsRefresh = false;
342 Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
343 if (mainFragment != null && mainFragment instanceof ConversationFragment) {
344 conversationFragment = (ConversationFragment) mainFragment;
345 } else {
346 conversationFragment = new ConversationFragment();
347 FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
348 fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
349 fragmentTransaction.addToBackStack(null);
350 fragmentTransaction.commit();
351 }
352 } else {
353 mainNeedsRefresh = true;
354 }
355 conversationFragment.reInit(conversation, extras);
356 if (mainNeedsRefresh) {
357 refreshFragment(R.id.main_fragment);
358 } else {
359 invalidateActionBarTitle();
360 }
361 }
362
363 @Override
364 public boolean onOptionsItemSelected(MenuItem item) {
365 switch (item.getItemId()) {
366 case android.R.id.home:
367 FragmentManager fm = getFragmentManager();
368 if (fm.getBackStackEntryCount() > 0) {
369 fm.popBackStack();
370 return true;
371 }
372 break;
373 case R.id.action_scan_qr_code:
374 UriHandlerActivity.scan(this);
375 return true;
376 }
377 return super.onOptionsItemSelected(item);
378 }
379
380 @Override
381 protected void onStart() {
382 final int theme = findTheme();
383 if (this.mTheme != theme) {
384 recreate();
385 }
386 mRedirectInProcess.set(false);
387 super.onStart();
388 }
389
390 @Override
391 protected void onNewIntent(final Intent intent) {
392 if (isViewIntent(intent)) {
393 if (xmppConnectionService != null) {
394 processViewIntent(intent);
395 } else {
396 pendingViewIntent.push(intent);
397 }
398 }
399 }
400
401 @Override
402 public void onPause() {
403 this.mActivityPaused = true;
404 super.onPause();
405 }
406
407 @Override
408 public void onResume() {
409 super.onResume();
410 this.mActivityPaused = false;
411 }
412
413 private void initializeFragments() {
414 FragmentTransaction transaction = getFragmentManager().beginTransaction();
415 Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
416 Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
417 if (mainFragment != null) {
418 Log.d(Config.LOGTAG, "initializeFragment(). main fragment exists");
419 if (binding.secondaryFragment != null) {
420 if (mainFragment instanceof ConversationFragment) {
421 Log.d(Config.LOGTAG, "gained secondary fragment. moving...");
422 getFragmentManager().popBackStack();
423 transaction.remove(mainFragment);
424 transaction.commit();
425 getFragmentManager().executePendingTransactions();
426 transaction = getFragmentManager().beginTransaction();
427 transaction.replace(R.id.secondary_fragment, mainFragment);
428 transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
429 transaction.commit();
430 return;
431 }
432 } else {
433 if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
434 Log.d(Config.LOGTAG, "lost secondary fragment. moving...");
435 transaction.remove(secondaryFragment);
436 transaction.commit();
437 getFragmentManager().executePendingTransactions();
438 transaction = getFragmentManager().beginTransaction();
439 transaction.replace(R.id.main_fragment, secondaryFragment);
440 transaction.addToBackStack(null);
441 transaction.commit();
442 return;
443 }
444 }
445 } else {
446 transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
447 }
448 if (binding.secondaryFragment != null && secondaryFragment == null) {
449 transaction.replace(R.id.secondary_fragment, new ConversationFragment());
450 }
451 transaction.commit();
452 }
453
454 private void invalidateActionBarTitle() {
455 final ActionBar actionBar = getSupportActionBar();
456 if (actionBar != null) {
457 Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
458 if (mainFragment != null && mainFragment instanceof ConversationFragment) {
459 final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
460 if (conversation != null) {
461 actionBar.setTitle(conversation.getName());
462 actionBar.setDisplayHomeAsUpEnabled(true);
463 return;
464 }
465 }
466 actionBar.setTitle(R.string.app_name);
467 actionBar.setDisplayHomeAsUpEnabled(false);
468 }
469 }
470
471 @Override
472 public void onConversationArchived(Conversation conversation) {
473 if (performRedirectIfNecessary(conversation, false)) {
474 return;
475 }
476 Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
477 if (mainFragment != null && mainFragment instanceof ConversationFragment) {
478 getFragmentManager().popBackStack();
479 return;
480 }
481 Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
482 if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
483 if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
484 Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
485 if (suggestion != null) {
486 openConversation(suggestion, null);
487 return;
488 }
489 }
490 }
491 }
492
493 @Override
494 public void onConversationsListItemUpdated() {
495 Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
496 if (fragment != null && fragment instanceof ConversationsOverviewFragment) {
497 ((ConversationsOverviewFragment) fragment).refresh();
498 }
499 }
500
501 @Override
502 public void onConversationRead(Conversation conversation) {
503 if (!mActivityPaused && pendingViewIntent.peek() == null) {
504 xmppConnectionService.sendReadMarker(conversation);
505 }
506 }
507
508 @Override
509 public void onAccountUpdate() {
510 this.refreshUi();
511 }
512
513 @Override
514 public void onConversationUpdate() {
515 if (performRedirectIfNecessary(false)) {
516 return;
517 }
518 this.refreshUi();
519 }
520
521 @Override
522 public void onRosterUpdate() {
523 this.refreshUi();
524 }
525
526 @Override
527 public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
528 this.refreshUi();
529 }
530
531 @Override
532 public void onShowErrorToast(int resId) {
533 runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
534 }
535}