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.app.Fragment;
 34import android.app.FragmentManager;
 35import android.app.FragmentTransaction;
 36import android.content.Context;
 37import android.content.Intent;
 38import android.databinding.DataBindingUtil;
 39import android.os.Bundle;
 40import android.support.annotation.IdRes;
 41import android.support.v7.app.ActionBar;
 42import android.util.Log;
 43import android.view.Menu;
 44import android.view.MenuItem;
 45import android.widget.Toast;
 46
 47import java.util.concurrent.atomic.AtomicBoolean;
 48
 49import eu.siacs.conversations.Config;
 50import eu.siacs.conversations.R;
 51import eu.siacs.conversations.databinding.ActivityConversationsBinding;
 52import eu.siacs.conversations.entities.Account;
 53import eu.siacs.conversations.entities.Conversation;
 54import eu.siacs.conversations.services.XmppConnectionService;
 55import eu.siacs.conversations.ui.interfaces.OnConversationArchived;
 56import eu.siacs.conversations.ui.interfaces.OnConversationRead;
 57import eu.siacs.conversations.ui.interfaces.OnConversationSelected;
 58import eu.siacs.conversations.ui.interfaces.OnConversationsListItemUpdated;
 59import eu.siacs.conversations.ui.service.EmojiService;
 60import eu.siacs.conversations.ui.util.PendingItem;
 61import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 62
 63public class ConversationActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast {
 64
 65	public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
 66	public static final String EXTRA_CONVERSATION = "conversationUuid";
 67	public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
 68	public static final String EXTRA_TEXT = "text";
 69	public static final String EXTRA_NICK = "nick";
 70	public static final String EXTRA_IS_PRIVATE_MESSAGE = "pm";
 71
 72
 73	//secondary fragment (when holding the conversation, must be initialized before refreshing the overview fragment
 74	private static final @IdRes
 75	int[] FRAGMENT_ID_NOTIFICATION_ORDER = {R.id.secondary_fragment, R.id.main_fragment};
 76	private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
 77	private ActivityConversationsBinding binding;
 78	private boolean mActivityPaused = true;
 79	private AtomicBoolean mRedirectInProcess = new AtomicBoolean(false);
 80
 81	private static boolean isViewIntent(Intent i) {
 82		return i != null && ACTION_VIEW_CONVERSATION.equals(i.getAction()) && i.hasExtra(EXTRA_CONVERSATION);
 83	}
 84
 85	private static Intent createLauncherIntent(Context context) {
 86		final Intent intent = new Intent(context, ConversationActivity.class);
 87		intent.setAction(Intent.ACTION_MAIN);
 88		intent.addCategory(Intent.CATEGORY_LAUNCHER);
 89		return intent;
 90	}
 91
 92	@Override
 93	protected void refreshUiReal() {
 94		for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
 95			refreshFragment(id);
 96		}
 97	}
 98
 99	@Override
100	void onBackendConnected() {
101		if (performRedirectIfNecessary(true)) {
102			return;
103		}
104		for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
105			notifyFragmentOfBackendConnected(id);
106		}
107		invalidateActionBarTitle();
108		xmppConnectionService.getNotificationService().setIsInForeground(true);
109		Intent intent = pendingViewIntent.pop();
110		if (intent != null) {
111			if (processViewIntent(intent)) {
112				return;
113			}
114		}
115		if (binding.secondaryFragment != null && ConversationFragment.getConversation(this) == null) {
116			Conversation conversation = ConversationsOverviewFragment.getSuggestion(this);
117			if (conversation != null) {
118				openConversation(conversation, null);
119			}
120		}
121	}
122
123	private boolean performRedirectIfNecessary(boolean noAnimation) {
124		return performRedirectIfNecessary(null, noAnimation);
125	}
126
127	private boolean performRedirectIfNecessary(final Conversation ignore, final boolean noAnimation) {
128		if (xmppConnectionService == null) {
129			return false;
130		}
131		boolean isConversationsListEmpty = xmppConnectionService.isConversationsListEmpty(ignore);
132		if (isConversationsListEmpty && mRedirectInProcess.compareAndSet(false, true)) {
133			final Intent intent = getRedirectionIntent(noAnimation);
134			runOnUiThread(() -> {
135				startActivity(intent);
136				if (noAnimation) {
137					overridePendingTransition(0, 0);
138				}
139			});
140		}
141		return mRedirectInProcess.get();
142	}
143
144	private Intent getRedirectionIntent(boolean noAnimation) {
145		Account pendingAccount = xmppConnectionService.getPendingAccount();
146		Intent intent;
147		if (pendingAccount != null) {
148			intent = new Intent(this, EditAccountActivity.class);
149			intent.putExtra("jid", pendingAccount.getJid().toBareJid().toString());
150		} else {
151			if (xmppConnectionService.getAccounts().size() == 0) {
152				if (Config.X509_VERIFICATION) {
153					intent = new Intent(this, ManageAccountActivity.class);
154				} else if (Config.MAGIC_CREATE_DOMAIN != null) {
155					intent = new Intent(this, WelcomeActivity.class);
156					WelcomeActivity.addInviteUri(intent, getIntent());
157				} else {
158					intent = new Intent(this, EditAccountActivity.class);
159				}
160			} else {
161				intent = new Intent(this, StartConversationActivity.class);
162			}
163		}
164		intent.putExtra("init", true);
165		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
166		if (noAnimation) {
167			intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
168		}
169		return intent;
170	}
171
172	private void notifyFragmentOfBackendConnected(@IdRes int id) {
173		final Fragment fragment = getFragmentManager().findFragmentById(id);
174		if (fragment != null && fragment instanceof XmppFragment) {
175			((XmppFragment) fragment).onBackendConnected();
176		}
177	}
178
179	private void refreshFragment(@IdRes int id) {
180		final Fragment fragment = getFragmentManager().findFragmentById(id);
181		if (fragment != null && fragment instanceof XmppFragment) {
182			((XmppFragment) fragment).refresh();
183		}
184	}
185
186	private boolean processViewIntent(Intent intent) {
187		String uuid = intent.getStringExtra(EXTRA_CONVERSATION);
188		Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null;
189		if (conversation == null) {
190			Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid);
191			return false;
192		}
193		openConversation(conversation, intent.getExtras());
194		return true;
195	}
196
197	@Override
198	protected void onCreate(final Bundle savedInstanceState) {
199		super.onCreate(savedInstanceState);
200		new EmojiService(this).init();
201		this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
202		this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
203		this.initializeFragments();
204		this.invalidateActionBarTitle();
205		final Intent intent = getIntent();
206		if (isViewIntent(intent)) {
207			pendingViewIntent.push(intent);
208			setIntent(createLauncherIntent(this));
209		}
210	}
211
212	@Override
213	public boolean onCreateOptionsMenu(Menu menu) {
214		getMenuInflater().inflate(R.menu.activity_conversations, menu);
215		return super.onCreateOptionsMenu(menu);
216	}
217
218	@Override
219	public void onConversationSelected(Conversation conversation) {
220		Log.d(Config.LOGTAG, "selected " + conversation.getName());
221		openConversation(conversation, null);
222	}
223
224	private void openConversation(Conversation conversation, Bundle extras) {
225		ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment);
226		final boolean mainNeedsRefresh;
227		if (conversationFragment == null) {
228			mainNeedsRefresh = false;
229			Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
230			if (mainFragment != null && mainFragment instanceof ConversationFragment) {
231				conversationFragment = (ConversationFragment) mainFragment;
232			} else {
233				conversationFragment = new ConversationFragment();
234				FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
235				fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
236				fragmentTransaction.addToBackStack(null);
237				fragmentTransaction.commit();
238			}
239		} else {
240			mainNeedsRefresh = true;
241		}
242		conversationFragment.reInit(conversation, extras);
243		if (mainNeedsRefresh) {
244			refreshFragment(R.id.main_fragment);
245		} else {
246			invalidateActionBarTitle();
247		}
248	}
249
250	@Override
251	public boolean onOptionsItemSelected(MenuItem item) {
252		switch (item.getItemId()) {
253			case android.R.id.home:
254				FragmentManager fm = getFragmentManager();
255				if (fm.getBackStackEntryCount() > 0) {
256					fm.popBackStack();
257					return true;
258				}
259				break;
260		}
261		return super.onOptionsItemSelected(item);
262	}
263
264	@Override
265	protected void onStart() {
266		final int theme = findTheme();
267		if (this.mTheme != theme) {
268			recreate();
269		}
270		mRedirectInProcess.set(false);
271		super.onStart();
272	}
273
274	@Override
275	protected void onNewIntent(final Intent intent) {
276		if (isViewIntent(intent)) {
277			if (xmppConnectionService != null) {
278				processViewIntent(intent);
279			} else {
280				pendingViewIntent.push(intent);
281			}
282		}
283	}
284
285	@Override
286	public void onPause() {
287		this.mActivityPaused = true;
288		super.onPause();
289	}
290
291	@Override
292	public void onResume() {
293		super.onResume();
294		this.mActivityPaused = false;
295	}
296
297	private void initializeFragments() {
298		FragmentTransaction transaction = getFragmentManager().beginTransaction();
299		Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
300		Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
301		if (mainFragment != null) {
302			Log.d(Config.LOGTAG, "initializeFragment(). main fragment exists");
303			if (binding.secondaryFragment != null) {
304				if (mainFragment instanceof ConversationFragment) {
305					Log.d(Config.LOGTAG, "gained secondary fragment. moving...");
306					getFragmentManager().popBackStack();
307					transaction.remove(mainFragment);
308					transaction.commit();
309					getFragmentManager().executePendingTransactions();
310					transaction = getFragmentManager().beginTransaction();
311					transaction.replace(R.id.secondary_fragment, mainFragment);
312					transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
313					transaction.commit();
314					return;
315				}
316			} else {
317				if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
318					Log.d(Config.LOGTAG, "lost secondary fragment. moving...");
319					transaction.remove(secondaryFragment);
320					transaction.commit();
321					getFragmentManager().executePendingTransactions();
322					transaction = getFragmentManager().beginTransaction();
323					transaction.replace(R.id.main_fragment, secondaryFragment);
324					transaction.addToBackStack(null);
325					transaction.commit();
326					return;
327				}
328			}
329		} else {
330			transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
331		}
332		if (binding.secondaryFragment != null && secondaryFragment == null) {
333			transaction.replace(R.id.secondary_fragment, new ConversationFragment());
334		}
335		transaction.commit();
336	}
337
338	private void invalidateActionBarTitle() {
339		final ActionBar actionBar = getSupportActionBar();
340		if (actionBar != null) {
341			Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
342			if (mainFragment != null && mainFragment instanceof ConversationFragment) {
343				final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
344				if (conversation != null) {
345					actionBar.setTitle(conversation.getName());
346					actionBar.setDisplayHomeAsUpEnabled(true);
347					return;
348				}
349			}
350			actionBar.setTitle(R.string.app_name);
351			actionBar.setDisplayHomeAsUpEnabled(false);
352		}
353	}
354
355	@Override
356	public void onConversationArchived(Conversation conversation) {
357		if (performRedirectIfNecessary(conversation, false)) {
358			return;
359		}
360		Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
361		if (mainFragment != null && mainFragment instanceof ConversationFragment) {
362			getFragmentManager().popBackStack();
363			return;
364		}
365		Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
366		if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
367			if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
368				Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
369				if (suggestion != null) {
370					openConversation(suggestion, null);
371					return;
372				}
373			}
374		}
375	}
376
377	@Override
378	public void onConversationsListItemUpdated() {
379		Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
380		if (fragment != null && fragment instanceof ConversationsOverviewFragment) {
381			((ConversationsOverviewFragment) fragment).refresh();
382		}
383	}
384
385	@Override
386	public void onConversationRead(Conversation conversation) {
387		if (!mActivityPaused && pendingViewIntent.peek() == null) {
388			xmppConnectionService.sendReadMarker(conversation);
389		}
390	}
391
392	@Override
393	public void onAccountUpdate() {
394		this.refreshUi();
395	}
396
397	@Override
398	public void onConversationUpdate() {
399		if (performRedirectIfNecessary(false)) {
400			return;
401		}
402		this.refreshUi();
403	}
404
405	@Override
406	public void onRosterUpdate() {
407		this.refreshUi();
408	}
409
410	@Override
411	public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
412		this.refreshUi();
413	}
414
415	@Override
416	public void onShowErrorToast(int resId) {
417		runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
418	}
419}