Search in sources :

Example 6 with RemoteFile

use of com.owncloud.android.lib.resources.files.model.RemoteFile in project android-library by nextcloud.

the class WebDavFileUtils method fillOCFile.

/**
 * Creates and populates a new {@link RemoteFile} object with the data read from the server.
 *
 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
 * @return New OCFile instance representing the remote resource described by we.
 */
private RemoteFile fillOCFile(WebdavEntry we) {
    RemoteFile file = new RemoteFile(we.decodedPath());
    file.setCreationTimestamp(we.getCreateTimestamp());
    file.setLength(we.getContentLength());
    file.setMimeType(we.getContentType());
    file.setModifiedTimestamp(we.getModifiedTimestamp());
    file.setCreationTimestamp(we.getCreateTimestamp());
    file.setUploadTimestamp(we.getUploadTimestamp());
    file.setEtag(we.getETag());
    file.setPermissions(we.getPermissions());
    file.setRemoteId(we.getRemoteId());
    file.setSize(we.getSize());
    file.setFavorite(we.isFavorite());
    file.setHasPreview(we.isHasPreview());
    file.setSharees(we.getSharees());
    return file;
}
Also used : RemoteFile(com.owncloud.android.lib.resources.files.model.RemoteFile)

Example 7 with RemoteFile

use of com.owncloud.android.lib.resources.files.model.RemoteFile in project android-library by nextcloud.

the class SearchRemoteOperation method run.

@Override
protected RemoteOperationResult<List<RemoteFile>> run(OwnCloudClient client) {
    RemoteOperationResult<List<RemoteFile>> result;
    NcSearchMethod searchMethod = null;
    OptionsMethod optionsMethod;
    String webDavUrl = client.getDavUri().toString();
    optionsMethod = new OptionsMethod(webDavUrl);
    try {
        int optionsStatus = client.executeMethod(optionsMethod);
        boolean isSearchSupported = optionsMethod.isAllowed("SEARCH");
        if (isSearchSupported) {
            searchMethod = new NcSearchMethod(webDavUrl, new SearchInfo("NC", Namespace.XMLNS_NAMESPACE, searchQuery), searchType, getClient().getUserIdPlain(), timestamp, limit, filterOutFiles, capability, startDate, endDate);
            int status = client.executeMethod(searchMethod);
            // check and process response
            boolean isSuccess = (status == HttpStatus.SC_MULTI_STATUS || status == HttpStatus.SC_OK);
            if (isSuccess) {
                // get data from remote folder
                MultiStatus dataInServer = searchMethod.getResponseBodyAsMultiStatus();
                WebDavFileUtils webDavFileUtils = new WebDavFileUtils();
                ArrayList<RemoteFile> mFolderAndFiles = webDavFileUtils.readData(dataInServer, client, false, true);
                // Result of the operation
                result = new RemoteOperationResult<>(true, status, searchMethod.getResponseHeaders());
                // Add data to the result
                if (result.isSuccess()) {
                    result.setResultData(mFolderAndFiles);
                }
            } else {
                // synchronization failed
                client.exhaustResponse(searchMethod.getResponseBodyAsStream());
                result = new RemoteOperationResult<>(false, status, searchMethod.getResponseHeaders());
            }
        } else {
            client.exhaustResponse(optionsMethod.getResponseBodyAsStream());
            result = new RemoteOperationResult<>(false, optionsStatus, optionsMethod.getResponseHeaders());
        }
    } catch (Exception e) {
        result = new RemoteOperationResult<>(e);
    } finally {
        if (searchMethod != null) {
            // let the connection available for other methods
            searchMethod.releaseConnection();
        }
        optionsMethod.releaseConnection();
    }
    return result;
}
Also used : SearchInfo(org.apache.jackrabbit.webdav.search.SearchInfo) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) MultiStatus(org.apache.jackrabbit.webdav.MultiStatus) WebDavFileUtils(com.owncloud.android.lib.common.utils.WebDavFileUtils) OptionsMethod(org.apache.jackrabbit.webdav.client.methods.OptionsMethod) ArrayList(java.util.ArrayList) List(java.util.List) RemoteFile(com.owncloud.android.lib.resources.files.model.RemoteFile)

Example 8 with RemoteFile

use of com.owncloud.android.lib.resources.files.model.RemoteFile in project android by nextcloud.

the class FileDataStorageManagerIT method testPhotoSearch.

/**
 * This test creates an image, does a photo search (now returned image is not yet in file hierarchy), then root
 * folder is refreshed and it is verified that the same image file is used in database
 */
@Test
public void testPhotoSearch() throws IOException {
    String remotePath = "/imageFile.png";
    VirtualFolderType virtualType = VirtualFolderType.GALLERY;
    assertEquals(0, sut.getFolderContent(sut.getFileByDecryptedRemotePath("/"), false).size());
    assertEquals(1, sut.getAllFiles().size());
    File imageFile = getFile("imageFile.png");
    assertTrue(new UploadFileRemoteOperation(imageFile.getAbsolutePath(), remotePath, "image/png", String.valueOf(System.currentTimeMillis() / 1000)).execute(client).isSuccess());
    assertNull(sut.getFileByDecryptedRemotePath(remotePath));
    // search
    SearchRemoteOperation searchRemoteOperation = new SearchRemoteOperation("image/%", PHOTO_SEARCH, false, capability);
    RemoteOperationResult<List<RemoteFile>> searchResult = searchRemoteOperation.execute(client);
    TestCase.assertTrue(searchResult.isSuccess());
    TestCase.assertEquals(1, searchResult.getResultData().size());
    OCFile ocFile = FileStorageUtils.fillOCFile(searchResult.getResultData().get(0));
    sut.saveFile(ocFile);
    List<ContentValues> contentValues = new ArrayList<>();
    ContentValues cv = new ContentValues();
    cv.put(ProviderMeta.ProviderTableMeta.VIRTUAL_TYPE, virtualType.toString());
    cv.put(ProviderMeta.ProviderTableMeta.VIRTUAL_OCFILE_ID, ocFile.getFileId());
    contentValues.add(cv);
    sut.saveVirtuals(contentValues);
    assertEquals(remotePath, ocFile.getRemotePath());
    assertEquals(0, sut.getFolderContent(sut.getFileByDecryptedRemotePath("/"), false).size());
    assertEquals(1, sut.getVirtualFolderContent(virtualType, false).size());
    assertEquals(2, sut.getAllFiles().size());
    // update root
    assertTrue(new RefreshFolderOperation(sut.getFileByDecryptedRemotePath("/"), System.currentTimeMillis() / 1000, false, false, sut, user, targetContext).execute(client).isSuccess());
    assertEquals(1, sut.getFolderContent(sut.getFileByDecryptedRemotePath("/"), false).size());
    assertEquals(1, sut.getVirtualFolderContent(virtualType, false).size());
    assertEquals(2, sut.getAllFiles().size());
    assertEquals(sut.getVirtualFolderContent(virtualType, false).get(0), sut.getFolderContent(sut.getFileByDecryptedRemotePath("/"), false).get(0));
}
Also used : ContentValues(android.content.ContentValues) SearchRemoteOperation(com.owncloud.android.lib.resources.files.SearchRemoteOperation) UploadFileRemoteOperation(com.owncloud.android.lib.resources.files.UploadFileRemoteOperation) RefreshFolderOperation(com.owncloud.android.operations.RefreshFolderOperation) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) RemoteFile(com.owncloud.android.lib.resources.files.model.RemoteFile) File(java.io.File) Test(org.junit.Test)

Example 9 with RemoteFile

use of com.owncloud.android.lib.resources.files.model.RemoteFile in project android by nextcloud.

the class CreateFolderOperation method encryptedCreate.

private RemoteOperationResult encryptedCreate(OCFile parent, OwnCloudClient client) {
    ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(context.getContentResolver());
    String privateKey = arbitraryDataProvider.getValue(user.getAccountName(), EncryptionUtils.PRIVATE_KEY);
    String publicKey = arbitraryDataProvider.getValue(user.getAccountName(), EncryptionUtils.PUBLIC_KEY);
    String token = null;
    Boolean metadataExists;
    DecryptedFolderMetadata metadata;
    String encryptedRemotePath = null;
    String filename = new File(remotePath).getName();
    try {
        // lock folder
        token = EncryptionUtils.lockFolder(parent, client);
        // get metadata
        Pair<Boolean, DecryptedFolderMetadata> metadataPair = EncryptionUtils.retrieveMetadata(parent, client, privateKey, publicKey);
        metadataExists = metadataPair.first;
        metadata = metadataPair.second;
        // check if filename already exists
        if (isFileExisting(metadata, filename)) {
            return new RemoteOperationResult(RemoteOperationResult.ResultCode.FOLDER_ALREADY_EXISTS);
        }
        // generate new random file name, check if it exists in metadata
        String encryptedFileName = createRandomFileName(metadata);
        encryptedRemotePath = parent.getRemotePath() + encryptedFileName;
        RemoteOperationResult result = new CreateFolderRemoteOperation(encryptedRemotePath, true, token).execute(client);
        if (result.isSuccess()) {
            // update metadata
            metadata.getFiles().put(encryptedFileName, createDecryptedFile(filename));
            EncryptedFolderMetadata encryptedFolderMetadata = EncryptionUtils.encryptFolderMetadata(metadata, privateKey);
            String serializedFolderMetadata = EncryptionUtils.serializeJSON(encryptedFolderMetadata);
            // upload metadata
            EncryptionUtils.uploadMetadata(parent, serializedFolderMetadata, token, client, metadataExists);
            // unlock folder
            if (token != null) {
                RemoteOperationResult unlockFolderResult = EncryptionUtils.unlockFolder(parent, client, token);
                if (unlockFolderResult.isSuccess()) {
                    token = null;
                } else {
                    // TODO do better
                    throw new RuntimeException("Could not unlock folder!");
                }
            }
            RemoteOperationResult remoteFolderOperationResult = new ReadFolderRemoteOperation(encryptedRemotePath).execute(client);
            createdRemoteFolder = (RemoteFile) remoteFolderOperationResult.getData().get(0);
            OCFile newDir = createRemoteFolderOcFile(parent, filename, createdRemoteFolder);
            getStorageManager().saveFile(newDir);
            RemoteOperationResult encryptionOperationResult = new ToggleEncryptionRemoteOperation(newDir.getLocalId(), newDir.getRemotePath(), true).execute(client);
            if (!encryptionOperationResult.isSuccess()) {
                throw new RuntimeException("Error creating encrypted subfolder!");
            }
        } else {
            // revert to sane state in case of any error
            Log_OC.e(TAG, remotePath + " hasn't been created");
        }
        return result;
    } catch (Exception e) {
        if (!EncryptionUtils.unlockFolder(parent, client, token).isSuccess()) {
            throw new RuntimeException("Could not clean up after failing folder creation!");
        }
        // remove folder
        if (encryptedRemotePath != null) {
            RemoteOperationResult removeResult = new RemoveRemoteEncryptedFileOperation(encryptedRemotePath, parent.getLocalId(), user.toPlatformAccount(), context, filename).execute(client);
            if (!removeResult.isSuccess()) {
                throw new RuntimeException("Could not clean up after failing folder creation!");
            }
        }
        // TODO do better
        return new RemoteOperationResult(e);
    } finally {
        // unlock folder
        if (token != null) {
            RemoteOperationResult unlockFolderResult = EncryptionUtils.unlockFolder(parent, client, token);
            if (!unlockFolderResult.isSuccess()) {
                // TODO do better
                throw new RuntimeException("Could not unlock folder!");
            }
        }
    }
}
Also used : CreateFolderRemoteOperation(com.owncloud.android.lib.resources.files.CreateFolderRemoteOperation) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) ArbitraryDataProvider(com.owncloud.android.datamodel.ArbitraryDataProvider) ReadFolderRemoteOperation(com.owncloud.android.lib.resources.files.ReadFolderRemoteOperation) OCFile(com.owncloud.android.datamodel.OCFile) EncryptedFolderMetadata(com.owncloud.android.datamodel.EncryptedFolderMetadata) DecryptedFolderMetadata(com.owncloud.android.datamodel.DecryptedFolderMetadata) RemoteFile(com.owncloud.android.lib.resources.files.model.RemoteFile) OCFile(com.owncloud.android.datamodel.OCFile) File(java.io.File) ToggleEncryptionRemoteOperation(com.owncloud.android.lib.resources.e2ee.ToggleEncryptionRemoteOperation)

Example 10 with RemoteFile

use of com.owncloud.android.lib.resources.files.model.RemoteFile in project android by nextcloud.

the class SynchronizeFileOperation method run.

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    mTransferWasRequested = false;
    if (mLocalFile == null) {
        // Get local file from the DB
        mLocalFile = getStorageManager().getFileByPath(mRemotePath);
    }
    if (!mLocalFile.isDown()) {
        // / easy decision
        requestForDownload(mLocalFile);
        result = new RemoteOperationResult(ResultCode.OK);
    } else {
        // / local copy in the device -> need to think a bit more before do anything
        if (mServerFile == null) {
            ReadFileRemoteOperation operation = new ReadFileRemoteOperation(mRemotePath);
            result = operation.execute(client);
            if (result.isSuccess()) {
                mServerFile = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
                mServerFile.setLastSyncDateForProperties(System.currentTimeMillis());
            } else if (result.getCode() != ResultCode.FILE_NOT_FOUND) {
                return result;
            }
        }
        if (mServerFile != null) {
            // / check changes in server and local file
            boolean serverChanged;
            if (TextUtils.isEmpty(mLocalFile.getEtag())) {
                // file uploaded (null) or downloaded ("") before upgrade to version 1.8.0; check the old condition
                serverChanged = mServerFile.getModificationTimestamp() != mLocalFile.getModificationTimestampAtLastSyncForData();
            } else {
                serverChanged = !mServerFile.getEtag().equals(mLocalFile.getEtag());
            }
            boolean localChanged = mLocalFile.getLocalModificationTimestamp() > mLocalFile.getLastSyncDateForData();
            // if (!mLocalFile.getEtag().isEmpty() && localChanged && serverChanged) {
            if (localChanged && serverChanged) {
                result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
                getStorageManager().saveConflict(mLocalFile, mServerFile.getEtag());
            } else if (localChanged) {
                if (mSyncFileContents && mAllowUploads) {
                    requestForUpload(mLocalFile);
                // the local update of file properties will be done by the FileUploader
                // service when the upload finishes
                } else {
                    // NOTHING TO DO HERE: updating the properties of the file in the server
                    // without uploading the contents would be stupid;
                    // So, an instance of SynchronizeFileOperation created with
                    // syncFileContents == false is completely useless when we suspect
                    // that an upload is necessary (for instance, in FileObserverService).
                    Log_OC.d(TAG, "Nothing to do here");
                }
                result = new RemoteOperationResult(ResultCode.OK);
            } else if (serverChanged) {
                mLocalFile.setRemoteId(mServerFile.getRemoteId());
                if (mSyncFileContents) {
                    // local, not server; we won't to keep
                    requestForDownload(mLocalFile);
                // the value of favorite!
                // the update of local data will be done later by the FileUploader
                // service when the upload finishes
                } else {
                    // TODO CHECK: is this really useful in some point in the code?
                    mServerFile.setFavorite(mLocalFile.isFavorite());
                    mServerFile.setLastSyncDateForData(mLocalFile.getLastSyncDateForData());
                    mServerFile.setStoragePath(mLocalFile.getStoragePath());
                    mServerFile.setParentId(mLocalFile.getParentId());
                    mServerFile.setEtag(mLocalFile.getEtag());
                    getStorageManager().saveFile(mServerFile);
                }
                result = new RemoteOperationResult(ResultCode.OK);
            } else {
                // nothing changed, nothing to do
                result = new RemoteOperationResult(ResultCode.OK);
            }
            // safe blanket: sync'ing a not in-conflict file will clean wrong conflict markers in ancestors
            if (result.getCode() != ResultCode.SYNC_CONFLICT) {
                getStorageManager().saveConflict(mLocalFile, null);
            }
        } else {
            // remote file does not exist, deleting local copy
            boolean deleteResult = getStorageManager().removeFile(mLocalFile, true, true);
            if (deleteResult) {
                result = new RemoteOperationResult(ResultCode.FILE_NOT_FOUND);
            } else {
                Log_OC.e(TAG, "Removal of local copy failed (remote file does not exist any longer).");
            }
        }
    }
    Log_OC.i(TAG, "Synchronizing " + mUser.getAccountName() + ", file " + mLocalFile.getRemotePath() + ": " + result.getLogMessage());
    return result;
}
Also used : RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) ReadFileRemoteOperation(com.owncloud.android.lib.resources.files.ReadFileRemoteOperation) RemoteFile(com.owncloud.android.lib.resources.files.model.RemoteFile)

Aggregations

RemoteFile (com.owncloud.android.lib.resources.files.model.RemoteFile)29 RemoteOperationResult (com.owncloud.android.lib.common.operations.RemoteOperationResult)15 Test (org.junit.Test)12 ArrayList (java.util.ArrayList)10 ReadFolderRemoteOperation (com.owncloud.android.lib.resources.files.ReadFolderRemoteOperation)9 CreateFolderRemoteOperation (com.owncloud.android.lib.resources.files.CreateFolderRemoteOperation)8 OCFile (com.owncloud.android.datamodel.OCFile)6 List (java.util.List)6 CreateShareRemoteOperation (com.owncloud.android.lib.resources.shares.CreateShareRemoteOperation)5 ReadFileRemoteOperation (com.owncloud.android.lib.resources.files.ReadFileRemoteOperation)4 ShareeUser (com.owncloud.android.lib.resources.shares.ShareeUser)4 RefreshFolderOperation (com.owncloud.android.operations.RefreshFolderOperation)4 File (java.io.File)4 ContentValues (android.content.ContentValues)3 DecryptedFolderMetadata (com.owncloud.android.datamodel.DecryptedFolderMetadata)3 WebdavEntry (com.owncloud.android.lib.common.network.WebdavEntry)3 ToggleEncryptionRemoteOperation (com.owncloud.android.lib.resources.e2ee.ToggleEncryptionRemoteOperation)3 SearchRemoteOperation (com.owncloud.android.lib.resources.files.SearchRemoteOperation)3 RemoteOperation (com.owncloud.android.lib.common.operations.RemoteOperation)2 RemoveFileRemoteOperation (com.owncloud.android.lib.resources.files.RemoveFileRemoteOperation)2