DocumentsStorageProvider.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /**
  2. * nextCloud Android client application
  3. *
  4. * @author Bartosz Przybylski
  5. * Copyright (C) 2016 Bartosz Przybylski <bart.p.pl@gmail.com>
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License version 2,
  9. * as published by the Free Software Foundation.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. package com.owncloud.android.providers;
  21. import android.accounts.Account;
  22. import android.annotation.SuppressLint;
  23. import android.annotation.TargetApi;
  24. import android.content.ContentResolver;
  25. import android.content.Context;
  26. import android.content.Intent;
  27. import android.content.res.AssetFileDescriptor;
  28. import android.database.Cursor;
  29. import android.graphics.Point;
  30. import android.os.Build;
  31. import android.os.CancellationSignal;
  32. import android.os.ParcelFileDescriptor;
  33. import android.provider.DocumentsProvider;
  34. import android.util.Log;
  35. import com.owncloud.android.authentication.AccountUtils;
  36. import com.owncloud.android.datamodel.FileDataStorageManager;
  37. import com.owncloud.android.datamodel.OCFile;
  38. import com.owncloud.android.files.services.FileDownloader;
  39. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  40. import com.owncloud.android.operations.SynchronizeFileOperation;
  41. import com.owncloud.android.ui.activity.ConflictsResolveActivity;
  42. import com.owncloud.android.ui.notifications.NotificationUtils;
  43. import com.owncloud.android.utils.FileStorageUtils;
  44. import org.nextcloud.providers.cursors.FileCursor;
  45. import org.nextcloud.providers.cursors.RootCursor;
  46. import java.io.File;
  47. import java.io.FileNotFoundException;
  48. import java.util.HashMap;
  49. import java.util.Map;
  50. import java.util.Vector;
  51. @TargetApi(Build.VERSION_CODES.KITKAT)
  52. public class DocumentsStorageProvider extends DocumentsProvider {
  53. private static final String TAG = "DocumentsStorageProvider";
  54. private FileDataStorageManager mCurrentStorageManager = null;
  55. private static Map<Long, FileDataStorageManager> mRootIdToStorageManager;
  56. @Override
  57. public Cursor queryRoots(String[] projection) throws FileNotFoundException {
  58. initiateStorageMap();
  59. final RootCursor result = new RootCursor(projection);
  60. for (Account account : AccountUtils.getAccounts(getContext())) {
  61. result.addRoot(account, getContext());
  62. }
  63. return result;
  64. }
  65. @Override
  66. public Cursor queryDocument(String documentId, String[] projection) throws FileNotFoundException {
  67. final long docId = Long.parseLong(documentId);
  68. updateCurrentStorageManagerIfNeeded(docId);
  69. final FileCursor result = new FileCursor(projection);
  70. if (mCurrentStorageManager == null) {
  71. for(long key : mRootIdToStorageManager.keySet()) {
  72. if (mRootIdToStorageManager.get(key).getFileById(docId) != null) {
  73. mCurrentStorageManager = mRootIdToStorageManager.get(key);
  74. break;
  75. }
  76. }
  77. }
  78. OCFile file = mCurrentStorageManager.getFileById(docId);
  79. if (file != null) {
  80. result.addFile(file);
  81. }
  82. return result;
  83. }
  84. @Override
  85. public Cursor queryChildDocuments(String parentDocumentId, String[] projection, String sortOrder)
  86. throws FileNotFoundException {
  87. final long folderId = Long.parseLong(parentDocumentId);
  88. updateCurrentStorageManagerIfNeeded(folderId);
  89. final FileCursor result = new FileCursor(projection);
  90. final OCFile browsedDir = mCurrentStorageManager.getFileById(folderId);
  91. for (OCFile file : mCurrentStorageManager.getFolderContent(browsedDir, false)) {
  92. result.addFile(file);
  93. }
  94. return result;
  95. }
  96. @SuppressLint("LongLogTag")
  97. @Override
  98. public ParcelFileDescriptor openDocument(String documentId, String mode, CancellationSignal cancellationSignal)
  99. throws FileNotFoundException {
  100. final long docId = Long.parseLong(documentId);
  101. updateCurrentStorageManagerIfNeeded(docId);
  102. OCFile file = mCurrentStorageManager.getFileById(docId);
  103. Account account = mCurrentStorageManager.getAccount();
  104. Context context = getContext();
  105. if (!file.isDown()) {
  106. Intent i = new Intent(getContext(), FileDownloader.class);
  107. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  108. i.putExtra(FileDownloader.EXTRA_FILE, file);
  109. context.startService(i);
  110. do {
  111. if (!waitOrGetCancelled(cancellationSignal)) {
  112. return null;
  113. }
  114. file = mCurrentStorageManager.getFileById(docId);
  115. } while (!file.isDown());
  116. } else {
  117. OCFile finalFile = file;
  118. Thread syncThread = new Thread(() -> {
  119. try {
  120. FileDataStorageManager storageManager =
  121. new FileDataStorageManager(account, context.getContentResolver());
  122. SynchronizeFileOperation sfo =
  123. new SynchronizeFileOperation(finalFile, null, account, true, context);
  124. RemoteOperationResult result = sfo.execute(storageManager, context);
  125. if (result.getCode() == RemoteOperationResult.ResultCode.SYNC_CONFLICT) {
  126. // ISSUE 5: if the user is not running the app (this is a service!),
  127. // this can be very intrusive; a notification should be preferred
  128. Intent i = new Intent(context, ConflictsResolveActivity.class);
  129. i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
  130. i.putExtra(ConflictsResolveActivity.EXTRA_FILE, finalFile);
  131. i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, account);
  132. context.startActivity(i);
  133. } else {
  134. FileStorageUtils.checkIfFileFinishedSaving(finalFile);
  135. if (!result.isSuccess()) {
  136. NotificationUtils.showSyncFailedNotification();
  137. }
  138. }
  139. } catch (Exception exception) {
  140. NotificationUtils.showSyncFailedNotification();
  141. }
  142. });
  143. syncThread.start();
  144. try {
  145. syncThread.join();
  146. } catch (InterruptedException e) {
  147. Log.e(TAG, "Failed to wait for thread to finish");
  148. }
  149. }
  150. return ParcelFileDescriptor.open(new File(file.getStoragePath()), ParcelFileDescriptor.parseMode(mode));
  151. }
  152. @Override
  153. public boolean onCreate() {
  154. return true;
  155. }
  156. @Override
  157. public AssetFileDescriptor openDocumentThumbnail(String documentId,
  158. Point sizeHint,
  159. CancellationSignal signal)
  160. throws FileNotFoundException {
  161. long docId = Long.parseLong(documentId);
  162. updateCurrentStorageManagerIfNeeded(docId);
  163. OCFile file = mCurrentStorageManager.getFileById(docId);
  164. File realFile = new File(file.getStoragePath());
  165. return new AssetFileDescriptor(
  166. ParcelFileDescriptor.open(realFile, ParcelFileDescriptor.MODE_READ_ONLY),
  167. 0,
  168. AssetFileDescriptor.UNKNOWN_LENGTH);
  169. }
  170. @Override
  171. public Cursor querySearchDocuments(String rootId, String query, String[] projection) throws FileNotFoundException {
  172. updateCurrentStorageManagerIfNeeded(rootId);
  173. OCFile root = mCurrentStorageManager.getFileByPath("/");
  174. FileCursor result = new FileCursor(projection);
  175. for (OCFile f : findFiles(root, query)) {
  176. result.addFile(f);
  177. }
  178. return result;
  179. }
  180. @SuppressLint("LongLogTag")
  181. private void updateCurrentStorageManagerIfNeeded(long docId) {
  182. if (mRootIdToStorageManager == null) {
  183. try {
  184. queryRoots(FileCursor.DEFAULT_DOCUMENT_PROJECTION);
  185. } catch (FileNotFoundException e) {
  186. Log.e(TAG, "Failed to query roots");
  187. }
  188. }
  189. if (mCurrentStorageManager == null ||
  190. (mRootIdToStorageManager.containsKey(docId) &&
  191. mCurrentStorageManager != mRootIdToStorageManager.get(docId))) {
  192. mCurrentStorageManager = mRootIdToStorageManager.get(docId);
  193. }
  194. }
  195. private void updateCurrentStorageManagerIfNeeded(String rootId) {
  196. for (FileDataStorageManager data : mRootIdToStorageManager.values()) {
  197. if (data.getAccount().name.equals(rootId)) {
  198. mCurrentStorageManager = data;
  199. }
  200. }
  201. }
  202. private void initiateStorageMap() {
  203. mRootIdToStorageManager = new HashMap<>();
  204. ContentResolver contentResolver = getContext().getContentResolver();
  205. for (Account account : AccountUtils.getAccounts(getContext())) {
  206. final FileDataStorageManager storageManager =
  207. new FileDataStorageManager(account, contentResolver);
  208. final OCFile rootDir = storageManager.getFileByPath("/");
  209. mRootIdToStorageManager.put(rootDir.getFileId(), storageManager);
  210. }
  211. }
  212. private boolean waitOrGetCancelled(CancellationSignal cancellationSignal) {
  213. try {
  214. Thread.sleep(1000);
  215. } catch (InterruptedException e) {
  216. return false;
  217. }
  218. return !(cancellationSignal != null && cancellationSignal.isCanceled());
  219. }
  220. Vector<OCFile> findFiles(OCFile root, String query) {
  221. Vector<OCFile> result = new Vector<>();
  222. for (OCFile f : mCurrentStorageManager.getFolderContent(root, false)) {
  223. if (f.isFolder()) {
  224. result.addAll(findFiles(f, query));
  225. } else if (f.getFileName().contains(query)) {
  226. result.add(f);
  227. }
  228. }
  229. return result;
  230. }
  231. }