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