ConversationActivity.java

  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);
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		savedInstanceState.putParcelable("intent", getIntent());
400		super.onSaveInstanceState(savedInstanceState);
401	}
402
403	@Override
404	protected void onStart() {
405		final int theme = findTheme();
406		if (this.mTheme != theme) {
407			recreate();
408		}
409		mRedirectInProcess.set(false);
410		super.onStart();
411	}
412
413	@Override
414	protected void onNewIntent(final Intent intent) {
415		if (isViewIntent(intent)) {
416			if (xmppConnectionService != null) {
417				processViewIntent(intent);
418			} else {
419				pendingViewIntent.push(intent);
420			}
421		}
422		setIntent(createLauncherIntent(this));
423	}
424
425	@Override
426	public void onPause() {
427		this.mActivityPaused = true;
428		super.onPause();
429	}
430
431	@Override
432	public void onResume() {
433		super.onResume();
434		this.mActivityPaused = false;
435	}
436
437	private void initializeFragments() {
438		FragmentTransaction transaction = getFragmentManager().beginTransaction();
439		Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
440		Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
441		if (mainFragment != null) {
442			Log.d(Config.LOGTAG, "initializeFragment(). main fragment exists");
443			if (binding.secondaryFragment != null) {
444				if (mainFragment instanceof ConversationFragment) {
445					Log.d(Config.LOGTAG, "gained secondary fragment. moving...");
446					getFragmentManager().popBackStack();
447					transaction.remove(mainFragment);
448					transaction.commit();
449					getFragmentManager().executePendingTransactions();
450					transaction = getFragmentManager().beginTransaction();
451					transaction.replace(R.id.secondary_fragment, mainFragment);
452					transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
453					transaction.commit();
454					return;
455				}
456			} else {
457				if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
458					Log.d(Config.LOGTAG, "lost secondary fragment. moving...");
459					transaction.remove(secondaryFragment);
460					transaction.commit();
461					getFragmentManager().executePendingTransactions();
462					transaction = getFragmentManager().beginTransaction();
463					transaction.replace(R.id.main_fragment, secondaryFragment);
464					transaction.addToBackStack(null);
465					transaction.commit();
466					return;
467				}
468			}
469		} else {
470			transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
471		}
472		if (binding.secondaryFragment != null && secondaryFragment == null) {
473			transaction.replace(R.id.secondary_fragment, new ConversationFragment());
474		}
475		transaction.commit();
476	}
477
478	private void invalidateActionBarTitle() {
479		final ActionBar actionBar = getSupportActionBar();
480		if (actionBar != null) {
481			Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
482			if (mainFragment != null && mainFragment instanceof ConversationFragment) {
483				final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
484				if (conversation != null) {
485					actionBar.setTitle(conversation.getName());
486					actionBar.setDisplayHomeAsUpEnabled(true);
487					return;
488				}
489			}
490			actionBar.setTitle(R.string.app_name);
491			actionBar.setDisplayHomeAsUpEnabled(false);
492		}
493	}
494
495	@Override
496	public void onConversationArchived(Conversation conversation) {
497		if (performRedirectIfNecessary(conversation, false)) {
498			return;
499		}
500		Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
501		if (mainFragment != null && mainFragment instanceof ConversationFragment) {
502			getFragmentManager().popBackStack();
503			return;
504		}
505		Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
506		if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
507			if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
508				Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
509				if (suggestion != null) {
510					openConversation(suggestion, null);
511					return;
512				}
513			}
514		}
515	}
516
517	@Override
518	public void onConversationsListItemUpdated() {
519		Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
520		if (fragment != null && fragment instanceof ConversationsOverviewFragment) {
521			((ConversationsOverviewFragment) fragment).refresh();
522		}
523	}
524
525	@Override
526	public void onConversationRead(Conversation conversation) {
527		if (!mActivityPaused && pendingViewIntent.peek() == null) {
528			xmppConnectionService.sendReadMarker(conversation);
529		} else {
530			Log.d(Config.LOGTAG,"ignoring read callback. mActivityPaused="+Boolean.toString(mActivityPaused));
531		}
532	}
533
534	@Override
535	public void onAccountUpdate() {
536		this.refreshUi();
537	}
538
539	@Override
540	public void onConversationUpdate() {
541		if (performRedirectIfNecessary(false)) {
542			return;
543		}
544		this.refreshUi();
545	}
546
547	@Override
548	public void onRosterUpdate() {
549		this.refreshUi();
550	}
551
552	@Override
553	public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
554		this.refreshUi();
555	}
556
557	@Override
558	public void onShowErrorToast(int resId) {
559		runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
560	}
561}