DrawerActivity.java 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. /*
  2. * Nextcloud Android client application
  3. *
  4. * @author Andy Scherzinger
  5. * @author Tobias Kaminsky
  6. * @author Chris Narkiewicz <hello@ezaquarii.com>
  7. * Copyright (C) 2016 Andy Scherzinger
  8. * Copyright (C) 2017 Tobias Kaminsky
  9. * Copyright (C) 2016 Nextcloud
  10. * Copyright (C) 2016 ownCloud Inc.
  11. * Copyright (C) 2020 Chris Narkiewicz <hello@ezaquarii.com>
  12. * Copyright (C) 2020 Infomaniak Network SA
  13. *
  14. * This program is free software; you can redistribute it and/or
  15. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  16. * License as published by the Free Software Foundation; either
  17. * version 3 of the License, or any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public
  25. * License along with this program. If not, see <http://www.gnu.org/licenses/>.
  26. */
  27. package com.owncloud.android.ui.activity;
  28. import android.app.Activity;
  29. import android.content.Context;
  30. import android.content.Intent;
  31. import android.content.res.Configuration;
  32. import android.graphics.drawable.Drawable;
  33. import android.net.Uri;
  34. import android.os.Build;
  35. import android.os.Bundle;
  36. import android.os.Handler;
  37. import android.os.SystemClock;
  38. import android.view.Menu;
  39. import android.view.MenuItem;
  40. import android.view.View;
  41. import android.widget.FrameLayout;
  42. import android.widget.ImageView;
  43. import android.widget.LinearLayout;
  44. import android.widget.ProgressBar;
  45. import android.widget.TextView;
  46. import com.bumptech.glide.request.animation.GlideAnimation;
  47. import com.bumptech.glide.request.target.SimpleTarget;
  48. import com.google.android.material.button.MaterialButton;
  49. import com.google.android.material.navigation.NavigationView;
  50. import com.nextcloud.client.account.User;
  51. import com.nextcloud.client.di.Injectable;
  52. import com.nextcloud.client.network.ClientFactory;
  53. import com.nextcloud.client.onboarding.FirstRunActivity;
  54. import com.nextcloud.client.preferences.AppPreferences;
  55. import com.nextcloud.java.util.Optional;
  56. import com.nextcloud.ui.ChooseAccountDialogFragment;
  57. import com.owncloud.android.MainApp;
  58. import com.owncloud.android.R;
  59. import com.owncloud.android.authentication.PassCodeManager;
  60. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  61. import com.owncloud.android.datamodel.ExternalLinksProvider;
  62. import com.owncloud.android.datamodel.FileDataStorageManager;
  63. import com.owncloud.android.datamodel.OCFile;
  64. import com.owncloud.android.lib.common.ExternalLink;
  65. import com.owncloud.android.lib.common.ExternalLinkType;
  66. import com.owncloud.android.lib.common.Quota;
  67. import com.owncloud.android.lib.common.UserInfo;
  68. import com.owncloud.android.lib.common.accounts.ExternalLinksOperation;
  69. import com.owncloud.android.lib.common.operations.RemoteOperation;
  70. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  71. import com.owncloud.android.lib.common.utils.Log_OC;
  72. import com.owncloud.android.lib.resources.files.SearchRemoteOperation;
  73. import com.owncloud.android.lib.resources.status.OCCapability;
  74. import com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation;
  75. import com.owncloud.android.operations.GetCapabilitiesOperation;
  76. import com.owncloud.android.ui.activities.ActivitiesActivity;
  77. import com.owncloud.android.ui.events.AccountRemovedEvent;
  78. import com.owncloud.android.ui.events.ChangeMenuEvent;
  79. import com.owncloud.android.ui.events.DummyDrawerEvent;
  80. import com.owncloud.android.ui.events.SearchEvent;
  81. import com.owncloud.android.ui.fragment.OCFileListFragment;
  82. import com.owncloud.android.ui.fragment.PhotoFragment;
  83. import com.owncloud.android.ui.trashbin.TrashbinActivity;
  84. import com.owncloud.android.utils.DisplayUtils;
  85. import com.owncloud.android.utils.DrawerMenuUtil;
  86. import com.owncloud.android.utils.FilesSyncHelper;
  87. import com.owncloud.android.utils.ThemeUtils;
  88. import com.owncloud.android.utils.svg.MenuSimpleTarget;
  89. import org.greenrobot.eventbus.EventBus;
  90. import org.greenrobot.eventbus.Subscribe;
  91. import org.greenrobot.eventbus.ThreadMode;
  92. import org.parceler.Parcels;
  93. import java.util.ArrayList;
  94. import java.util.List;
  95. import javax.inject.Inject;
  96. import androidx.annotation.NonNull;
  97. import androidx.appcompat.app.ActionBarDrawerToggle;
  98. import androidx.core.content.ContextCompat;
  99. import androidx.core.content.res.ResourcesCompat;
  100. import androidx.core.view.GravityCompat;
  101. import androidx.drawerlayout.widget.DrawerLayout;
  102. /**
  103. * Base class to handle setup of the drawer implementation including user switching and avatar fetching and fallback
  104. * generation.
  105. */
  106. public abstract class DrawerActivity extends ToolbarActivity
  107. implements DisplayUtils.AvatarGenerationListener, Injectable {
  108. private static final String TAG = DrawerActivity.class.getSimpleName();
  109. private static final String KEY_IS_ACCOUNT_CHOOSER_ACTIVE = "IS_ACCOUNT_CHOOSER_ACTIVE";
  110. private static final String KEY_CHECKED_MENU_ITEM = "CHECKED_MENU_ITEM";
  111. private static final int ACTION_MANAGE_ACCOUNTS = 101;
  112. private static final int MENU_ORDER_EXTERNAL_LINKS = 3;
  113. private static final int MENU_ITEM_EXTERNAL_LINK = 111;
  114. /**
  115. * Reference to the drawer layout.
  116. */
  117. private DrawerLayout mDrawerLayout;
  118. /**
  119. * Reference to the drawer toggle.
  120. */
  121. protected ActionBarDrawerToggle mDrawerToggle;
  122. /**
  123. * Reference to the navigation view.
  124. */
  125. private NavigationView mNavigationView;
  126. /**
  127. * Reference to the navigation view header.
  128. */
  129. private View mNavigationViewHeader;
  130. /**
  131. * Flag to signal if the account chooser is active.
  132. */
  133. private boolean mIsAccountChooserActive;
  134. /**
  135. * Id of the checked menu item.
  136. */
  137. private int mCheckedMenuItem = Menu.NONE;
  138. /**
  139. * container layout of the quota view.
  140. */
  141. private LinearLayout mQuotaView;
  142. /**
  143. * progress bar of the quota view.
  144. */
  145. private ProgressBar mQuotaProgressBar;
  146. /**
  147. * text view of the quota view.
  148. */
  149. private TextView mQuotaTextPercentage;
  150. private TextView mQuotaTextLink;
  151. /**
  152. * runnable that will be executed after the drawer has been closed.
  153. */
  154. private Runnable pendingRunnable;
  155. private ExternalLinksProvider externalLinksProvider;
  156. private ArbitraryDataProvider arbitraryDataProvider;
  157. @Inject
  158. AppPreferences preferences;
  159. @Inject
  160. ClientFactory clientFactory;
  161. /**
  162. * Initializes the drawer, its content and highlights the menu item with the given id. This method needs to be
  163. * called after the content view has been set.
  164. *
  165. * @param menuItemId the menu item to be checked/highlighted
  166. */
  167. protected void setupDrawer(int menuItemId) {
  168. setupDrawer();
  169. setDrawerMenuItemChecked(menuItemId);
  170. }
  171. /**
  172. * Initializes the drawer and its content. This method needs to be called after the content view has been set.
  173. */
  174. protected void setupDrawer() {
  175. mDrawerLayout = findViewById(R.id.drawer_layout);
  176. mNavigationView = findViewById(R.id.nav_view);
  177. if (mNavigationView != null) {
  178. // Setting up drawer header
  179. mNavigationViewHeader = mNavigationView.getHeaderView(0);
  180. FrameLayout drawerHeader = mNavigationViewHeader.findViewById(R.id.drawer_header_view);
  181. setupDrawerHeader(drawerHeader);
  182. setupDrawerMenu(mNavigationView);
  183. getAndDisplayUserQuota();
  184. setupQuotaElement();
  185. }
  186. setupDrawerToggle();
  187. if (getSupportActionBar() != null) {
  188. getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  189. }
  190. }
  191. /**
  192. * initializes and sets up the drawer toggle.
  193. */
  194. private void setupDrawerToggle() {
  195. mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
  196. /** Called when a drawer has settled in a completely closed state. */
  197. public void onDrawerClosed(View view) {
  198. super.onDrawerClosed(view);
  199. supportInvalidateOptionsMenu();
  200. mDrawerToggle.setDrawerIndicatorEnabled(isDrawerIndicatorAvailable());
  201. if (pendingRunnable != null) {
  202. new Handler().post(pendingRunnable);
  203. pendingRunnable = null;
  204. }
  205. closeDrawer();
  206. }
  207. /** Called when a drawer has settled in a completely open state. */
  208. public void onDrawerOpened(View drawerView) {
  209. super.onDrawerOpened(drawerView);
  210. mDrawerToggle.setDrawerIndicatorEnabled(true);
  211. supportInvalidateOptionsMenu();
  212. }
  213. };
  214. // Set the drawer toggle as the DrawerListener
  215. mDrawerLayout.addDrawerListener(mDrawerToggle);
  216. mDrawerToggle.setDrawerIndicatorEnabled(true);
  217. mDrawerToggle.setDrawerSlideAnimationEnabled(true);
  218. Drawable backArrow = ResourcesCompat.getDrawable(getResources(),
  219. R.drawable.ic_arrow_back,
  220. null);
  221. mDrawerToggle.setHomeAsUpIndicator(ThemeUtils.tintDrawable(backArrow, ThemeUtils.appBarPrimaryFontColor(this)));
  222. mDrawerToggle.getDrawerArrowDrawable().setColor(ThemeUtils.appBarPrimaryFontColor(this));
  223. }
  224. /**
  225. * setup quota elements of the drawer.
  226. */
  227. private void setupQuotaElement() {
  228. mQuotaView = (LinearLayout) findQuotaViewById(R.id.drawer_quota);
  229. mQuotaProgressBar = (ProgressBar) findQuotaViewById(R.id.drawer_quota_ProgressBar);
  230. mQuotaTextPercentage = (TextView) findQuotaViewById(R.id.drawer_quota_percentage);
  231. mQuotaTextLink = (TextView) findQuotaViewById(R.id.drawer_quota_link);
  232. ThemeUtils.colorProgressBar(mQuotaProgressBar, ThemeUtils.primaryColor(this));
  233. }
  234. /**
  235. * setup drawer header, basically the logo color
  236. */
  237. private void setupDrawerHeader(FrameLayout drawerHeader) {
  238. drawerHeader.setBackgroundColor(ThemeUtils.primaryColor(getAccount(), true, this));
  239. }
  240. /**
  241. * setup drawer content, basically setting the item selected listener.
  242. *
  243. * @param navigationView the drawers navigation view
  244. */
  245. private void setupDrawerMenu(NavigationView navigationView) {
  246. navigationView.setItemIconTintList(null);
  247. // setup actions for drawer menu items
  248. navigationView.setNavigationItemSelectedListener(
  249. menuItem -> {
  250. mDrawerLayout.closeDrawers();
  251. // pending runnable will be executed after the drawer has been closed
  252. pendingRunnable = () -> onNavigationItemClicked(menuItem);
  253. return true;
  254. });
  255. User account = accountManager.getUser();
  256. filterDrawerMenu(navigationView.getMenu(), account);
  257. }
  258. private void filterDrawerMenu(final Menu menu, @NonNull final User user) {
  259. FileDataStorageManager storageManager = new FileDataStorageManager(user.toPlatformAccount(),
  260. getContentResolver());
  261. OCCapability capability = storageManager.getCapability(user.getAccountName());
  262. DrawerMenuUtil.filterSearchMenuItems(menu, user, getResources());
  263. DrawerMenuUtil.filterTrashbinMenuItem(menu, user, capability);
  264. DrawerMenuUtil.filterActivityMenuItem(menu, capability);
  265. DrawerMenuUtil.setupHomeMenuItem(menu, getResources());
  266. DrawerMenuUtil.removeMenuItem(menu, R.id.nav_community,
  267. !getResources().getBoolean(R.bool.participate_enabled));
  268. DrawerMenuUtil.removeMenuItem(menu, R.id.nav_shared, !getResources().getBoolean(R.bool.shared_enabled));
  269. DrawerMenuUtil.removeMenuItem(menu, R.id.nav_contacts, !getResources().getBoolean(R.bool.contacts_backup)
  270. || !getResources().getBoolean(R.bool.show_drawer_contacts_backup));
  271. DrawerMenuUtil.removeMenuItem(menu, R.id.nav_synced_folders,
  272. getResources().getBoolean(R.bool.syncedFolder_light));
  273. DrawerMenuUtil.removeMenuItem(menu, R.id.nav_logout, !getResources().getBoolean(R.bool.show_drawer_logout));
  274. }
  275. @Subscribe(threadMode = ThreadMode.MAIN)
  276. public void onMessageEvent(DummyDrawerEvent event) {
  277. unsetAllDrawerMenuItems();
  278. }
  279. private void onNavigationItemClicked(final MenuItem menuItem) {
  280. setDrawerMenuItemChecked(menuItem.getItemId());
  281. switch (menuItem.getItemId()) {
  282. case R.id.nav_all_files:
  283. showFiles(false);
  284. if ((this instanceof FileDisplayActivity) &&
  285. !(((FileDisplayActivity) this).getListOfFilesFragment() instanceof PhotoFragment)) {
  286. ((FileDisplayActivity) this).browseToRoot();
  287. EventBus.getDefault().post(new ChangeMenuEvent());
  288. } else {
  289. Intent intent = new Intent(getApplicationContext(), FileDisplayActivity.class);
  290. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  291. intent.setAction(FileDisplayActivity.ALL_FILES);
  292. intent.putExtra(FileDisplayActivity.DRAWER_MENU_ID, menuItem.getItemId());
  293. startActivity(intent);
  294. }
  295. break;
  296. case R.id.nav_favorites:
  297. handleSearchEvents(new SearchEvent("", SearchRemoteOperation.SearchType.FAVORITE_SEARCH),
  298. menuItem.getItemId());
  299. break;
  300. case R.id.nav_photos:
  301. startPhotoSearch(menuItem);
  302. break;
  303. case R.id.nav_on_device:
  304. EventBus.getDefault().post(new ChangeMenuEvent());
  305. showFiles(true);
  306. break;
  307. case R.id.nav_uploads:
  308. startActivity(UploadListActivity.class, Intent.FLAG_ACTIVITY_CLEAR_TOP);
  309. break;
  310. case R.id.nav_trashbin:
  311. startActivity(TrashbinActivity.class, Intent.FLAG_ACTIVITY_CLEAR_TOP);
  312. break;
  313. case R.id.nav_activity:
  314. startActivity(ActivitiesActivity.class, Intent.FLAG_ACTIVITY_CLEAR_TOP);
  315. break;
  316. case R.id.nav_notifications:
  317. startActivity(NotificationsActivity.class);
  318. break;
  319. case R.id.nav_synced_folders:
  320. startActivity(SyncedFoldersActivity.class);
  321. break;
  322. case R.id.nav_contacts:
  323. ContactsPreferenceActivity.startActivity(this);
  324. break;
  325. case R.id.nav_settings:
  326. startActivity(SettingsActivity.class);
  327. break;
  328. case R.id.nav_community:
  329. startActivity(CommunityActivity.class);
  330. break;
  331. case R.id.nav_logout:
  332. mCheckedMenuItem = -1;
  333. menuItem.setChecked(false);
  334. final Optional<User> optionalUser = getUser();
  335. if (optionalUser.isPresent()) {
  336. UserInfoActivity.openAccountRemovalConfirmationDialog(optionalUser.get(), getSupportFragmentManager());
  337. }
  338. break;
  339. case R.id.nav_shared:
  340. handleSearchEvents(new SearchEvent("", SearchRemoteOperation.SearchType.SHARED_FILTER),
  341. menuItem.getItemId());
  342. break;
  343. case R.id.nav_recently_modified:
  344. handleSearchEvents(new SearchEvent("", SearchRemoteOperation.SearchType.RECENTLY_MODIFIED_SEARCH),
  345. menuItem.getItemId());
  346. break;
  347. default:
  348. if (menuItem.getItemId() >= MENU_ITEM_EXTERNAL_LINK &&
  349. menuItem.getItemId() <= MENU_ITEM_EXTERNAL_LINK + 100) {
  350. // external link clicked
  351. externalLinkClicked(menuItem);
  352. } else {
  353. Log_OC.i(TAG, "Unknown drawer menu item clicked: " + menuItem.getTitle());
  354. }
  355. break;
  356. }
  357. }
  358. private void startActivity(Class<? extends Activity> activity) {
  359. startActivity(new Intent(getApplicationContext(), activity));
  360. }
  361. private void startActivity(Class<? extends Activity> activity, int flags) {
  362. Intent intent = new Intent(getApplicationContext(), activity);
  363. intent.setFlags(flags);
  364. startActivity(intent);
  365. }
  366. public void showManageAccountsDialog() {
  367. ChooseAccountDialogFragment choseAccountDialog = ChooseAccountDialogFragment.newInstance(accountManager.getUser());
  368. choseAccountDialog.show(getSupportFragmentManager(), "fragment_chose_account");
  369. }
  370. public void openManageAccounts() {
  371. Intent manageAccountsIntent = new Intent(getApplicationContext(), ManageAccountsActivity.class);
  372. startActivityForResult(manageAccountsIntent, ACTION_MANAGE_ACCOUNTS);
  373. }
  374. public void openAddAccount() {
  375. boolean isProviderOrOwnInstallationVisible = getResources()
  376. .getBoolean(R.bool.show_provider_or_own_installation);
  377. if (isProviderOrOwnInstallationVisible) {
  378. Intent firstRunIntent = new Intent(getApplicationContext(), FirstRunActivity.class);
  379. firstRunIntent.putExtra(FirstRunActivity.EXTRA_ALLOW_CLOSE, true);
  380. startActivity(firstRunIntent);
  381. } else {
  382. startAccountCreation();
  383. }
  384. }
  385. private void startPhotoSearch(MenuItem menuItem) {
  386. SearchEvent searchEvent = new SearchEvent("image/%", SearchRemoteOperation.SearchType.PHOTO_SEARCH);
  387. MainApp.showOnlyFilesOnDevice(false);
  388. Intent intent = new Intent(getApplicationContext(), FileDisplayActivity.class);
  389. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  390. intent.setAction(Intent.ACTION_SEARCH);
  391. intent.putExtra(OCFileListFragment.SEARCH_EVENT, Parcels.wrap(searchEvent));
  392. intent.putExtra(FileDisplayActivity.DRAWER_MENU_ID, menuItem.getItemId());
  393. startActivity(intent);
  394. }
  395. private void handleSearchEvents(SearchEvent searchEvent, int menuItemId) {
  396. if (this instanceof FileDisplayActivity) {
  397. if (((FileDisplayActivity) this).getListOfFilesFragment() instanceof PhotoFragment) {
  398. Intent intent = new Intent(getApplicationContext(), FileDisplayActivity.class);
  399. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  400. intent.setAction(Intent.ACTION_SEARCH);
  401. intent.putExtra(OCFileListFragment.SEARCH_EVENT, Parcels.wrap(searchEvent));
  402. intent.putExtra(FileDisplayActivity.DRAWER_MENU_ID, menuItemId);
  403. startActivity(intent);
  404. } else {
  405. EventBus.getDefault().post(searchEvent);
  406. }
  407. } else {
  408. Intent intent = new Intent(getApplicationContext(), FileDisplayActivity.class);
  409. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  410. intent.setAction(Intent.ACTION_SEARCH);
  411. intent.putExtra(OCFileListFragment.SEARCH_EVENT, Parcels.wrap(searchEvent));
  412. intent.putExtra(FileDisplayActivity.DRAWER_MENU_ID, menuItemId);
  413. startActivity(intent);
  414. }
  415. }
  416. /**
  417. * show the file list to the user.
  418. *
  419. * @param onDeviceOnly flag to decide if all files or only the ones on the device should be shown
  420. */
  421. public abstract void showFiles(boolean onDeviceOnly);
  422. /**
  423. * sets the new/current account and restarts. In case the given account equals the actual/current account the call
  424. * will be ignored.
  425. *
  426. * @param hashCode HashCode of account to be set
  427. */
  428. public void accountClicked(int hashCode) {
  429. final User currentUser = accountManager.getUser();
  430. if (currentUser.hashCode() != hashCode && accountManager.setCurrentOwnCloudAccount(hashCode)) {
  431. fetchExternalLinks(true);
  432. restart();
  433. }
  434. }
  435. private void externalLinkClicked(MenuItem menuItem) {
  436. for (ExternalLink link : externalLinksProvider.getExternalLink(ExternalLinkType.LINK)) {
  437. if (menuItem.getTitle().toString().equalsIgnoreCase(link.name)) {
  438. if (link.redirect) {
  439. Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link.url));
  440. DisplayUtils.startIntentIfAppAvailable(intent, this, R.string.no_browser_available);
  441. } else {
  442. Intent externalWebViewIntent = new Intent(getApplicationContext(), ExternalSiteWebView.class);
  443. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_TITLE, link.name);
  444. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_URL, link.url);
  445. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_SHOW_SIDEBAR, true);
  446. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_MENU_ITEM_ID, menuItem.getItemId());
  447. startActivity(externalWebViewIntent);
  448. }
  449. }
  450. }
  451. }
  452. /**
  453. * checks if the drawer exists and is opened.
  454. *
  455. * @return <code>true</code> if the drawer is open, else <code>false</code>
  456. */
  457. public boolean isDrawerOpen() {
  458. return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START);
  459. }
  460. /**
  461. * closes the drawer.
  462. */
  463. public void closeDrawer() {
  464. if (mDrawerLayout != null) {
  465. mDrawerLayout.closeDrawer(GravityCompat.START);
  466. }
  467. }
  468. /**
  469. * opens the drawer.
  470. */
  471. public void openDrawer() {
  472. if (mDrawerLayout != null) {
  473. mDrawerLayout.openDrawer(GravityCompat.START);
  474. updateExternalLinksInDrawer();
  475. updateQuotaLink();
  476. }
  477. }
  478. /**
  479. * Enable or disable interaction with all drawers.
  480. *
  481. * @param lockMode The new lock mode for the given drawer. One of {@link DrawerLayout#LOCK_MODE_UNLOCKED}, {@link
  482. * DrawerLayout#LOCK_MODE_LOCKED_CLOSED} or {@link DrawerLayout#LOCK_MODE_LOCKED_OPEN}.
  483. */
  484. public void setDrawerLockMode(int lockMode) {
  485. if (mDrawerLayout != null) {
  486. mDrawerLayout.setDrawerLockMode(lockMode);
  487. }
  488. }
  489. /**
  490. * Enable or disable the drawer indicator.
  491. *
  492. * @param enable true to enable, false to disable
  493. */
  494. public void setDrawerIndicatorEnabled(boolean enable) {
  495. if (mDrawerToggle != null) {
  496. mDrawerToggle.setDrawerIndicatorEnabled(enable);
  497. }
  498. }
  499. /**
  500. * Updates title bar and home buttons (state and icon). Assumes that navigation drawer is NOT visible.
  501. */
  502. protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
  503. super.updateActionBarTitleAndHomeButton(chosenFile);
  504. // set home button properties
  505. if (mDrawerToggle != null) {
  506. if (chosenFile != null && isRoot(chosenFile)) {
  507. mDrawerToggle.setDrawerIndicatorEnabled(true);
  508. } else {
  509. mDrawerToggle.setDrawerIndicatorEnabled(false);
  510. }
  511. }
  512. }
  513. /**
  514. * shows or hides the quota UI elements.
  515. *
  516. * @param showQuota show/hide quota information
  517. */
  518. private void showQuota(boolean showQuota) {
  519. if (showQuota) {
  520. mQuotaView.setVisibility(View.VISIBLE);
  521. } else {
  522. mQuotaView.setVisibility(View.GONE);
  523. }
  524. }
  525. /**
  526. * configured the quota to be displayed.
  527. *
  528. * @param usedSpace the used space
  529. * @param totalSpace the total space
  530. * @param relative the percentage of space already used
  531. * @param quotaValue {@link GetUserInfoRemoteOperation#SPACE_UNLIMITED} or other to determinate state
  532. */
  533. private void setQuotaInformation(long usedSpace, long totalSpace, int relative, long quotaValue) {
  534. if (GetUserInfoRemoteOperation.SPACE_UNLIMITED == quotaValue) {
  535. mQuotaTextPercentage.setText(String.format(
  536. getString(R.string.drawer_quota_unlimited),
  537. DisplayUtils.bytesToHumanReadable(usedSpace)));
  538. } else {
  539. mQuotaTextPercentage.setText(String.format(
  540. getString(R.string.drawer_quota),
  541. DisplayUtils.bytesToHumanReadable(usedSpace),
  542. DisplayUtils.bytesToHumanReadable(totalSpace)));
  543. }
  544. mQuotaProgressBar.setProgress(relative);
  545. ThemeUtils.colorProgressBar(mQuotaProgressBar, DisplayUtils.getRelativeInfoColor(this, relative));
  546. updateQuotaLink();
  547. showQuota(true);
  548. }
  549. private void unsetAllDrawerMenuItems() {
  550. if (mNavigationView != null) {
  551. mNavigationView.getMenu();
  552. Menu menu = mNavigationView.getMenu();
  553. for (int i = 0; i < menu.size(); i++) {
  554. menu.getItem(i).setChecked(false);
  555. }
  556. }
  557. mCheckedMenuItem = Menu.NONE;
  558. }
  559. private void updateQuotaLink() {
  560. if (mQuotaTextLink != null) {
  561. if (getBaseContext().getResources().getBoolean(R.bool.show_external_links)) {
  562. List<ExternalLink> quotas = externalLinksProvider.getExternalLink(ExternalLinkType.QUOTA);
  563. float density = getResources().getDisplayMetrics().density;
  564. final int size = Math.round(24 * density);
  565. if (quotas.size() > 0) {
  566. final ExternalLink firstQuota = quotas.get(0);
  567. mQuotaTextLink.setText(firstQuota.name);
  568. mQuotaTextLink.setClickable(true);
  569. mQuotaTextLink.setVisibility(View.VISIBLE);
  570. mQuotaTextLink.setOnClickListener(v -> {
  571. Intent externalWebViewIntent = new Intent(getApplicationContext(), ExternalSiteWebView.class);
  572. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_TITLE, firstQuota.name);
  573. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_URL, firstQuota.url);
  574. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_SHOW_SIDEBAR, true);
  575. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_MENU_ITEM_ID, -1);
  576. startActivity(externalWebViewIntent);
  577. });
  578. SimpleTarget target = new SimpleTarget<Drawable>() {
  579. @Override
  580. public void onResourceReady(Drawable resource, GlideAnimation glideAnimation) {
  581. Drawable test = resource.getCurrent();
  582. test.setBounds(0, 0, size, size);
  583. mQuotaTextLink.setCompoundDrawablesWithIntrinsicBounds(test, null, null, null);
  584. }
  585. @Override
  586. public void onLoadFailed(Exception e, Drawable errorDrawable) {
  587. super.onLoadFailed(e, errorDrawable);
  588. Drawable test = errorDrawable.getCurrent();
  589. test.setBounds(0, 0, size, size);
  590. mQuotaTextLink.setCompoundDrawablesWithIntrinsicBounds(test, null, null, null);
  591. }
  592. };
  593. DisplayUtils.downloadIcon(getUserAccountManager(),
  594. clientFactory,
  595. this,
  596. firstQuota.iconUrl,
  597. target,
  598. R.drawable.ic_link,
  599. size,
  600. size);
  601. } else {
  602. mQuotaTextLink.setVisibility(View.GONE);
  603. }
  604. } else {
  605. mQuotaTextLink.setVisibility(View.GONE);
  606. }
  607. }
  608. }
  609. /**
  610. * checks/highlights the provided menu item if the drawer has been initialized and the menu item exists.
  611. *
  612. * @param menuItemId the menu item to be highlighted
  613. */
  614. protected void setDrawerMenuItemChecked(int menuItemId) {
  615. if (mNavigationView != null && mNavigationView.getMenu().findItem(menuItemId) != null) {
  616. mCheckedMenuItem = menuItemId;
  617. MenuItem currentItem = mNavigationView.getMenu().findItem(menuItemId);
  618. int drawerColor = getResources().getColor(R.color.drawer_text_color);
  619. int activeColor = ThemeUtils.elementColor(this);
  620. currentItem.setChecked(true);
  621. // For each menu item, change the color of the selected item, and of the other items
  622. for (int i = 0; i < mNavigationView.getMenu().size(); i++) {
  623. MenuItem menuItem = mNavigationView.getMenu().getItem(i);
  624. if (menuItem.getIcon() != null) {
  625. if (menuItem == currentItem) {
  626. ThemeUtils.tintDrawable(currentItem.getIcon(), activeColor);
  627. ThemeUtils.tintMenuItemText(currentItem, activeColor);
  628. } else {
  629. ThemeUtils.tintDrawable(menuItem.getIcon(), drawerColor);
  630. ThemeUtils.tintMenuItemText(menuItem, drawerColor);
  631. }
  632. }
  633. }
  634. } else {
  635. Log_OC.w(TAG, "setDrawerMenuItemChecked has been called with invalid menu-item-ID");
  636. }
  637. }
  638. /**
  639. * Retrieves and shows the user quota if available
  640. */
  641. private void getAndDisplayUserQuota() {
  642. // set user space information
  643. Thread t = new Thread(() -> {
  644. final User user = accountManager.getUser();
  645. if (user.isAnonymous()) {
  646. return;
  647. }
  648. final Context context = MainApp.getAppContext();
  649. RemoteOperationResult result = new GetUserInfoRemoteOperation().execute(user.toPlatformAccount(), context);
  650. if (result.isSuccess() && result.getData() != null) {
  651. final UserInfo userInfo = (UserInfo) result.getData().get(0);
  652. final Quota quota = userInfo.getQuota();
  653. if (quota != null) {
  654. final long used = quota.getUsed();
  655. final long total = quota.getTotal();
  656. final int relative = (int) Math.ceil(quota.getRelative());
  657. final long quotaValue = quota.getQuota();
  658. runOnUiThread(() -> {
  659. if (quotaValue > 0 || quotaValue == GetUserInfoRemoteOperation.SPACE_UNLIMITED
  660. || quotaValue == GetUserInfoRemoteOperation.QUOTA_LIMIT_INFO_NOT_AVAILABLE) {
  661. /*
  662. * show quota in case
  663. * it is available and calculated (> 0) or
  664. * in case of legacy servers (==QUOTA_LIMIT_INFO_NOT_AVAILABLE)
  665. */
  666. setQuotaInformation(used, total, relative, quotaValue);
  667. } else {
  668. /*
  669. * quotaValue < 0 means special cases like
  670. * {@link RemoteGetUserQuotaOperation.SPACE_NOT_COMPUTED},
  671. * {@link RemoteGetUserQuotaOperation.SPACE_UNKNOWN} or
  672. * {@link RemoteGetUserQuotaOperation.SPACE_UNLIMITED}
  673. * thus don't display any quota information.
  674. */
  675. showQuota(false);
  676. }
  677. });
  678. }
  679. }
  680. });
  681. t.start();
  682. }
  683. private void updateExternalLinksInDrawer() {
  684. if (mNavigationView != null && getBaseContext().getResources().getBoolean(R.bool.show_external_links)) {
  685. mNavigationView.getMenu().removeGroup(R.id.drawer_menu_external_links);
  686. float density = getResources().getDisplayMetrics().density;
  687. final int size = Math.round(24 * density);
  688. int greyColor = ContextCompat.getColor(this, R.color.drawer_menu_icon);
  689. for (final ExternalLink link : externalLinksProvider.getExternalLink(ExternalLinkType.LINK)) {
  690. int id = mNavigationView.getMenu().add(R.id.drawer_menu_external_links,
  691. MENU_ITEM_EXTERNAL_LINK + link.id, MENU_ORDER_EXTERNAL_LINKS, link.name)
  692. .setCheckable(true).getItemId();
  693. MenuSimpleTarget target = new MenuSimpleTarget<Drawable>(id) {
  694. @Override
  695. public void onResourceReady(Drawable resource, GlideAnimation glideAnimation) {
  696. setExternalLinkIcon(getIdMenuItem(), resource, greyColor);
  697. }
  698. @Override
  699. public void onLoadFailed(Exception e, Drawable errorDrawable) {
  700. super.onLoadFailed(e, errorDrawable);
  701. setExternalLinkIcon(getIdMenuItem(), errorDrawable, greyColor);
  702. }
  703. };
  704. DisplayUtils.downloadIcon(getUserAccountManager(),
  705. clientFactory,
  706. this,
  707. link.iconUrl,
  708. target,
  709. R.drawable.ic_link,
  710. size,
  711. size);
  712. }
  713. setDrawerMenuItemChecked(mCheckedMenuItem);
  714. }
  715. }
  716. private void setExternalLinkIcon(int id, Drawable drawable, int greyColor) {
  717. MenuItem menuItem = mNavigationView.getMenu().findItem(id);
  718. if (menuItem != null) {
  719. if (drawable != null) {
  720. menuItem.setIcon(ThemeUtils.tintDrawable(drawable, greyColor));
  721. } else {
  722. menuItem.setIcon(R.drawable.ic_link);
  723. }
  724. }
  725. }
  726. @Override
  727. protected void onCreate(Bundle savedInstanceState) {
  728. super.onCreate(savedInstanceState);
  729. if (savedInstanceState != null) {
  730. mIsAccountChooserActive = savedInstanceState.getBoolean(KEY_IS_ACCOUNT_CHOOSER_ACTIVE, false);
  731. mCheckedMenuItem = savedInstanceState.getInt(KEY_CHECKED_MENU_ITEM, Menu.NONE);
  732. }
  733. externalLinksProvider = new ExternalLinksProvider(getContentResolver());
  734. arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver());
  735. }
  736. @Override
  737. protected void onSaveInstanceState(@NonNull Bundle outState) {
  738. super.onSaveInstanceState(outState);
  739. outState.putBoolean(KEY_IS_ACCOUNT_CHOOSER_ACTIVE, mIsAccountChooserActive);
  740. outState.putInt(KEY_CHECKED_MENU_ITEM, mCheckedMenuItem);
  741. }
  742. @Override
  743. public void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
  744. super.onRestoreInstanceState(savedInstanceState);
  745. mIsAccountChooserActive = savedInstanceState.getBoolean(KEY_IS_ACCOUNT_CHOOSER_ACTIVE, false);
  746. mCheckedMenuItem = savedInstanceState.getInt(KEY_CHECKED_MENU_ITEM, Menu.NONE);
  747. // check/highlight the menu item if present
  748. if (mCheckedMenuItem > Menu.NONE || mCheckedMenuItem < Menu.NONE) {
  749. setDrawerMenuItemChecked(mCheckedMenuItem);
  750. }
  751. }
  752. @Override
  753. protected void onPostCreate(Bundle savedInstanceState) {
  754. super.onPostCreate(savedInstanceState);
  755. // Sync the toggle state after onRestoreInstanceState has occurred.
  756. if (mDrawerToggle != null) {
  757. mDrawerToggle.syncState();
  758. if (isDrawerOpen()) {
  759. mDrawerToggle.setDrawerIndicatorEnabled(true);
  760. }
  761. }
  762. updateExternalLinksInDrawer();
  763. updateQuotaLink();
  764. }
  765. @Override
  766. public void onConfigurationChanged(@NonNull Configuration newConfig) {
  767. super.onConfigurationChanged(newConfig);
  768. if (mDrawerToggle != null) {
  769. mDrawerToggle.onConfigurationChanged(newConfig);
  770. }
  771. }
  772. @Override
  773. public void onBackPressed() {
  774. if (isDrawerOpen()) {
  775. closeDrawer();
  776. return;
  777. }
  778. super.onBackPressed();
  779. }
  780. @Override
  781. protected void onResume() {
  782. super.onResume();
  783. setDrawerMenuItemChecked(mCheckedMenuItem);
  784. }
  785. @Override
  786. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  787. super.onActivityResult(requestCode, resultCode, data);
  788. // update Account list and active account if Manage Account activity replies with
  789. // - ACCOUNT_LIST_CHANGED = true
  790. // - RESULT_OK
  791. if (requestCode == ACTION_MANAGE_ACCOUNTS && resultCode == RESULT_OK
  792. && data.getBooleanExtra(ManageAccountsActivity.KEY_ACCOUNT_LIST_CHANGED, false)) {
  793. // current account has changed
  794. if (data.getBooleanExtra(ManageAccountsActivity.KEY_CURRENT_ACCOUNT_CHANGED, false)) {
  795. setAccount(accountManager.getCurrentAccount(), false);
  796. restart();
  797. }
  798. } else if (requestCode == PassCodeManager.PASSCODE_ACTIVITY &&
  799. Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && data != null) {
  800. int result = data.getIntExtra(RequestCredentialsActivity.KEY_CHECK_RESULT,
  801. RequestCredentialsActivity.KEY_CHECK_RESULT_FALSE);
  802. if (result == RequestCredentialsActivity.KEY_CHECK_RESULT_CANCEL) {
  803. Log_OC.d(TAG, "PassCodeManager cancelled");
  804. preferences.setLockTimestamp(0);
  805. finish();
  806. }
  807. }
  808. }
  809. /**
  810. * Quota view can be either at navigation bottom or header
  811. *
  812. * @param id the view's id
  813. * @return The view if found or <code>null</code> otherwise.
  814. */
  815. private View findQuotaViewById(int id) {
  816. View v = ((NavigationView) findViewById(R.id.nav_view)).getHeaderView(0).findViewById(id);
  817. if (v != null) {
  818. return v;
  819. } else {
  820. return findViewById(id);
  821. }
  822. }
  823. /**
  824. * restart helper method which is called after a changing the current account.
  825. */
  826. protected abstract void restart();
  827. @Override
  828. public void avatarGenerated(Drawable avatarDrawable, Object callContext) {
  829. if (callContext instanceof MenuItem) {
  830. MenuItem menuItem = (MenuItem) callContext;
  831. menuItem.setIcon(avatarDrawable);
  832. } else if (callContext instanceof ImageView) {
  833. ImageView imageView = (ImageView) callContext;
  834. imageView.setImageDrawable(avatarDrawable);
  835. } else if (callContext instanceof MaterialButton) {
  836. MaterialButton materialButton = (MaterialButton) callContext;
  837. materialButton.setIcon(avatarDrawable);
  838. }
  839. }
  840. @Override
  841. public boolean shouldCallGeneratedCallback(String tag, Object callContext) {
  842. if (callContext instanceof MenuItem) {
  843. MenuItem menuItem = (MenuItem) callContext;
  844. return String.valueOf(menuItem.getTitle()).equals(tag);
  845. } else if (callContext instanceof ImageView) {
  846. ImageView imageView = (ImageView) callContext;
  847. return String.valueOf(imageView.getTag()).equals(tag);
  848. } else if (callContext instanceof MaterialButton) {
  849. MaterialButton materialButton = (MaterialButton) callContext;
  850. return String.valueOf(materialButton.getTag()).equals(tag);
  851. }
  852. return false;
  853. }
  854. /**
  855. * Adds other listeners to react on changes of the drawer layout.
  856. *
  857. * @param listener Object interested in changes of the drawer layout.
  858. */
  859. public void addDrawerListener(DrawerLayout.DrawerListener listener) {
  860. if (mDrawerLayout != null) {
  861. mDrawerLayout.addDrawerListener(listener);
  862. } else {
  863. Log_OC.e(TAG, "Drawer layout not ready to add drawer listener");
  864. }
  865. }
  866. public boolean isDrawerIndicatorAvailable() {
  867. return true;
  868. }
  869. @Override
  870. protected void onStart() {
  871. super.onStart();
  872. EventBus.getDefault().register(this);
  873. }
  874. @Override
  875. protected void onStop() {
  876. if (preferences.getLockTimestamp() != 0) {
  877. preferences.setLockTimestamp(SystemClock.elapsedRealtime());
  878. }
  879. EventBus.getDefault().unregister(this);
  880. super.onStop();
  881. }
  882. @Subscribe(threadMode = ThreadMode.MAIN)
  883. public void onAccountRemovedEvent(AccountRemovedEvent event) {
  884. restart();
  885. }
  886. /**
  887. * Retrieves external links via api from 'external' app
  888. */
  889. public void fetchExternalLinks(final boolean force) {
  890. if (getBaseContext().getResources().getBoolean(R.bool.show_external_links)) {
  891. Thread t = new Thread(() -> {
  892. // fetch capabilities as early as possible
  893. if ((getCapabilities() == null || getCapabilities().getAccountName().isEmpty())
  894. && getStorageManager() != null) {
  895. GetCapabilitiesOperation getCapabilities = new GetCapabilitiesOperation();
  896. getCapabilities.execute(getStorageManager(), getBaseContext());
  897. }
  898. User user = accountManager.getUser();
  899. String name = user.getAccountName();
  900. if (getStorageManager() != null && getStorageManager().getCapability(name).getExternalLinks().isTrue()) {
  901. int count = arbitraryDataProvider.getIntegerValue(FilesSyncHelper.GLOBAL,
  902. FileActivity.APP_OPENED_COUNT);
  903. if (count > 10 || count == -1 || force) {
  904. if (force) {
  905. Log_OC.d("ExternalLinks", "force update");
  906. }
  907. arbitraryDataProvider.storeOrUpdateKeyValue(FilesSyncHelper.GLOBAL,
  908. FileActivity.APP_OPENED_COUNT, "0");
  909. Log_OC.d("ExternalLinks", "update via api");
  910. RemoteOperation getExternalLinksOperation = new ExternalLinksOperation();
  911. RemoteOperationResult result = getExternalLinksOperation.execute(user.toPlatformAccount(), this);
  912. if (result.isSuccess() && result.getData() != null) {
  913. externalLinksProvider.deleteAllExternalLinks();
  914. ArrayList<ExternalLink> externalLinks = (ArrayList<ExternalLink>) (Object) result.getData();
  915. for (ExternalLink link : externalLinks) {
  916. externalLinksProvider.storeExternalLink(link);
  917. }
  918. }
  919. } else {
  920. arbitraryDataProvider.storeOrUpdateKeyValue(FilesSyncHelper.GLOBAL,
  921. FileActivity.APP_OPENED_COUNT, String.valueOf(count + 1));
  922. }
  923. } else {
  924. externalLinksProvider.deleteAllExternalLinks();
  925. Log_OC.d("ExternalLinks", "links disabled");
  926. }
  927. runOnUiThread(this::updateExternalLinksInDrawer);
  928. });
  929. t.start();
  930. }
  931. }
  932. }