use of com.owncloud.android.lib.common.operations.RemoteOperationResult in project android by owncloud.
the class RefreshFolderOperation method refreshSharesForFolder.
/**
* Syncs the Share resources for the files contained in the folder refreshed (children, not deeper descendants).
*
* @param client Handler of a session with an OC server.
* @return The result of the remote operation retrieving the Share resources in the folder refreshed by
* the operation.
*/
private RemoteOperationResult refreshSharesForFolder(OwnCloudClient client) {
RemoteOperationResult result;
// remote request
GetRemoteSharesForFileOperation operation = new GetRemoteSharesForFileOperation(mLocalFolder.getRemotePath(), true, true);
result = operation.execute(client);
if (result.isSuccess()) {
// update local database
ArrayList<OCShare> shares = new ArrayList<>();
for (Object obj : result.getData()) {
shares.add((OCShare) obj);
}
getStorageManager().saveSharesInFolder(shares, mLocalFolder);
}
return result;
}
use of com.owncloud.android.lib.common.operations.RemoteOperationResult in project android by owncloud.
the class UsersAndGroupsSearchProvider method searchForUsersOrGroups.
private Cursor searchForUsersOrGroups(Uri uri) {
MatrixCursor response = null;
String userQuery = uri.getLastPathSegment().toLowerCase();
/// need to trust on the AccountUtils to get the current account since the query in the client side is not
/// directly started by our code, but from SearchView implementation
Account account = AccountUtils.getCurrentOwnCloudAccount(getContext());
/// request to the OC server about users and groups matching userQuery
GetRemoteShareesOperation searchRequest = new GetRemoteShareesOperation(userQuery, REQUESTED_PAGE, RESULTS_PER_PAGE);
RemoteOperationResult result = searchRequest.execute(account, getContext());
List<JSONObject> names = new ArrayList<JSONObject>();
if (result.isSuccess()) {
for (Object o : result.getData()) {
// Get JSonObjects from response
names.add((JSONObject) o);
}
} else {
showErrorMessage(result);
}
/// convert the responses from the OC server to the expected format
if (names.size() > 0) {
response = new MatrixCursor(COLUMNS);
Iterator<JSONObject> namesIt = names.iterator();
JSONObject item;
String displayName = null;
int icon = 0;
Uri dataUri = null;
int count = 0;
MainApp app = (MainApp) getContext().getApplicationContext();
Uri userBaseUri = new Uri.Builder().scheme(CONTENT).authority(sSuggestAuthority + DATA_USER_SUFFIX).build();
Uri groupBaseUri = new Uri.Builder().scheme(CONTENT).authority(sSuggestAuthority + DATA_GROUP_SUFFIX).build();
Uri remoteBaseUri = new Uri.Builder().scheme(CONTENT).authority(sSuggestAuthority + DATA_REMOTE_SUFFIX).build();
FileDataStorageManager manager = new FileDataStorageManager(account, getContext().getContentResolver());
boolean federatedShareAllowed = manager.getCapability(account.name).getFilesSharingFederationOutgoing().isTrue();
try {
while (namesIt.hasNext()) {
item = namesIt.next();
String userName = item.getString(GetRemoteShareesOperation.PROPERTY_LABEL);
JSONObject value = item.getJSONObject(GetRemoteShareesOperation.NODE_VALUE);
int type = value.getInt(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE);
String shareWith = value.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH);
if (ShareType.GROUP.getValue() == type) {
displayName = getContext().getString(R.string.share_group_clarification, userName);
icon = R.drawable.ic_group;
dataUri = Uri.withAppendedPath(groupBaseUri, shareWith);
} else if (ShareType.FEDERATED.getValue() == type && federatedShareAllowed) {
icon = R.drawable.ic_user;
if (userName.equals(shareWith)) {
displayName = getContext().getString(R.string.share_remote_clarification, userName);
} else {
String[] uriSplitted = shareWith.split("@");
displayName = getContext().getString(R.string.share_known_remote_clarification, userName, uriSplitted[uriSplitted.length - 1]);
}
dataUri = Uri.withAppendedPath(remoteBaseUri, shareWith);
} else if (ShareType.USER.getValue() == type) {
displayName = userName;
icon = R.drawable.ic_user;
dataUri = Uri.withAppendedPath(userBaseUri, shareWith);
}
if (displayName != null && dataUri != null) {
response.newRow().add(// BaseColumns._ID
count++).add(// SearchManager.SUGGEST_COLUMN_TEXT_1
displayName).add(// SearchManager.SUGGEST_COLUMN_ICON_1
icon).add(dataUri);
}
}
} catch (JSONException e) {
Log_OC.e(TAG, "Exception while parsing data of users/groups", e);
}
}
return response;
}
use of com.owncloud.android.lib.common.operations.RemoteOperationResult in project android by owncloud.
the class UpdateShareViaLinkOperation method run.
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
OCShare publicShare = getStorageManager().getFirstShareByPathAndType(mPath, ShareType.PUBLIC_LINK, "");
if (publicShare == null) {
// TODO try to get remote share before failing?
return new RemoteOperationResult(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND);
}
// Update remote share with password
UpdateRemoteShareOperation updateOp = new UpdateRemoteShareOperation(publicShare.getRemoteId());
updateOp.setPassword(mPassword);
updateOp.setExpirationDate(mExpirationDateInMillis);
updateOp.setPublicUpload(mPublicUpload);
RemoteOperationResult result = updateOp.execute(client);
if (result.isSuccess()) {
// Retrieve updated share / save directly with password? -> no; the password is not to be saved
RemoteOperation getShareOp = new GetRemoteShareOperation(publicShare.getRemoteId());
result = getShareOp.execute(client);
if (result.isSuccess()) {
OCShare share = (OCShare) result.getData().get(0);
updateData(share);
}
}
return result;
}
use of com.owncloud.android.lib.common.operations.RemoteOperationResult in project android by owncloud.
the class UploadFileOperation method copy.
/**
* TODO rewrite with homogeneous fail handling, remove dependency on {@link RemoteOperationResult},
* TODO use Exceptions instead
*
* @param sourceFile Source file to copy.
* @param targetFile Target location to copy the file.
* @return {@link RemoteOperationResult}
* @throws IOException
*/
private RemoteOperationResult copy(File sourceFile, File targetFile) throws IOException {
Log_OC.d(TAG, "Copying local file");
RemoteOperationResult result = null;
if (FileStorageUtils.getUsableSpace(mAccount.name) < sourceFile.length()) {
result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL);
// error condition when the file should be copied
return result;
} else {
Log_OC.d(TAG, "Creating temporal folder");
File temporalParent = targetFile.getParentFile();
temporalParent.mkdirs();
if (!temporalParent.isDirectory()) {
throw new IOException("Unexpected error: parent directory could not be created");
}
Log_OC.d(TAG, "Creating temporal file");
targetFile.createNewFile();
if (!targetFile.isFile()) {
throw new IOException("Unexpected error: target file could not be created");
}
Log_OC.d(TAG, "Copying file contents");
InputStream in = null;
OutputStream out = null;
try {
if (!mOriginalStoragePath.equals(targetFile.getAbsolutePath())) {
// In case document provider schema as 'content://'
if (mOriginalStoragePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
Uri uri = Uri.parse(mOriginalStoragePath);
in = mContext.getContentResolver().openInputStream(uri);
} else {
in = new FileInputStream(sourceFile);
}
out = new FileOutputStream(targetFile);
int nRead;
byte[] buf = new byte[4096];
while (!mCancellationRequested.get() && (nRead = in.read(buf)) > -1) {
out.write(buf, 0, nRead);
}
out.flush();
}
if (mCancellationRequested.get()) {
result = new RemoteOperationResult(new OperationCancelledException());
return result;
}
} catch (Exception e) {
result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
return result;
} finally {
try {
if (in != null)
in.close();
} catch (Exception e) {
Log_OC.d(TAG, "Weird exception while closing input stream for " + mOriginalStoragePath + " (ignoring)", e);
}
try {
if (out != null)
out.close();
} catch (Exception e) {
Log_OC.d(TAG, "Weird exception while closing output stream for " + targetFile.getAbsolutePath() + " (ignoring)", e);
}
}
}
return result;
}
use of com.owncloud.android.lib.common.operations.RemoteOperationResult in project android by owncloud.
the class UploadFileOperation method run.
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
mCancellationRequested.set(false);
mUploadStarted.set(true);
RemoteOperationResult result = null;
File temporalFile = null, originalFile = new File(mOriginalStoragePath), expectedFile = null;
try {
/// Check that connectivity conditions are met and delays the upload otherwise
if (delayForWifi()) {
Log_OC.d(TAG, "Upload delayed until WiFi is available: " + getRemotePath());
return new RemoteOperationResult(ResultCode.DELAYED_FOR_WIFI);
}
/// check if the file continues existing before schedule the operation
if (!originalFile.exists()) {
Log_OC.d(TAG, mOriginalStoragePath.toString() + " not exists anymore");
return new RemoteOperationResult(ResultCode.LOCAL_FILE_NOT_FOUND);
}
/// check the existence of the parent folder for the file to upload
String remoteParentPath = new File(getRemotePath()).getParent();
remoteParentPath = remoteParentPath.endsWith(OCFile.PATH_SEPARATOR) ? remoteParentPath : remoteParentPath + OCFile.PATH_SEPARATOR;
result = grantFolderExistence(remoteParentPath, client);
if (!result.isSuccess()) {
return result;
}
/// set parent local id in uploading file
OCFile parent = getStorageManager().getFileByPath(remoteParentPath);
mFile.setParentId(parent.getFileId());
/// automatic rename of file to upload in case of name collision in server
Log_OC.d(TAG, "Checking name collision in server");
if (!mForceOverwrite) {
String remotePath = getAvailableRemotePath(client, mRemotePath);
mWasRenamed = !remotePath.equals(mRemotePath);
if (mWasRenamed) {
createNewOCFile(remotePath);
Log_OC.d(TAG, "File renamed as " + remotePath);
}
mRemotePath = remotePath;
mRenameUploadListener.onRenameUpload();
}
if (mCancellationRequested.get()) {
throw new OperationCancelledException();
}
String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile);
expectedFile = new File(expectedPath);
/// copy the file locally before uploading
if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY && !mOriginalStoragePath.equals(expectedPath)) {
String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
mFile.setStoragePath(temporalPath);
temporalFile = new File(temporalPath);
result = copy(originalFile, temporalFile);
if (result != null) {
return result;
}
}
if (mCancellationRequested.get()) {
throw new OperationCancelledException();
}
// Get the last modification date of the file from the file system
Long timeStampLong = originalFile.lastModified() / 1000;
String timeStamp = timeStampLong.toString();
/// perform the upload
if (mChunked && (new File(mFile.getStoragePath())).length() > ChunkedUploadRemoteFileOperation.CHUNK_SIZE) {
mUploadOperation = new ChunkedUploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(), mFile.getMimetype(), mFile.getEtagInConflict(), timeStamp);
} else {
mUploadOperation = new UploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(), mFile.getMimetype(), mFile.getEtagInConflict(), timeStamp);
}
Iterator<OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
while (listener.hasNext()) {
mUploadOperation.addDatatransferProgressListener(listener.next());
}
if (mCancellationRequested.get()) {
throw new OperationCancelledException();
}
result = mUploadOperation.execute(client);
// location in the ownCloud local folder
if (result.isSuccess()) {
if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_FORGET) {
String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
if (mOriginalStoragePath.equals(temporalPath)) {
// delete local file is was pre-copied in temporary folder (see .ui.helpers.UriUploader)
temporalFile = new File(temporalPath);
temporalFile.delete();
}
mFile.setStoragePath("");
} else {
mFile.setStoragePath(expectedPath);
if (temporalFile != null) {
// FileUploader.LOCAL_BEHAVIOUR_COPY
move(temporalFile, expectedFile);
} else {
// FileUploader.LOCAL_BEHAVIOUR_MOVE
move(originalFile, expectedFile);
getStorageManager().deleteFileInMediaScan(originalFile.getAbsolutePath());
}
FileDataStorageManager.triggerMediaScan(expectedFile.getAbsolutePath());
}
} else if (result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) {
result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
}
} catch (Exception e) {
result = new RemoteOperationResult(e);
} finally {
mUploadStarted.set(false);
if (temporalFile != null && !originalFile.equals(temporalFile)) {
temporalFile.delete();
}
if (result == null) {
result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
}
if (result.isSuccess()) {
Log_OC.i(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
} else {
if (result.getException() != null) {
if (result.isCancelled()) {
Log_OC.w(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
} else {
Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage(), result.getException());
}
} else {
Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
}
}
}
if (result.isSuccess()) {
saveUploadedFile(client);
} else if (result.getCode() == ResultCode.SYNC_CONFLICT) {
getStorageManager().saveConflict(mFile, mFile.getEtagInConflict());
}
return result;
}
Aggregations