DocumentsStorageProvider.java 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. /*
  2. * Nextcloud Android client application
  3. *
  4. * @author Bartosz Przybylski
  5. * @author Chris Narkiewicz
  6. * Copyright (C) 2016 Bartosz Przybylski <bart.p.pl@gmail.com>
  7. * Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
  8. *
  9. * This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2,
  11. * as published by the Free Software Foundation.
  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 General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. package com.owncloud.android.providers;
  23. import android.accounts.Account;
  24. import android.accounts.AuthenticatorException;
  25. import android.accounts.OperationCanceledException;
  26. import android.annotation.SuppressLint;
  27. import android.annotation.TargetApi;
  28. import android.content.ContentResolver;
  29. import android.content.Context;
  30. import android.content.res.AssetFileDescriptor;
  31. import android.database.Cursor;
  32. import android.graphics.Point;
  33. import android.net.Uri;
  34. import android.os.AsyncTask;
  35. import android.os.Build;
  36. import android.os.Bundle;
  37. import android.os.CancellationSignal;
  38. import android.os.Handler;
  39. import android.os.ParcelFileDescriptor;
  40. import android.provider.DocumentsContract;
  41. import android.provider.DocumentsProvider;
  42. import android.util.Log;
  43. import android.util.SparseArray;
  44. import com.nextcloud.client.account.User;
  45. import com.nextcloud.client.account.UserAccountManager;
  46. import com.nextcloud.client.account.UserAccountManagerImpl;
  47. import com.nextcloud.client.files.downloader.DownloadTask;
  48. import com.nextcloud.client.preferences.AppPreferences;
  49. import com.nextcloud.client.preferences.AppPreferencesImpl;
  50. import com.owncloud.android.MainApp;
  51. import com.owncloud.android.R;
  52. import com.owncloud.android.datamodel.FileDataStorageManager;
  53. import com.owncloud.android.datamodel.OCFile;
  54. import com.owncloud.android.datamodel.ThumbnailsCacheManager;
  55. import com.owncloud.android.files.services.FileDownloader;
  56. import com.owncloud.android.files.services.FileUploader;
  57. import com.owncloud.android.files.services.FileUploader.NameCollisionPolicy;
  58. import com.owncloud.android.lib.common.OwnCloudAccount;
  59. import com.owncloud.android.lib.common.OwnCloudClient;
  60. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  61. import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
  62. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  63. import com.owncloud.android.lib.common.utils.Log_OC;
  64. import com.owncloud.android.lib.resources.files.UploadFileRemoteOperation;
  65. import com.owncloud.android.operations.CopyFileOperation;
  66. import com.owncloud.android.operations.CreateFolderOperation;
  67. import com.owncloud.android.operations.DownloadFileOperation;
  68. import com.owncloud.android.operations.MoveFileOperation;
  69. import com.owncloud.android.operations.RefreshFolderOperation;
  70. import com.owncloud.android.operations.RemoveFileOperation;
  71. import com.owncloud.android.operations.RenameFileOperation;
  72. import com.owncloud.android.operations.SynchronizeFileOperation;
  73. import com.owncloud.android.ui.activity.SettingsActivity;
  74. import com.owncloud.android.utils.FileStorageUtils;
  75. import com.owncloud.android.utils.MimeTypeUtil;
  76. import org.nextcloud.providers.cursors.FileCursor;
  77. import org.nextcloud.providers.cursors.RootCursor;
  78. import java.io.File;
  79. import java.io.FileNotFoundException;
  80. import java.io.IOException;
  81. import java.util.ArrayList;
  82. import java.util.List;
  83. import java.util.Objects;
  84. import java.util.concurrent.Executor;
  85. import java.util.concurrent.Executors;
  86. import java.util.concurrent.TimeUnit;
  87. import androidx.annotation.NonNull;
  88. import androidx.annotation.VisibleForTesting;
  89. import static com.owncloud.android.datamodel.OCFile.PATH_SEPARATOR;
  90. import static com.owncloud.android.datamodel.OCFile.ROOT_PATH;
  91. import static com.owncloud.android.files.services.FileUploader.LOCAL_BEHAVIOUR_MOVE;
  92. @TargetApi(Build.VERSION_CODES.KITKAT)
  93. public class DocumentsStorageProvider extends DocumentsProvider {
  94. private static final String TAG = DocumentsStorageProvider.class.getSimpleName();
  95. private static final long CACHE_EXPIRATION = TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES);
  96. UserAccountManager accountManager;
  97. @VisibleForTesting
  98. static final String DOCUMENTID_SEPARATOR = "/";
  99. private static final int DOCUMENTID_PARTS = 2;
  100. private final SparseArray<FileDataStorageManager> rootIdToStorageManager = new SparseArray<>();
  101. private final Executor executor = Executors.newCachedThreadPool();
  102. @Override
  103. public Cursor queryRoots(String[] projection) {
  104. // always recreate storage manager collection, as it will change after account creation/removal
  105. // and we need to serve document(tree)s with persist permissions
  106. initiateStorageMap();
  107. Context context = MainApp.getAppContext();
  108. AppPreferences preferences = AppPreferencesImpl.fromContext(context);
  109. if (SettingsActivity.LOCK_PASSCODE.equals(preferences.getLockPreference()) ||
  110. SettingsActivity.LOCK_DEVICE_CREDENTIALS.equals(preferences.getLockPreference())) {
  111. return new FileCursor();
  112. }
  113. final RootCursor result = new RootCursor(projection);
  114. for(int i = 0; i < rootIdToStorageManager.size(); i++) {
  115. result.addRoot(new Document(rootIdToStorageManager.valueAt(i), ROOT_PATH), getContext());
  116. }
  117. return result;
  118. }
  119. @Override
  120. public Cursor queryDocument(String documentId, String[] projection) throws FileNotFoundException {
  121. Log.d(TAG, "queryDocument(), id=" + documentId);
  122. Document document = toDocument(documentId);
  123. final FileCursor result = new FileCursor(projection);
  124. result.addFile(document);
  125. return result;
  126. }
  127. @SuppressLint("LongLogTag")
  128. @Override
  129. public Cursor queryChildDocuments(String parentDocumentId, String[] projection, String sortOrder)
  130. throws FileNotFoundException {
  131. Log.d(TAG, "queryChildDocuments(), id=" + parentDocumentId);
  132. Context context = getContext();
  133. if (context == null) {
  134. throw new FileNotFoundException("Context may not be null");
  135. }
  136. Document parentFolder = toDocument(parentDocumentId);
  137. FileDataStorageManager storageManager = parentFolder.getStorageManager();
  138. final FileCursor resultCursor = new FileCursor(projection);
  139. for (OCFile file : storageManager.getFolderContent(parentFolder.getFile(), false)) {
  140. resultCursor.addFile(new Document(storageManager, file));
  141. }
  142. boolean isLoading = false;
  143. if (parentFolder.isExpired()) {
  144. final ReloadFolderDocumentTask task = new ReloadFolderDocumentTask(parentFolder, result ->
  145. getContext().getContentResolver().notifyChange(toNotifyUri(parentFolder), null, false));
  146. task.executeOnExecutor(executor);
  147. resultCursor.setLoadingTask(task);
  148. isLoading = true;
  149. }
  150. final Bundle extra = new Bundle();
  151. extra.putBoolean(DocumentsContract.EXTRA_LOADING, isLoading);
  152. resultCursor.setExtras(extra);
  153. resultCursor.setNotificationUri(getContext().getContentResolver(), toNotifyUri(parentFolder));
  154. return resultCursor;
  155. }
  156. @SuppressLint("LongLogTag")
  157. @Override
  158. public ParcelFileDescriptor openDocument(String documentId, String mode, CancellationSignal cancellationSignal)
  159. throws FileNotFoundException {
  160. Log.d(TAG, "openDocument(), id=" + documentId);
  161. Document document = toDocument(documentId);
  162. Context context = getNonNullContext();
  163. OCFile ocFile = document.getFile();
  164. Account account = document.getAccount();
  165. final User user = accountManager.getUser(account.name).orElseThrow(RuntimeException::new); // should exist
  166. if (ocFile.isDown()) {
  167. RemoteOperationResult result;
  168. try {
  169. result = new SynchronizeFileOperation(ocFile, null, user, true, context)
  170. .execute(document.getClient(), document.getStorageManager());
  171. } catch (Exception e) {
  172. throw getFileNotFoundExceptionWithCause("Error synchronizing file: " + ocFile.getFileName(), e);
  173. }
  174. if (result.getCode() == RemoteOperationResult.ResultCode.SYNC_CONFLICT) {
  175. // TODO show a conflict notification with a pending intent that shows a ConflictResolveDialog
  176. Log_OC.w(TAG, "Conflict found: " + result);
  177. } else if (!result.isSuccess()) {
  178. Log_OC.e(TAG, result.toString());
  179. throw new FileNotFoundException("Error synchronizing file: " + ocFile.getFileName());
  180. }
  181. // TODO test if this needed here
  182. // block thread until file is saved
  183. FileStorageUtils.checkIfFileFinishedSaving(ocFile);
  184. } else {
  185. DownloadFileOperation downloadFileOperation = new DownloadFileOperation(account, ocFile, context);
  186. RemoteOperationResult result = downloadFileOperation.execute(document.getClient());
  187. if (!result.isSuccess()) {
  188. Log_OC.e(TAG, result.toString());
  189. throw new FileNotFoundException("Error downloading file: " + ocFile.getFileName());
  190. }
  191. saveDownloadedFile(document.getStorageManager(), downloadFileOperation, ocFile);
  192. }
  193. File file = new File(ocFile.getStoragePath());
  194. int accessMode = ParcelFileDescriptor.parseMode(mode);
  195. boolean isWrite = accessMode != ParcelFileDescriptor.MODE_READ_ONLY;
  196. if (isWrite) {
  197. // The calling thread is not guaranteed to have a Looper, so we can't block it with the OnCloseListener.
  198. // Thus, we are unable to do a synchronous upload and have to start an asynchronous one.
  199. Handler handler = new Handler(context.getMainLooper());
  200. try {
  201. return ParcelFileDescriptor.open(file, accessMode, handler, error -> {
  202. if (error == null) { // no error
  203. // As we can't upload the file synchronously, let's at least update its metadata here already.
  204. ocFile.setFileLength(file.length());
  205. ocFile.setModificationTimestamp(System.currentTimeMillis());
  206. document.getStorageManager().saveFile(ocFile);
  207. // TODO disable upload notifications as DocumentsProvider users already show them
  208. // upload file with FileUploader service (off main thread)
  209. FileUploader.uploadUpdateFile(
  210. context,
  211. account,
  212. ocFile,
  213. LOCAL_BEHAVIOUR_MOVE,
  214. NameCollisionPolicy.OVERWRITE
  215. );
  216. } else { // error, no upload needed
  217. Log_OC.e(TAG, "File was closed with an error: " + ocFile.getFileName(), error);
  218. }
  219. });
  220. } catch (IOException e) {
  221. throw new FileNotFoundException("Failed to open document for writing " + ocFile.getFileName());
  222. }
  223. } else {
  224. return ParcelFileDescriptor.open(file, accessMode);
  225. }
  226. }
  227. /**
  228. * Updates the OC File after a successful download.
  229. *
  230. * TODO unify with code from {@link FileDownloader} and {@link DownloadTask}.
  231. */
  232. private void saveDownloadedFile(FileDataStorageManager storageManager, DownloadFileOperation dfo, OCFile file) {
  233. long syncDate = System.currentTimeMillis();
  234. file.setLastSyncDateForProperties(syncDate);
  235. file.setLastSyncDateForData(syncDate);
  236. file.setUpdateThumbnailNeeded(true);
  237. file.setModificationTimestamp(dfo.getModificationTimestamp());
  238. file.setModificationTimestampAtLastSyncForData(dfo.getModificationTimestamp());
  239. file.setEtag(dfo.getEtag());
  240. file.setMimeType(dfo.getMimeType());
  241. String savePath = dfo.getSavePath();
  242. file.setStoragePath(savePath);
  243. file.setFileLength(new File(savePath).length());
  244. file.setRemoteId(dfo.getFile().getRemoteId());
  245. storageManager.saveFile(file);
  246. if (MimeTypeUtil.isMedia(dfo.getMimeType())) {
  247. FileDataStorageManager.triggerMediaScan(file.getStoragePath(), file);
  248. }
  249. storageManager.saveConflict(file, null);
  250. }
  251. @Override
  252. public boolean onCreate() {
  253. accountManager = UserAccountManagerImpl.fromContext(getContext());
  254. // initiate storage manager collection, because we need to serve document(tree)s
  255. // with persist permissions
  256. initiateStorageMap();
  257. return true;
  258. }
  259. @Override
  260. public AssetFileDescriptor openDocumentThumbnail(String documentId,
  261. Point sizeHint,
  262. CancellationSignal signal)
  263. throws FileNotFoundException {
  264. Log.d(TAG, "openDocumentThumbnail(), id=" + documentId);
  265. Context context = getContext();
  266. if (context == null) {
  267. throw new FileNotFoundException("Context may not be null!");
  268. }
  269. OCFile file = toDocument(documentId).getFile();
  270. boolean exists = ThumbnailsCacheManager.containsBitmap(ThumbnailsCacheManager.PREFIX_THUMBNAIL
  271. + file.getRemoteId());
  272. if (!exists) {
  273. ThumbnailsCacheManager.generateThumbnailFromOCFile(file);
  274. }
  275. return new AssetFileDescriptor(DiskLruImageCacheFileProvider.getParcelFileDescriptorForOCFile(file),
  276. 0,
  277. file.getFileLength());
  278. }
  279. @Override
  280. public String renameDocument(String documentId, String displayName) throws FileNotFoundException {
  281. Log.d(TAG, "renameDocument(), id=" + documentId);
  282. Context context = getContext();
  283. if (context == null) {
  284. throw new FileNotFoundException("Context may not be null!");
  285. }
  286. Document document = toDocument(documentId);
  287. RemoteOperationResult result = new RenameFileOperation(document.getRemotePath(), displayName)
  288. .execute(document.getClient(), document.getStorageManager());
  289. if (!result.isSuccess()) {
  290. Log_OC.e(TAG, result.toString());
  291. throw new FileNotFoundException("Failed to rename document with documentId " + documentId + ": " +
  292. result.getException());
  293. }
  294. context.getContentResolver().notifyChange(toNotifyUri(document.getParent()), null, false);
  295. return null;
  296. }
  297. @Override
  298. public String copyDocument(String sourceDocumentId, String targetParentDocumentId) throws FileNotFoundException {
  299. Log.d(TAG, "copyDocument(), id=" + sourceDocumentId);
  300. Context context = getContext();
  301. if (context == null) {
  302. throw new FileNotFoundException("Context may not be null!");
  303. }
  304. Document document = toDocument(sourceDocumentId);
  305. FileDataStorageManager storageManager = document.getStorageManager();
  306. Document targetFolder = toDocument(targetParentDocumentId);
  307. RemoteOperationResult result = new CopyFileOperation(document.getRemotePath(), targetFolder.getRemotePath())
  308. .execute(document.getClient(), storageManager);
  309. if (!result.isSuccess()) {
  310. Log_OC.e(TAG, result.toString());
  311. throw new FileNotFoundException("Failed to copy document with documentId " + sourceDocumentId
  312. + " to " + targetParentDocumentId);
  313. }
  314. Account account = document.getAccount();
  315. RemoteOperationResult updateParent = new RefreshFolderOperation(targetFolder.getFile(), System.currentTimeMillis(),
  316. false, false, true, storageManager,
  317. account, context)
  318. .execute(targetFolder.getClient());
  319. if (!updateParent.isSuccess()) {
  320. Log_OC.e(TAG, updateParent.toString());
  321. throw new FileNotFoundException("Failed to copy document with documentId " + sourceDocumentId
  322. + " to " + targetParentDocumentId);
  323. }
  324. String newPath = targetFolder.getRemotePath() + document.getFile().getFileName();
  325. if (document.getFile().isFolder()) {
  326. newPath = newPath + PATH_SEPARATOR;
  327. }
  328. Document newFile = new Document(storageManager, newPath);
  329. context.getContentResolver().notifyChange(toNotifyUri(targetFolder), null, false);
  330. return newFile.getDocumentId();
  331. }
  332. @Override
  333. public String moveDocument(String sourceDocumentId, String sourceParentDocumentId, String targetParentDocumentId)
  334. throws FileNotFoundException {
  335. Log.d(TAG, "moveDocument(), id=" + sourceDocumentId);
  336. Context context = getContext();
  337. if (context == null) {
  338. throw new FileNotFoundException("Context may not be null!");
  339. }
  340. Document document = toDocument(sourceDocumentId);
  341. Document targetFolder = toDocument(targetParentDocumentId);
  342. RemoteOperationResult result = new MoveFileOperation(document.getRemotePath(), targetFolder.getRemotePath())
  343. .execute(document.getClient(), document.getStorageManager());
  344. if (!result.isSuccess()) {
  345. Log_OC.e(TAG, result.toString());
  346. throw new FileNotFoundException("Failed to move document with documentId " + sourceDocumentId
  347. + " to " + targetParentDocumentId);
  348. }
  349. Document sourceFolder = toDocument(sourceParentDocumentId);
  350. getContext().getContentResolver().notifyChange(toNotifyUri(sourceFolder), null, false);
  351. getContext().getContentResolver().notifyChange(toNotifyUri(targetFolder), null, false);
  352. return sourceDocumentId;
  353. }
  354. @Override
  355. public Cursor querySearchDocuments(String rootId, String query, String[] projection) {
  356. Log.d(TAG, "querySearchDocuments(), rootId=" + rootId);
  357. FileCursor result = new FileCursor(projection);
  358. FileDataStorageManager storageManager = getStorageManager(rootId);
  359. if (storageManager == null) {
  360. return result;
  361. }
  362. for (Document d : findFiles(new Document(storageManager, ROOT_PATH), query)) {
  363. result.addFile(d);
  364. }
  365. return result;
  366. }
  367. @Override
  368. public String createDocument(String documentId, String mimeType, String displayName) throws FileNotFoundException {
  369. Log.d(TAG, "createDocument(), id=" + documentId);
  370. Document folderDocument = toDocument(documentId);
  371. if (DocumentsContract.Document.MIME_TYPE_DIR.equalsIgnoreCase(mimeType)) {
  372. return createFolder(folderDocument, displayName);
  373. } else {
  374. return createFile(folderDocument, displayName, mimeType);
  375. }
  376. }
  377. private String createFolder(Document targetFolder, String displayName) throws FileNotFoundException {
  378. Context context = getContext();
  379. if (context == null) {
  380. throw new FileNotFoundException("Context may not be null!");
  381. }
  382. String newDirPath = targetFolder.getRemotePath() + displayName + PATH_SEPARATOR;
  383. FileDataStorageManager storageManager = targetFolder.getStorageManager();
  384. RemoteOperationResult result = new CreateFolderOperation(newDirPath,
  385. accountManager.getUser(),
  386. getContext())
  387. .execute(targetFolder.getClient(), storageManager);
  388. if (!result.isSuccess()) {
  389. Log_OC.e(TAG, result.toString());
  390. throw new FileNotFoundException("Failed to create document with name " +
  391. displayName + " and documentId " + targetFolder.getDocumentId());
  392. }
  393. RemoteOperationResult updateParent = new RefreshFolderOperation(targetFolder.getFile(), System.currentTimeMillis(),
  394. false, false, true, storageManager,
  395. targetFolder.getAccount(), context)
  396. .execute(targetFolder.getClient());
  397. if (!updateParent.isSuccess()) {
  398. Log_OC.e(TAG, updateParent.toString());
  399. throw new FileNotFoundException("Failed to create document with documentId " + targetFolder.getDocumentId());
  400. }
  401. Document newFolder = new Document(storageManager, newDirPath);
  402. context.getContentResolver().notifyChange(toNotifyUri(targetFolder), null, false);
  403. return newFolder.getDocumentId();
  404. }
  405. private String createFile(Document targetFolder, String displayName, String mimeType) throws FileNotFoundException {
  406. Context context = getContext();
  407. if (context == null) {
  408. throw new FileNotFoundException("Context may not be null!");
  409. }
  410. Account account = targetFolder.getAccount();
  411. // create dummy file
  412. File tempDir = new File(FileStorageUtils.getTemporalPath(account.name));
  413. if (!tempDir.exists() && !tempDir.mkdirs()) {
  414. throw new FileNotFoundException("Temp folder could not be created: " + tempDir.getAbsolutePath());
  415. }
  416. File emptyFile = new File(tempDir, displayName);
  417. if (emptyFile.exists() && !emptyFile.delete()) {
  418. throw new FileNotFoundException("Previous file could not be deleted");
  419. }
  420. try {
  421. if (!emptyFile.createNewFile()) {
  422. throw new FileNotFoundException("File could not be created");
  423. }
  424. } catch (IOException e) {
  425. throw getFileNotFoundExceptionWithCause("File could not be created", e);
  426. }
  427. String newFilePath = targetFolder.getRemotePath() + displayName;
  428. // FIXME we need to update the mimeType somewhere else as well
  429. // perform the upload, no need for chunked operation as we have a empty file
  430. OwnCloudClient client = targetFolder.getClient();
  431. RemoteOperationResult result = new UploadFileRemoteOperation(emptyFile.getAbsolutePath(),
  432. newFilePath,
  433. mimeType,
  434. "",
  435. String.valueOf(System.currentTimeMillis() / 1000))
  436. .execute(client);
  437. if (!result.isSuccess()) {
  438. Log_OC.e(TAG, result.toString());
  439. throw new FileNotFoundException("Failed to upload document with path " + newFilePath);
  440. }
  441. RemoteOperationResult updateParent = new RefreshFolderOperation(targetFolder.getFile(),
  442. System.currentTimeMillis(),
  443. false,
  444. false,
  445. true,
  446. targetFolder.getStorageManager(),
  447. account,
  448. context)
  449. .execute(client);
  450. if (!updateParent.isSuccess()) {
  451. Log_OC.e(TAG, updateParent.toString());
  452. throw new FileNotFoundException("Failed to create document with documentId " + targetFolder.getDocumentId());
  453. }
  454. Document newFile = new Document(targetFolder.getStorageManager(), newFilePath);
  455. context.getContentResolver().notifyChange(toNotifyUri(targetFolder), null, false);
  456. return newFile.getDocumentId();
  457. }
  458. @Override
  459. public void removeDocument(String documentId, String parentDocumentId) throws FileNotFoundException {
  460. deleteDocument(documentId);
  461. }
  462. @Override
  463. public void deleteDocument(String documentId) throws FileNotFoundException {
  464. Log.d(TAG, "deleteDocument(), id=" + documentId);
  465. Context context = getContext();
  466. if (context == null) {
  467. throw new FileNotFoundException("Context may not be null!");
  468. }
  469. Document document = toDocument(documentId);
  470. // get parent here, because it is not available anymore after the document was deleted
  471. Document parentFolder = document.getParent();
  472. recursiveRevokePermission(document);
  473. OCFile file = document.getStorageManager().getFileByPath(document.getRemotePath());
  474. RemoteOperationResult result = new RemoveFileOperation(file,
  475. false,
  476. document.getAccount(),
  477. true,
  478. context)
  479. .execute(document.getClient(), document.getStorageManager());
  480. if (!result.isSuccess()) {
  481. throw new FileNotFoundException("Failed to delete document with documentId " + documentId);
  482. }
  483. context.getContentResolver().notifyChange(toNotifyUri(parentFolder), null, false);
  484. }
  485. @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  486. private void recursiveRevokePermission(Document document) {
  487. FileDataStorageManager storageManager = document.getStorageManager();
  488. OCFile file = document.getFile();
  489. if (file.isFolder()) {
  490. for (OCFile child : storageManager.getFolderContent(file, false)) {
  491. recursiveRevokePermission(new Document(storageManager, child));
  492. }
  493. }
  494. revokeDocumentPermission(document.getDocumentId());
  495. }
  496. @Override
  497. public boolean isChildDocument(String parentDocumentId, String documentId) {
  498. Log.d(TAG, "isChildDocument(), parent=" + parentDocumentId + ", id=" + documentId);
  499. try {
  500. // get file for parent document
  501. Document parentDocument = toDocument(parentDocumentId);
  502. OCFile parentFile = parentDocument.getFile();
  503. if (parentFile == null) {
  504. throw new FileNotFoundException("No parent file with ID " + parentDocumentId);
  505. }
  506. // get file for child candidate document
  507. Document currentDocument = toDocument(documentId);
  508. OCFile childFile = currentDocument.getFile();
  509. if (childFile == null) {
  510. throw new FileNotFoundException("No child file with ID " + documentId);
  511. }
  512. String parentPath = parentFile.getDecryptedRemotePath();
  513. String childPath = childFile.getDecryptedRemotePath();
  514. // The alternative is to go up the folder hierarchy from currentDocument with getParent()
  515. // until we arrive at parentDocument or the storage root.
  516. // However, especially for long paths this is expensive and can take substantial time.
  517. // The solution below uses paths and is faster by a factor of 2-10 depending on the nesting level of child.
  518. // So far, the same document with its unique ID can never be in two places at once.
  519. // If this assumption ever changes, this code would need to be adapted.
  520. return parentDocument.getAccount() == currentDocument.getAccount() && childPath.startsWith(parentPath);
  521. } catch (FileNotFoundException e) {
  522. Log.e(TAG, "failed to check for child document", e);
  523. }
  524. return false;
  525. }
  526. private FileNotFoundException getFileNotFoundExceptionWithCause(String msg, Exception cause) {
  527. FileNotFoundException e = new FileNotFoundException(msg);
  528. e.initCause(cause);
  529. return e;
  530. }
  531. private FileDataStorageManager getStorageManager(String rootId) {
  532. for(int i = 0; i < rootIdToStorageManager.size(); i++) {
  533. FileDataStorageManager storageManager = rootIdToStorageManager.valueAt(i);
  534. if (storageManager.getAccount().name.equals(rootId)) {
  535. return storageManager;
  536. }
  537. }
  538. return null;
  539. }
  540. private void initiateStorageMap() {
  541. rootIdToStorageManager.clear();
  542. ContentResolver contentResolver = getContext().getContentResolver();
  543. for (Account account : accountManager.getAccounts()) {
  544. final FileDataStorageManager storageManager = new FileDataStorageManager(account, contentResolver);
  545. rootIdToStorageManager.put(account.hashCode(), storageManager);
  546. }
  547. }
  548. private List<Document> findFiles(Document root, String query) {
  549. FileDataStorageManager storageManager = root.getStorageManager();
  550. List<Document> result = new ArrayList<>();
  551. for (OCFile f : storageManager.getFolderContent(root.getFile(), false)) {
  552. if (f.isFolder()) {
  553. result.addAll(findFiles(new Document(storageManager, f), query));
  554. } else if (f.getFileName().contains(query)) {
  555. result.add(new Document(storageManager, f));
  556. }
  557. }
  558. return result;
  559. }
  560. private Uri toNotifyUri(Document document) {
  561. return DocumentsContract.buildDocumentUri(
  562. getContext().getString(R.string.document_provider_authority),
  563. document.getDocumentId());
  564. }
  565. private Document toDocument(String documentId) throws FileNotFoundException {
  566. String[] separated = documentId.split(DOCUMENTID_SEPARATOR, DOCUMENTID_PARTS);
  567. if (separated.length != DOCUMENTID_PARTS) {
  568. throw new FileNotFoundException("Invalid documentID " + documentId + "!");
  569. }
  570. FileDataStorageManager storageManager = rootIdToStorageManager.get(Integer.parseInt(separated[0]));
  571. if (storageManager == null) {
  572. throw new FileNotFoundException("No storage manager associated for " + documentId + "!");
  573. }
  574. return new Document(storageManager, Long.parseLong(separated[1]));
  575. }
  576. /**
  577. * Returns a {@link Context} guaranteed to be non-null.
  578. *
  579. * @throws IllegalStateException if called before {@link #onCreate()}.
  580. */
  581. @NonNull
  582. private Context getNonNullContext() {
  583. Context context = getContext();
  584. if (context == null) {
  585. throw new IllegalStateException();
  586. }
  587. return context;
  588. }
  589. public interface OnTaskFinishedCallback {
  590. void onTaskFinished(RemoteOperationResult result);
  591. }
  592. static class ReloadFolderDocumentTask extends AsyncTask<Void, Void, RemoteOperationResult> {
  593. private final Document folder;
  594. private final OnTaskFinishedCallback callback;
  595. ReloadFolderDocumentTask(Document folder, OnTaskFinishedCallback callback) {
  596. this.folder = folder;
  597. this.callback = callback;
  598. }
  599. @Override
  600. public final RemoteOperationResult doInBackground(Void... params) {
  601. Log.d(TAG, "run ReloadFolderDocumentTask(), id=" + folder.getDocumentId());
  602. return new RefreshFolderOperation(folder.getFile(), System.currentTimeMillis(), false,
  603. false, true, folder.getStorageManager(), folder.getAccount(),
  604. MainApp.getAppContext())
  605. .execute(folder.getClient());
  606. }
  607. @Override
  608. public final void onPostExecute(RemoteOperationResult result) {
  609. if (callback != null) {
  610. callback.onTaskFinished(result);
  611. }
  612. }
  613. }
  614. public class Document {
  615. private final FileDataStorageManager storageManager;
  616. private final long fileId;
  617. Document(FileDataStorageManager storageManager, long fileId) {
  618. this.storageManager = storageManager;
  619. this.fileId = fileId;
  620. }
  621. Document(FileDataStorageManager storageManager, OCFile file) {
  622. this.storageManager = storageManager;
  623. this.fileId = file.getFileId();
  624. }
  625. Document(FileDataStorageManager storageManager, String filePath) {
  626. this.storageManager = storageManager;
  627. this.fileId = storageManager.getFileByPath(filePath).getFileId();
  628. }
  629. public String getDocumentId() {
  630. for(int i = 0; i < rootIdToStorageManager.size(); i++) {
  631. if (Objects.equals(storageManager, rootIdToStorageManager.valueAt(i))) {
  632. return rootIdToStorageManager.keyAt(i) + DOCUMENTID_SEPARATOR + fileId;
  633. }
  634. }
  635. return null;
  636. }
  637. FileDataStorageManager getStorageManager() {
  638. return storageManager;
  639. }
  640. public Account getAccount() {
  641. return getStorageManager().getAccount();
  642. }
  643. public OCFile getFile() {
  644. return getStorageManager().getFileById(fileId);
  645. }
  646. public String getRemotePath() {
  647. return getFile().getRemotePath();
  648. }
  649. OwnCloudClient getClient() {
  650. try {
  651. OwnCloudAccount ocAccount = new OwnCloudAccount(getAccount(), MainApp.getAppContext());
  652. return OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, getContext());
  653. } catch (OperationCanceledException | IOException | AuthenticatorException | AccountNotFoundException e) {
  654. Log_OC.e(TAG, "Failed to set client", e);
  655. }
  656. return null;
  657. }
  658. boolean isExpired() {
  659. return getFile().getLastSyncDateForData() + CACHE_EXPIRATION < System.currentTimeMillis();
  660. }
  661. Document getParent() {
  662. long parentId = getFile().getParentId();
  663. if (parentId <= 0) {
  664. return null;
  665. }
  666. return new Document(getStorageManager(), parentId);
  667. }
  668. }
  669. }