SyncedFoldersActivity.java 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. /*
  2. * Nextcloud Android client application
  3. *
  4. * @author Andy Scherzinger
  5. * Copyright (C) 2016 Andy Scherzinger
  6. * Copyright (C) 2016 Nextcloud
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  10. * License as published by the Free Software Foundation; either
  11. * version 3 of the License, or any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public
  19. * License along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. package com.owncloud.android.ui.activity;
  22. import android.accounts.Account;
  23. import android.annotation.SuppressLint;
  24. import android.app.Activity;
  25. import android.app.NotificationManager;
  26. import android.content.Context;
  27. import android.content.Intent;
  28. import android.content.pm.PackageManager;
  29. import android.net.Uri;
  30. import android.os.Build;
  31. import android.os.Bundle;
  32. import android.os.PowerManager;
  33. import android.text.TextUtils;
  34. import android.util.Log;
  35. import android.view.Menu;
  36. import android.view.MenuInflater;
  37. import android.view.MenuItem;
  38. import android.view.View;
  39. import android.widget.LinearLayout;
  40. import android.widget.TextView;
  41. import com.google.android.material.bottomnavigation.BottomNavigationView;
  42. import com.owncloud.android.BuildConfig;
  43. import com.owncloud.android.MainApp;
  44. import com.owncloud.android.R;
  45. import com.owncloud.android.authentication.AccountUtils;
  46. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  47. import com.owncloud.android.datamodel.MediaFolder;
  48. import com.owncloud.android.datamodel.MediaFolderType;
  49. import com.owncloud.android.datamodel.MediaProvider;
  50. import com.owncloud.android.datamodel.OCFile;
  51. import com.owncloud.android.datamodel.SyncedFolder;
  52. import com.owncloud.android.datamodel.SyncedFolderDisplayItem;
  53. import com.owncloud.android.datamodel.SyncedFolderProvider;
  54. import com.owncloud.android.files.services.FileUploader;
  55. import com.owncloud.android.jobs.MediaFoldersDetectionJob;
  56. import com.owncloud.android.jobs.NotificationJob;
  57. import com.owncloud.android.ui.adapter.SyncedFolderAdapter;
  58. import com.owncloud.android.ui.decoration.MediaGridItemDecoration;
  59. import com.owncloud.android.ui.dialog.SyncedFolderPreferencesDialogFragment;
  60. import com.owncloud.android.ui.dialog.parcel.SyncedFolderParcelable;
  61. import com.owncloud.android.utils.DisplayUtils;
  62. import com.owncloud.android.utils.FilesSyncHelper;
  63. import com.owncloud.android.utils.PermissionUtil;
  64. import com.owncloud.android.utils.ThemeUtils;
  65. import java.io.File;
  66. import java.util.ArrayList;
  67. import java.util.Arrays;
  68. import java.util.Collections;
  69. import java.util.HashMap;
  70. import java.util.List;
  71. import java.util.Locale;
  72. import java.util.Map;
  73. import androidx.annotation.NonNull;
  74. import androidx.appcompat.app.ActionBar;
  75. import androidx.appcompat.app.AlertDialog;
  76. import androidx.drawerlayout.widget.DrawerLayout;
  77. import androidx.fragment.app.FragmentManager;
  78. import androidx.fragment.app.FragmentTransaction;
  79. import androidx.recyclerview.widget.GridLayoutManager;
  80. import androidx.recyclerview.widget.RecyclerView;
  81. import static android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS;
  82. import static com.owncloud.android.datamodel.SyncedFolderDisplayItem.UNPERSISTED_ID;
  83. /**
  84. * Activity displaying all auto-synced folders and/or instant upload media folders.
  85. */
  86. public class SyncedFoldersActivity extends FileActivity implements SyncedFolderAdapter.ClickListener,
  87. SyncedFolderPreferencesDialogFragment.OnSyncedFolderPreferenceListener {
  88. public static final String[] PRIORITIZED_FOLDERS = new String[]{"Camera", "Screenshots"};
  89. public static final List<String> SPECIAL_MANUFACTURER = Arrays.asList("Samsung", "Huawei", "Xiaomi");
  90. public static final String EXTRA_SHOW_SIDEBAR = "SHOW_SIDEBAR";
  91. private static final String SYNCED_FOLDER_PREFERENCES_DIALOG_TAG = "SYNCED_FOLDER_PREFERENCES_DIALOG";
  92. private static final String TAG = SyncedFoldersActivity.class.getSimpleName();
  93. private RecyclerView mRecyclerView;
  94. private SyncedFolderAdapter mAdapter;
  95. private LinearLayout mProgress;
  96. private TextView mEmpty;
  97. private SyncedFolderProvider mSyncedFolderProvider;
  98. private SyncedFolderPreferencesDialogFragment mSyncedFolderPreferencesDialogFragment;
  99. private boolean showSidebar = true;
  100. private String path;
  101. private int type;
  102. @Override
  103. protected void onCreate(Bundle savedInstanceState) {
  104. super.onCreate(savedInstanceState);
  105. if (getIntent().getExtras() != null) {
  106. showSidebar = getIntent().getExtras().getBoolean(EXTRA_SHOW_SIDEBAR);
  107. }
  108. setContentView(R.layout.synced_folders_layout);
  109. String account;
  110. Account currentAccount;
  111. if (getIntent() != null && getIntent().getExtras() != null) {
  112. account = getIntent().getExtras().getString(NotificationJob.KEY_NOTIFICATION_ACCOUNT);
  113. currentAccount = getAccount();
  114. if (account != null && currentAccount != null && !account.equalsIgnoreCase(currentAccount.name)) {
  115. AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account);
  116. setAccount(AccountUtils.getCurrentOwnCloudAccount(this));
  117. }
  118. path = getIntent().getStringExtra(MediaFoldersDetectionJob.KEY_MEDIA_FOLDER_PATH);
  119. type = getIntent().getIntExtra(MediaFoldersDetectionJob.KEY_MEDIA_FOLDER_TYPE, -1);
  120. // Cancel notification
  121. int notificationId = getIntent().getIntExtra(MediaFoldersDetectionJob.NOTIFICATION_ID, 0);
  122. NotificationManager notificationManager =
  123. (NotificationManager) getSystemService(Activity.NOTIFICATION_SERVICE);
  124. notificationManager.cancel(notificationId);
  125. }
  126. // setup toolbar
  127. setupToolbar();
  128. if (getSupportActionBar() != null){
  129. getSupportActionBar().setTitle(R.string.drawer_synced_folders);
  130. }
  131. // setup drawer
  132. setupDrawer(R.id.nav_synced_folders);
  133. if (!showSidebar) {
  134. setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
  135. mDrawerToggle.setDrawerIndicatorEnabled(false);
  136. }
  137. setupContent();
  138. ActionBar actionBar = getSupportActionBar();
  139. if (actionBar != null) {
  140. ThemeUtils.setColoredTitle(getSupportActionBar(), getString(R.string.drawer_synced_folders), this);
  141. actionBar.setDisplayHomeAsUpEnabled(true);
  142. }
  143. if (ThemeUtils.themingEnabled(this)) {
  144. setTheme(R.style.FallbackThemingTheme);
  145. }
  146. }
  147. @Override
  148. public boolean onCreateOptionsMenu(Menu menu) {
  149. MenuInflater inflater = getMenuInflater();
  150. inflater.inflate(R.menu.synced_folders_menu, menu);
  151. return true;
  152. }
  153. /**
  154. * sets up the UI elements and loads all media/synced folders.
  155. */
  156. private void setupContent() {
  157. mRecyclerView = findViewById(android.R.id.list);
  158. mProgress = findViewById(android.R.id.progress);
  159. mEmpty = findViewById(android.R.id.empty);
  160. final int gridWidth = getResources().getInteger(R.integer.media_grid_width);
  161. boolean lightVersion = getResources().getBoolean(R.bool.syncedFolder_light);
  162. mAdapter = new SyncedFolderAdapter(this, gridWidth, this, lightVersion);
  163. mSyncedFolderProvider = new SyncedFolderProvider(getContentResolver());
  164. final GridLayoutManager lm = new GridLayoutManager(this, gridWidth);
  165. mAdapter.setLayoutManager(lm);
  166. int spacing = getResources().getDimensionPixelSize(R.dimen.media_grid_spacing);
  167. mRecyclerView.addItemDecoration(new MediaGridItemDecoration(spacing));
  168. mRecyclerView.setLayoutManager(lm);
  169. mRecyclerView.setAdapter(mAdapter);
  170. BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation_view);
  171. if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) {
  172. bottomNavigationView.setVisibility(View.VISIBLE);
  173. DisplayUtils.setupBottomBar(bottomNavigationView, getResources(), this, -1);
  174. }
  175. load(gridWidth * 2, false);
  176. }
  177. /**
  178. * loads all media/synced folders, adds them to the recycler view adapter and shows the list.
  179. *
  180. * @param perFolderMediaItemLimit the amount of media items to be loaded/shown per media folder
  181. */
  182. private void load(final int perFolderMediaItemLimit, boolean force) {
  183. if (mAdapter.getItemCount() > 0 && !force) {
  184. return;
  185. }
  186. setListShown(false);
  187. final List<MediaFolder> mediaFolders = MediaProvider.getImageFolders(getContentResolver(),
  188. perFolderMediaItemLimit, this, false);
  189. mediaFolders.addAll(MediaProvider.getVideoFolders(getContentResolver(), perFolderMediaItemLimit,
  190. this, false));
  191. List<SyncedFolder> syncedFolderArrayList = mSyncedFolderProvider.getSyncedFolders();
  192. List<SyncedFolder> currentAccountSyncedFoldersList = new ArrayList<>();
  193. Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(this);
  194. for (SyncedFolder syncedFolder : syncedFolderArrayList) {
  195. if (currentAccount != null && syncedFolder.getAccount().equals(currentAccount.name)) {
  196. // delete non-existing & disabled synced folders
  197. if (!new File(syncedFolder.getLocalPath()).exists() && !syncedFolder.isEnabled()) {
  198. mSyncedFolderProvider.deleteSyncedFolder(syncedFolder.getId());
  199. } else {
  200. currentAccountSyncedFoldersList.add(syncedFolder);
  201. }
  202. }
  203. }
  204. List<SyncedFolderDisplayItem> syncFolderItems = sortSyncedFolderItems(
  205. mergeFolderData(currentAccountSyncedFoldersList, mediaFolders));
  206. mAdapter.setSyncFolderItems(syncFolderItems);
  207. mAdapter.notifyDataSetChanged();
  208. setListShown(true);
  209. if (!TextUtils.isEmpty(path)) {
  210. int section = mAdapter.getSectionByLocalPathAndType(path, type);
  211. if (section >= 0) {
  212. onSyncFolderSettingsClick(section, mAdapter.get(section));
  213. }
  214. }
  215. }
  216. /**
  217. * Sorts list of {@link SyncedFolderDisplayItem}s.
  218. *
  219. * @param syncFolderItemList list of items to be sorted
  220. * @return sorted list of items
  221. */
  222. public static List<SyncedFolderDisplayItem> sortSyncedFolderItems(List<SyncedFolderDisplayItem>
  223. syncFolderItemList) {
  224. Collections.sort(syncFolderItemList, (f1, f2) -> {
  225. if (f1 == null && f2 == null) {
  226. return 0;
  227. } else if (f1 == null) {
  228. return -1;
  229. } else if (f2 == null) {
  230. return 1;
  231. } else if (f1.isEnabled() && f2.isEnabled()) {
  232. return f1.getFolderName().toLowerCase(Locale.getDefault()).compareTo(
  233. f2.getFolderName().toLowerCase(Locale.getDefault()));
  234. } else if (f1.isEnabled()) {
  235. return -1;
  236. } else if (f2.isEnabled()) {
  237. return 1;
  238. } else if (f1.getFolderName() == null && f2.getFolderName() == null) {
  239. return 0;
  240. } else if (f1.getFolderName() == null) {
  241. return -1;
  242. } else if (f2.getFolderName() == null) {
  243. return 1;
  244. }
  245. for (String folder : PRIORITIZED_FOLDERS) {
  246. if (folder.equals(f1.getFolderName()) && folder.equals(f2.getFolderName())) {
  247. return 0;
  248. } else if (folder.equals(f1.getFolderName())) {
  249. return -1;
  250. } else if (folder.equals(f2.getFolderName())) {
  251. return 1;
  252. }
  253. }
  254. return f1.getFolderName().toLowerCase(Locale.getDefault()).compareTo(
  255. f2.getFolderName().toLowerCase(Locale.getDefault()));
  256. });
  257. return syncFolderItemList;
  258. }
  259. /**
  260. * merges two lists of {@link SyncedFolder} and {@link MediaFolder} items into one of SyncedFolderItems.
  261. *
  262. * @param syncedFolders the synced folders
  263. * @param mediaFolders the media folders
  264. * @return the merged list of SyncedFolderItems
  265. */
  266. @NonNull
  267. private List<SyncedFolderDisplayItem> mergeFolderData(List<SyncedFolder> syncedFolders,
  268. @NonNull List<MediaFolder> mediaFolders) {
  269. Map<String, SyncedFolder> syncedFoldersMap = createSyncedFoldersMap(syncedFolders);
  270. List<SyncedFolderDisplayItem> result = new ArrayList<>();
  271. for (MediaFolder mediaFolder : mediaFolders) {
  272. if (syncedFoldersMap.containsKey(mediaFolder.absolutePath + "-" + mediaFolder.type)) {
  273. SyncedFolder syncedFolder = syncedFoldersMap.get(mediaFolder.absolutePath + "-" + mediaFolder.type);
  274. syncedFoldersMap.remove(mediaFolder.absolutePath + "-" + mediaFolder.type);
  275. if (MediaFolderType.CUSTOM == syncedFolder.getType()) {
  276. result.add(createSyncedFolderWithoutMediaFolder(syncedFolder));
  277. } else {
  278. result.add(createSyncedFolder(syncedFolder, mediaFolder));
  279. }
  280. } else {
  281. result.add(createSyncedFolderFromMediaFolder(mediaFolder));
  282. }
  283. }
  284. for (SyncedFolder syncedFolder : syncedFoldersMap.values()) {
  285. result.add(createSyncedFolderWithoutMediaFolder(syncedFolder));
  286. }
  287. return result;
  288. }
  289. @NonNull
  290. private SyncedFolderDisplayItem createSyncedFolderWithoutMediaFolder(@NonNull SyncedFolder syncedFolder) {
  291. File localFolder = new File(syncedFolder.getLocalPath());
  292. File[] files = getFileList(localFolder);
  293. List<String> filePaths = getDisplayFilePathList(files);
  294. return new SyncedFolderDisplayItem(
  295. syncedFolder.getId(),
  296. syncedFolder.getLocalPath(),
  297. syncedFolder.getRemotePath(),
  298. syncedFolder.getWifiOnly(),
  299. syncedFolder.getChargingOnly(),
  300. syncedFolder.getSubfolderByDate(),
  301. syncedFolder.getAccount(),
  302. syncedFolder.getUploadAction(),
  303. syncedFolder.isEnabled(),
  304. filePaths,
  305. localFolder.getName(),
  306. files.length,
  307. syncedFolder.getType());
  308. }
  309. /**
  310. * creates a SyncedFolderDisplayItem merging a {@link SyncedFolder} and a {@link MediaFolder} object instance.
  311. *
  312. * @param syncedFolder the synced folder object
  313. * @param mediaFolder the media folder object
  314. * @return the created SyncedFolderDisplayItem
  315. */
  316. @NonNull
  317. private SyncedFolderDisplayItem createSyncedFolder(@NonNull SyncedFolder syncedFolder, @NonNull MediaFolder mediaFolder) {
  318. return new SyncedFolderDisplayItem(
  319. syncedFolder.getId(),
  320. syncedFolder.getLocalPath(),
  321. syncedFolder.getRemotePath(),
  322. syncedFolder.getWifiOnly(),
  323. syncedFolder.getChargingOnly(),
  324. syncedFolder.getSubfolderByDate(),
  325. syncedFolder.getAccount(),
  326. syncedFolder.getUploadAction(),
  327. syncedFolder.isEnabled(),
  328. mediaFolder.filePaths,
  329. mediaFolder.folderName,
  330. mediaFolder.numberOfFiles,
  331. mediaFolder.type);
  332. }
  333. /**
  334. * creates a {@link SyncedFolderDisplayItem} based on a {@link MediaFolder} object instance.
  335. *
  336. * @param mediaFolder the media folder object
  337. * @return the created SyncedFolderDisplayItem
  338. */
  339. @NonNull
  340. private SyncedFolderDisplayItem createSyncedFolderFromMediaFolder(@NonNull MediaFolder mediaFolder) {
  341. return new SyncedFolderDisplayItem(
  342. UNPERSISTED_ID,
  343. mediaFolder.absolutePath,
  344. getString(R.string.instant_upload_path) + "/" + mediaFolder.folderName,
  345. true,
  346. false,
  347. false,
  348. getAccount().name,
  349. FileUploader.LOCAL_BEHAVIOUR_FORGET,
  350. false,
  351. mediaFolder.filePaths,
  352. mediaFolder.folderName,
  353. mediaFolder.numberOfFiles,
  354. mediaFolder.type);
  355. }
  356. private File[] getFileList(File localFolder) {
  357. File[] files = localFolder.listFiles(pathname -> !pathname.isDirectory());
  358. if (files != null) {
  359. Arrays.sort(files, (f1, f2) -> Long.compare(f1.lastModified(), f2.lastModified()));
  360. } else {
  361. files = new File[]{};
  362. }
  363. return files;
  364. }
  365. private List<String> getDisplayFilePathList(File... files) {
  366. List<String> filePaths = null;
  367. if (files != null && files.length > 0) {
  368. filePaths = new ArrayList<>();
  369. for (int i = 0; i < 7 && i < files.length; i++) {
  370. filePaths.add(files[i].getAbsolutePath());
  371. }
  372. }
  373. return filePaths;
  374. }
  375. /**
  376. * creates a lookup map for a list of given {@link SyncedFolder}s with their local path as the key.
  377. *
  378. * @param syncFolders list of {@link SyncedFolder}s
  379. * @return the lookup map for {@link SyncedFolder}s
  380. */
  381. @NonNull
  382. private Map<String, SyncedFolder> createSyncedFoldersMap(List<SyncedFolder> syncFolders) {
  383. Map<String, SyncedFolder> result = new HashMap<>();
  384. if (syncFolders != null) {
  385. for (SyncedFolder syncFolder : syncFolders) {
  386. result.put(syncFolder.getLocalPath() + "-" + syncFolder.getType(), syncFolder);
  387. }
  388. }
  389. return result;
  390. }
  391. /**
  392. * show/hide recycler view list or the empty message / progress info.
  393. *
  394. * @param shown flag if list should be shown
  395. */
  396. private void setListShown(boolean shown) {
  397. if (mRecyclerView != null) {
  398. mRecyclerView.setVisibility(shown ? View.VISIBLE : View.GONE);
  399. mProgress.setVisibility(shown ? View.GONE : View.VISIBLE);
  400. mEmpty.setVisibility(shown && mAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
  401. }
  402. }
  403. @Override
  404. public boolean onOptionsItemSelected(MenuItem item) {
  405. boolean result = true;
  406. switch (item.getItemId()) {
  407. case android.R.id.home: {
  408. if (showSidebar) {
  409. if (isDrawerOpen()) {
  410. closeDrawer();
  411. } else {
  412. openDrawer();
  413. }
  414. } else {
  415. Intent settingsIntent = new Intent(getApplicationContext(), Preferences.class);
  416. startActivity(settingsIntent);
  417. }
  418. break;
  419. }
  420. case R.id.action_create_custom_folder: {
  421. Log.d(TAG, "Show custom folder dialog");
  422. SyncedFolderDisplayItem emptyCustomFolder = new SyncedFolderDisplayItem(
  423. SyncedFolder.UNPERSISTED_ID, null, null, true, false,
  424. false, getAccount().name,
  425. FileUploader.LOCAL_BEHAVIOUR_FORGET, false, null, MediaFolderType.CUSTOM);
  426. onSyncFolderSettingsClick(0, emptyCustomFolder);
  427. }
  428. default:
  429. result = super.onOptionsItemSelected(item);
  430. break;
  431. }
  432. return result;
  433. }
  434. @Override
  435. public void restart() {
  436. Intent i = new Intent(this, FileDisplayActivity.class);
  437. i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  438. startActivity(i);
  439. }
  440. @Override
  441. public void showFiles(boolean onDeviceOnly) {
  442. MainApp.showOnlyFilesOnDevice(onDeviceOnly);
  443. Intent fileDisplayActivity = new Intent(getApplicationContext(), FileDisplayActivity.class);
  444. fileDisplayActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  445. startActivity(fileDisplayActivity);
  446. }
  447. @Override
  448. public void onSyncStatusToggleClick(int section, SyncedFolderDisplayItem syncedFolderDisplayItem) {
  449. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(MainApp.getAppContext().
  450. getContentResolver());
  451. if (syncedFolderDisplayItem.getId() > UNPERSISTED_ID) {
  452. mSyncedFolderProvider.updateSyncedFolderEnabled(syncedFolderDisplayItem.getId(),
  453. syncedFolderDisplayItem.isEnabled());
  454. } else {
  455. long storedId = mSyncedFolderProvider.storeSyncedFolder(syncedFolderDisplayItem);
  456. if (storedId != -1) {
  457. syncedFolderDisplayItem.setId(storedId);
  458. }
  459. }
  460. if (syncedFolderDisplayItem.isEnabled()) {
  461. FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolderDisplayItem);
  462. showBatteryOptimizationInfo();
  463. } else {
  464. String syncedFolderInitiatedKey = "syncedFolderIntitiated_" + syncedFolderDisplayItem.getId();
  465. arbitraryDataProvider.deleteKeyForAccount("global", syncedFolderInitiatedKey);
  466. }
  467. }
  468. @Override
  469. public void onSyncFolderSettingsClick(int section, SyncedFolderDisplayItem syncedFolderDisplayItem) {
  470. FragmentManager fm = getSupportFragmentManager();
  471. FragmentTransaction ft = fm.beginTransaction();
  472. ft.addToBackStack(null);
  473. mSyncedFolderPreferencesDialogFragment = SyncedFolderPreferencesDialogFragment.newInstance(
  474. syncedFolderDisplayItem, section);
  475. mSyncedFolderPreferencesDialogFragment.show(ft, SYNCED_FOLDER_PREFERENCES_DIALOG_TAG);
  476. }
  477. @Override
  478. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  479. if (requestCode == SyncedFolderPreferencesDialogFragment.REQUEST_CODE__SELECT_REMOTE_FOLDER
  480. && resultCode == RESULT_OK && mSyncedFolderPreferencesDialogFragment != null) {
  481. OCFile chosenFolder = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  482. mSyncedFolderPreferencesDialogFragment.setRemoteFolderSummary(chosenFolder.getRemotePath());
  483. }
  484. if (requestCode == SyncedFolderPreferencesDialogFragment.REQUEST_CODE__SELECT_LOCAL_FOLDER
  485. && resultCode == RESULT_OK && mSyncedFolderPreferencesDialogFragment != null) {
  486. String localPath = data.getStringExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
  487. mSyncedFolderPreferencesDialogFragment.setLocalFolderSummary(localPath);
  488. } else {
  489. super.onActivityResult(requestCode, resultCode, data);
  490. }
  491. }
  492. @Override
  493. public void onSaveSyncedFolderPreference(SyncedFolderParcelable syncedFolder) {
  494. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(MainApp.getAppContext().
  495. getContentResolver());
  496. // custom folders newly created aren't in the list already,
  497. // so triggering a refresh
  498. if (MediaFolderType.CUSTOM.equals(syncedFolder.getType()) && syncedFolder.getId() == UNPERSISTED_ID) {
  499. SyncedFolderDisplayItem newCustomFolder = new SyncedFolderDisplayItem(
  500. SyncedFolder.UNPERSISTED_ID, syncedFolder.getLocalPath(), syncedFolder.getRemotePath(),
  501. syncedFolder.getWifiOnly(), syncedFolder.getChargingOnly(), syncedFolder.getSubfolderByDate(),
  502. syncedFolder.getAccount(), syncedFolder.getUploadAction(), syncedFolder.getEnabled(),
  503. new File(syncedFolder.getLocalPath()).getName(), syncedFolder.getType());
  504. long storedId = mSyncedFolderProvider.storeSyncedFolder(newCustomFolder);
  505. if (storedId != -1) {
  506. newCustomFolder.setId(storedId);
  507. if (newCustomFolder.isEnabled()) {
  508. FilesSyncHelper.insertAllDBEntriesForSyncedFolder(newCustomFolder);
  509. } else {
  510. String syncedFolderInitiatedKey = "syncedFolderIntitiated_" + newCustomFolder.getId();
  511. arbitraryDataProvider.deleteKeyForAccount("global", syncedFolderInitiatedKey);
  512. }
  513. }
  514. mAdapter.addSyncFolderItem(newCustomFolder);
  515. } else {
  516. SyncedFolderDisplayItem item = mAdapter.get(syncedFolder.getSection());
  517. item = updateSyncedFolderItem(item, syncedFolder.getLocalPath(), syncedFolder.getRemotePath(), syncedFolder
  518. .getWifiOnly(), syncedFolder.getChargingOnly(), syncedFolder.getSubfolderByDate(), syncedFolder
  519. .getUploadAction(), syncedFolder.getEnabled());
  520. if (syncedFolder.getId() == UNPERSISTED_ID) {
  521. // newly set up folder sync config
  522. long storedId = mSyncedFolderProvider.storeSyncedFolder(item);
  523. if (storedId != -1) {
  524. item.setId(storedId);
  525. if (item.isEnabled()) {
  526. FilesSyncHelper.insertAllDBEntriesForSyncedFolder(item);
  527. } else {
  528. String syncedFolderInitiatedKey = "syncedFolderIntitiated_" + item.getId();
  529. arbitraryDataProvider.deleteKeyForAccount("global", syncedFolderInitiatedKey);
  530. }
  531. }
  532. } else {
  533. // existing synced folder setup to be updated
  534. mSyncedFolderProvider.updateSyncFolder(item);
  535. if (item.isEnabled()) {
  536. FilesSyncHelper.insertAllDBEntriesForSyncedFolder(item);
  537. } else {
  538. String syncedFolderInitiatedKey = "syncedFolderIntitiated_" + item.getId();
  539. arbitraryDataProvider.deleteKeyForAccount("global", syncedFolderInitiatedKey);
  540. }
  541. }
  542. mAdapter.setSyncFolderItem(syncedFolder.getSection(), item);
  543. }
  544. mSyncedFolderPreferencesDialogFragment = null;
  545. if (syncedFolder.getEnabled()) {
  546. showBatteryOptimizationInfo();
  547. }
  548. }
  549. @Override
  550. public void onCancelSyncedFolderPreference() {
  551. mSyncedFolderPreferencesDialogFragment = null;
  552. }
  553. @Override
  554. public void onDeleteSyncedFolderPreference(SyncedFolderParcelable syncedFolder) {
  555. mSyncedFolderProvider.deleteSyncedFolder(syncedFolder.getId());
  556. mAdapter.removeItem(syncedFolder.getSection());
  557. }
  558. /**
  559. * update given synced folder with the given values.
  560. *
  561. * @param item the synced folder to be updated
  562. * @param localPath the local path
  563. * @param remotePath the remote path
  564. * @param wifiOnly upload on wifi only
  565. * @param chargingOnly upload on charging only
  566. * @param subfolderByDate created sub folders
  567. * @param uploadAction upload action
  568. * @param enabled is sync enabled
  569. * @return the updated item
  570. */
  571. private SyncedFolderDisplayItem updateSyncedFolderItem(SyncedFolderDisplayItem item,
  572. String localPath,
  573. String remotePath,
  574. Boolean wifiOnly,
  575. Boolean chargingOnly,
  576. Boolean subfolderByDate,
  577. Integer uploadAction,
  578. Boolean enabled) {
  579. item.setLocalPath(localPath);
  580. item.setRemotePath(remotePath);
  581. item.setWifiOnly(wifiOnly);
  582. item.setChargingOnly(chargingOnly);
  583. item.setSubfolderByDate(subfolderByDate);
  584. item.setUploadAction(uploadAction);
  585. item.setEnabled(enabled);
  586. return item;
  587. }
  588. @Override
  589. public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
  590. @NonNull int[] grantResults) {
  591. switch (requestCode) {
  592. case PermissionUtil.PERMISSIONS_WRITE_EXTERNAL_STORAGE: {
  593. // If request is cancelled, result arrays are empty.
  594. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  595. // permission was granted
  596. int gridWidth = getResources().getInteger(R.integer.media_grid_width);
  597. load(gridWidth * 2, true);
  598. } else {
  599. // permission denied --> do nothing
  600. return;
  601. }
  602. return;
  603. }
  604. default:
  605. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  606. }
  607. }
  608. @Override
  609. protected void onResume() {
  610. super.onResume();
  611. setDrawerMenuItemChecked(R.id.nav_synced_folders);
  612. }
  613. private void showBatteryOptimizationInfo() {
  614. boolean isSpecialManufacturer = SPECIAL_MANUFACTURER.contains(Build.MANUFACTURER.toLowerCase(Locale.ROOT));
  615. if (isSpecialManufacturer && checkIfBatteryOptimizationEnabled() || checkIfBatteryOptimizationEnabled()) {
  616. AlertDialog alertDialog = new AlertDialog.Builder(this, R.style.Theme_ownCloud_Dialog)
  617. .setTitle(getString(R.string.battery_optimization_title))
  618. .setMessage(getString(R.string.battery_optimization_message))
  619. .setPositiveButton(getString(R.string.battery_optimization_disable), (dialog, which) -> {
  620. // show instant upload
  621. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  622. @SuppressLint("BatteryLife")
  623. Intent intent = new Intent(ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
  624. Uri.parse("package:" + BuildConfig.APPLICATION_ID));
  625. if (intent.resolveActivity(getPackageManager()) != null) {
  626. startActivity(intent);
  627. }
  628. } else {
  629. Intent powerUsageIntent = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);
  630. if (getPackageManager().resolveActivity(powerUsageIntent, 0) != null) {
  631. startActivity(powerUsageIntent);
  632. } else {
  633. dialog.dismiss();
  634. DisplayUtils.showSnackMessage(this, getString(R.string.battery_optimization_no_setting));
  635. }
  636. }
  637. })
  638. .setNegativeButton(getString(R.string.battery_optimization_close), (dialog, which) -> dialog.dismiss())
  639. .setIcon(R.drawable.ic_battery_alert)
  640. .show();
  641. int color = ThemeUtils.primaryAccentColor(this);
  642. alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(color);
  643. alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(color);
  644. }
  645. }
  646. /**
  647. * Check if battery optimization is enabled. If unknown, fallback to true.
  648. *
  649. * @return true if battery optimization is enabled
  650. */
  651. private boolean checkIfBatteryOptimizationEnabled() {
  652. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  653. PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
  654. if (powerManager == null) {
  655. return true;
  656. }
  657. return !powerManager.isIgnoringBatteryOptimizations(BuildConfig.APPLICATION_ID);
  658. } else {
  659. return true;
  660. }
  661. }
  662. }