1
0
mirror of https://github.com/owncloud/android-library.git synced 2025-06-07 16:06:08 +00:00

refactor RemoteOperationResult

This commit is contained in:
DerSchabi 2018-05-24 12:46:55 +02:00 committed by davigonz
parent 63c917c979
commit dae28aee48
11 changed files with 244 additions and 209 deletions

@ -1 +1 @@
Subproject commit d0a09ad1ea87044d7e50cc870fc798562d1f0d38 Subproject commit 980eb7ece17314f6c88f87319be1541c579c4b94

View File

@ -24,7 +24,7 @@
--> -->
<resources> <resources>
<string name="server_base_url">http://docker.oc.solidgear.es:11917/</string> <string name="server_base_url">http://docker.oc.solidgear.es:11917</string>
<string name="username">admin</string> <string name="username">admin</string>
<string name="password">Password</string> <string name="password">Password</string>
<string name ="user_agent">Mozilla/5.0 (Android) ownCloud sample </string> <string name ="user_agent">Mozilla/5.0 (Android) ownCloud sample </string>

View File

@ -24,6 +24,31 @@
package com.owncloud.android.lib.sampleclient; package com.owncloud.android.lib.sampleclient;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
import com.owncloud.android.lib.common.OwnCloudClientFactory;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.refactor.OCContext;
import com.owncloud.android.lib.refactor.account.OCAccount;
import com.owncloud.android.lib.refactor.authentication.credentials.OwnCloudCredentialsFactory;
import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
import com.owncloud.android.lib.refactor.operations.PropfindOperation;
import com.owncloud.android.lib.resources.files.RemoteFile;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.resources.files.DownloadRemoteFileOperation;
import com.owncloud.android.lib.resources.files.ReadRemoteFolderOperation;
import com.owncloud.android.lib.resources.files.RemoveRemoteFileOperation;
import com.owncloud.android.lib.refactor.operations.UploadRemoteFileOperation;
import com.owncloud.android.lib.resources.files.FileUtils;
import android.app.Activity; import android.app.Activity;
import android.content.res.AssetManager; import android.content.res.AssetManager;
import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.BitmapDrawable;
@ -36,43 +61,16 @@ import android.widget.ListView;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import com.owncloud.android.lib.common.OwnCloudClient; import at.bitfire.dav4android.DavResource;
import com.owncloud.android.lib.common.OwnCloudClientFactory;
import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.refactor.OCContext;
import com.owncloud.android.lib.refactor.account.OCAccount;
import com.owncloud.android.lib.refactor.authentication.credentials.OwnCloudCredentialsFactory;
import com.owncloud.android.lib.refactor.operations.PropfindOperation;
import com.owncloud.android.lib.refactor.operations.UploadRemoteFileOperation;
import com.owncloud.android.lib.resources.files.DownloadRemoteFileOperation;
import com.owncloud.android.lib.resources.files.FileUtils;
import com.owncloud.android.lib.resources.files.ReadRemoteFolderOperation;
import com.owncloud.android.lib.resources.files.RemoteFile;
import com.owncloud.android.lib.resources.files.RemoveRemoteFileOperation;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MainActivity extends Activity implements OnRemoteOperationListener, OnDatatransferProgressListener { public class MainActivity extends Activity implements OnRemoteOperationListener, OnDatatransferProgressListener {
private static String LOG_TAG = MainActivity.class.getCanonicalName(); private static String LOG_TAG = MainActivity.class.getCanonicalName();
private Handler mHandler; private Handler mHandler;
private OwnCloudClient mClient; private OwnCloudClient mClient;
private OCContext mOCContext; private OCContext mOCContext;
private FilesArrayAdapter mFilesAdapter; private FilesArrayAdapter mFilesAdapter;
private View mFrame; private View mFrame;
/** Called when the activity is first created. */ /** Called when the activity is first created. */
@ -157,8 +155,20 @@ public class MainActivity extends Activity implements OnRemoteOperationListener,
private void startRefresh() { private void startRefresh() {
final PropfindOperation propfindOperation = new PropfindOperation(mOCContext, FileUtils.PATH_SEPARATOR); final PropfindOperation propfindOperation = new PropfindOperation(mOCContext, FileUtils.PATH_SEPARATOR);
new Thread(() -> propfindOperation.exec()).start(); final Handler handler = new Handler();
new Thread(() -> {
final PropfindOperation.Result result = propfindOperation.exec();
final List<RemoteFile> remoteFiles = new ArrayList<>();
if(!result.isSuccess()) {
handler.post(() ->
Toast.makeText(this, result.getLogMessage(), Toast.LENGTH_LONG).show());
return;
}
for(DavResource el : result.getData().getMembers()) {
remoteFiles.add(new RemoteFile(el));
}
handler.post(() -> mFilesAdapter.addAll(remoteFiles));
}).start();
// ReadRemoteFolderOperation refreshOperation = new ReadRemoteFolderOperation(FileUtils.PATH_SEPARATOR); // ReadRemoteFolderOperation refreshOperation = new ReadRemoteFolderOperation(FileUtils.PATH_SEPARATOR);
// refreshOperation.execute(mClient, this, mHandler); // refreshOperation.execute(mClient, this, mHandler);
} }

View File

@ -1,23 +1,55 @@
package com.owncloud.android.lib.refactor; package com.owncloud.android.lib.refactor;
import android.annotation.TargetApi;
import android.net.Uri; import android.net.Uri;
import android.os.Build;
import java.io.IOException;
import java.util.Map; import java.util.Map;
import at.bitfire.dav4android.UrlUtils; import at.bitfire.dav4android.UrlUtils;
import okhttp3.HttpUrl; import okhttp3.HttpUrl;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.Response;
public abstract class RemoteOperation { public abstract class RemoteOperation<I extends Object> {
private final OCContext mContext; private final OCContext mContext;
// TODO Move to a constants file // TODO Move to a constants file
private static final String USER_AGENT_HEADER = "User-Agent"; private static final String USER_AGENT_HEADER = "User-Agent";
public static final String WEBDAV_PATH_4_0 = "remote.php/dav/files"; public static final String WEBDAV_PATH_4_0 = "remote.php/dav/files";
private static OkHttpClient mClient = null; private static OkHttpClient mClient = null;
public class Result extends RemoteOperationResult {
public Result(ResultCode code) {
this(code, null);
}
public Result(ResultCode code, I data) {
super(code);
mData = data;
}
public Result(Exception e) {
super(e);
mData = null;
}
public Result(boolean success, Request request, Response response) throws IOException {
this(success, request, response, null);;
}
public Result(boolean success, Request request, Response response, I data) throws IOException {
super(success, request, response);
mData = data;
}
private final I mData;
public I getData() {
return mData;
}
}
protected RemoteOperation(OCContext context) { protected RemoteOperation(OCContext context) {
mContext = context; mContext = context;
if(mClient == null) { if(mClient == null) {
@ -27,7 +59,7 @@ public abstract class RemoteOperation {
} }
} }
public abstract RemoteOperationResult exec(); public abstract Result exec();
protected OCContext getOCContext() { protected OCContext getOCContext() {
return mContext; return mContext;

View File

@ -37,7 +37,6 @@ import org.apache.commons.httpclient.HttpStatus;
import org.json.JSONException; import org.json.JSONException;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.Serializable; import java.io.Serializable;
@ -51,8 +50,16 @@ import java.util.Map;
import javax.net.ssl.SSLException; import javax.net.ssl.SSLException;
import at.bitfire.dav4android.DavResource;
import at.bitfire.dav4android.exception.ConflictException;
import at.bitfire.dav4android.exception.DavException; import at.bitfire.dav4android.exception.DavException;
import at.bitfire.dav4android.exception.HttpException; import at.bitfire.dav4android.exception.HttpException;
import at.bitfire.dav4android.exception.InvalidDavResponseException;
import at.bitfire.dav4android.exception.NotFoundException;
import at.bitfire.dav4android.exception.PreconditionFailedException;
import at.bitfire.dav4android.exception.ServiceUnavailableException;
import at.bitfire.dav4android.exception.UnauthorizedException;
import at.bitfire.dav4android.exception.UnsupportedDavException;
import okhttp3.Headers; import okhttp3.Headers;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.Response; import okhttp3.Response;
@ -66,7 +73,7 @@ import okhttp3.Response;
* *
* @author David A. Velasco * @author David A. Velasco
*/ */
public class RemoteOperationResult implements Serializable { public abstract class RemoteOperationResult implements Serializable {
/** /**
* Generated - should be refreshed every time the class changes!! * Generated - should be refreshed every time the class changes!!
@ -75,6 +82,7 @@ public class RemoteOperationResult implements Serializable {
private static final String TAG = RemoteOperationResult.class.getSimpleName(); private static final String TAG = RemoteOperationResult.class.getSimpleName();
public enum ResultCode { public enum ResultCode {
OK, OK,
OK_SSL, OK_SSL,
@ -137,8 +145,6 @@ public class RemoteOperationResult implements Serializable {
private ArrayList<String> mAuthenticate = new ArrayList<>(); private ArrayList<String> mAuthenticate = new ArrayList<>();
private String mLastPermanentLocation = null; private String mLastPermanentLocation = null;
private ArrayList<Object> mData;
/** /**
* Public constructor from result code. * Public constructor from result code.
* *
@ -151,7 +157,6 @@ public class RemoteOperationResult implements Serializable {
mSuccess = (code == ResultCode.OK || code == ResultCode.OK_SSL || mSuccess = (code == ResultCode.OK || code == ResultCode.OK_SSL ||
code == ResultCode.OK_NO_SSL || code == ResultCode.OK_NO_SSL ||
code == ResultCode.OK_REDIRECT_TO_NON_SECURE_CONNECTION); code == ResultCode.OK_REDIRECT_TO_NON_SECURE_CONNECTION);
mData = null;
} }
/** /**
@ -164,53 +169,39 @@ public class RemoteOperationResult implements Serializable {
* @param e Exception that interrupted the {@link RemoteOperation} * @param e Exception that interrupted the {@link RemoteOperation}
*/ */
public RemoteOperationResult(Exception e) { public RemoteOperationResult(Exception e) {
mException = e; if (e instanceof SSLException || e instanceof RuntimeException) {
if (e instanceof OperationCancelledException) {
mCode = ResultCode.CANCELLED;
} else if (e instanceof SocketException) {
mCode = ResultCode.WRONG_CONNECTION;
} else if (e instanceof SocketTimeoutException) {
mCode = ResultCode.TIMEOUT;
} else if (e instanceof SocketTimeoutException) {
mCode = ResultCode.TIMEOUT;
} else if (e instanceof MalformedURLException) {
mCode = ResultCode.INCORRECT_ADDRESS;
} else if (e instanceof UnknownHostException) {
mCode = ResultCode.HOST_NOT_AVAILABLE;
} else if (e instanceof AccountNotFoundException) {
mCode = ResultCode.ACCOUNT_NOT_FOUND;
} else if (e instanceof AccountsException) {
mCode = ResultCode.ACCOUNT_EXCEPTION;
} else if (e instanceof SSLException || e instanceof RuntimeException) {
CertificateCombinedException se = getCertificateCombinedException(e); CertificateCombinedException se = getCertificateCombinedException(e);
if (se != null) { mException = se;
mException = se;
if (se.isRecoverable()) {
mCode = ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED;
}
} else if (e instanceof RuntimeException) {
mCode = ResultCode.HOST_NOT_AVAILABLE;
} else {
mCode = ResultCode.SSL_ERROR;
}
} else if (e instanceof FileNotFoundException) {
mCode = ResultCode.LOCAL_FILE_NOT_FOUND;
} else { } else {
mCode = ResultCode.UNKNOWN_ERROR; mException = e;
} }
mCode = getResultCodeByException(e);
}
private ResultCode getResultCodeByException(Exception e) {
return (e instanceof UnauthorizedException) ? ResultCode.UNAUTHORIZED
: (e instanceof NotFoundException) ? ResultCode.FILE_NOT_FOUND
: (e instanceof ConflictException) ? ResultCode.CONFLICT
: (e instanceof PreconditionFailedException) ? ResultCode.UNKNOWN_ERROR
: (e instanceof ServiceUnavailableException) ? ResultCode.SERVICE_UNAVAILABLE
: (e instanceof HttpException) ? ResultCode.UNHANDLED_HTTP_CODE
: (e instanceof InvalidDavResponseException) ? ResultCode.UNKNOWN_ERROR
: (e instanceof UnsupportedDavException) ? ResultCode.UNKNOWN_ERROR
: (e instanceof DavException) ? ResultCode.UNKNOWN_ERROR
: (e instanceof SSLException || e instanceof RuntimeException) ? handleSSLException(e)
: (e instanceof SocketException) ? ResultCode.WRONG_CONNECTION
: (e instanceof SocketTimeoutException) ? ResultCode.TIMEOUT
: (e instanceof MalformedURLException) ? ResultCode.INCORRECT_ADDRESS
: (e instanceof UnknownHostException) ? ResultCode.HOST_NOT_AVAILABLE
: ResultCode.UNKNOWN_ERROR;
}
private ResultCode handleSSLException(Exception e) {
final CertificateCombinedException se = getCertificateCombinedException(e);
return (se != null && se.isRecoverable()) ? ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED
: (e instanceof RuntimeException) ? ResultCode.HOST_NOT_AVAILABLE
: ResultCode.SSL_ERROR;
} }
/** /**
@ -366,14 +357,6 @@ public class RemoteOperationResult implements Serializable {
} }
} }
public void setData(ArrayList<Object> files) {
mData = files;
}
public ArrayList<Object> getData() {
return mData;
}
public boolean isSuccess() { public boolean isSuccess() {
return mSuccess; return mSuccess;
} }
@ -418,63 +401,57 @@ public class RemoteOperationResult implements Serializable {
previousCause = cause; previousCause = cause;
cause = cause.getCause(); cause = cause.getCause();
} }
if (cause != null && cause instanceof CertificateCombinedException) { return (cause != null && cause instanceof CertificateCombinedException)
result = (CertificateCombinedException) cause; ? (CertificateCombinedException) cause
} : result;
return result;
} }
public String getLogMessage() { public String getLogMessage() {
if (mException != null) { if (mException != null) {
if(mException instanceof OperationCancelledException) return (mException instanceof OperationCancelledException)
return "Operation cancelled by the caller"; ? "Operation cancelled by the caller"
if(mException instanceof SocketException) return "Socket exception"; : (mException instanceof SocketException) ? "Socket exception"
if(mException instanceof SocketTimeoutException) return "Socket timeout exception"; : (mException instanceof SocketTimeoutException) ? "Socket timeout exception"
if(mException instanceof MalformedURLException) return "Malformed URL exception"; : (mException instanceof MalformedURLException) ? "Malformed URL exception"
if(mException instanceof UnknownHostException) return "Unknown host exception"; : (mException instanceof UnknownHostException) ? "Unknown host exception"
if(mException instanceof CertificateCombinedException) { : (mException instanceof CertificateCombinedException) ?
if (((CertificateCombinedException) mException).isRecoverable()) (((CertificateCombinedException) mException).isRecoverable()
return "SSL recoverable exception"; ? "SSL recoverable exception"
else : "SSL exception")
return "SSL exception"; : (mException instanceof SSLException) ? "SSL exception"
: (mException instanceof DavException) ? "Unexpected WebDAV exception"
} : (mException instanceof HttpException) ? "HTTP violation"
if(mException instanceof SSLException) return "SSL exception"; : (mException instanceof IOException) ? "Unrecovered transport exception"
if(mException instanceof DavException) return "Unexpected WebDAV exception"; : (mException instanceof AccountNotFoundException)
if(mException instanceof HttpException) return "HTTP violation"; ? handleFailedAccountException((AccountNotFoundException)mException)
if(mException instanceof IOException) return "Unrecovered transport exception"; : (mException instanceof AccountsException) ? "Exception while using account"
if(mException instanceof AccountNotFoundException) { : (mException instanceof JSONException) ? "JSON exception"
Account failedAccount = : "Unexpected exception";
((AccountNotFoundException) mException).getFailedAccount();
return mException.getMessage() + " (" +
(failedAccount != null ? failedAccount.name : "NULL") + ")";
}
if (mException instanceof AccountsException) return "Exception while using account";
if (mException instanceof JSONException) return "JSON exception";
return "Unexpected exception";
} }
if(mCode == ResultCode.INSTANCE_NOT_CONFIGURED) switch (mCode) {
return "The ownCloud server is not configured!"; case INSTANCE_NOT_CONFIGURED: return "The ownCloud server is not configured!";
if(mCode == ResultCode.NO_NETWORK_CONNECTION) return "No network connection"; case NO_NETWORK_CONNECTION: return "No network connection";
if(mCode == ResultCode.BAD_OC_VERSION) case BAD_OC_VERSION: return "No valid ownCloud version was found at the server";
return "No valid ownCloud version was found at the server"; case LOCAL_STORAGE_FULL: return "Local storage full";
if(mCode == ResultCode.LOCAL_STORAGE_FULL) return "Local storage full"; case LOCAL_STORAGE_NOT_MOVED: return "Error while moving file to final directory";
if(mCode == ResultCode.LOCAL_STORAGE_NOT_MOVED) case ACCOUNT_NOT_NEW: return "Account already existing when creating a new one";
return "Error while moving file to final directory"; case INVALID_CHARACTER_IN_NAME: return "The file name contains an forbidden character";
if(mCode == ResultCode.ACCOUNT_NOT_NEW) case FILE_NOT_FOUND: return "Local file does not exist";
return "Account already existing when creating a new one"; case SYNC_CONFLICT: return "Synchronization conflict";
if(mCode == ResultCode.INVALID_CHARACTER_IN_NAME) default: return "Operation finished with HTTP status code "
return "The file name contains an forbidden character"; + mHttpCode
if(mCode == ResultCode.FILE_NOT_FOUND) return "Local file does not exist"; + " ("
if(mCode == ResultCode.SYNC_CONFLICT) return "Synchronization conflict"; + (isSuccess() ? "success" : "fail")
+ ")";
return "Operation finished with HTTP status code " + mHttpCode + " (" + }
(isSuccess() ? "success" : "fail") + ")"; }
private String handleFailedAccountException(AccountNotFoundException e) {
final Account failedAccount = e.getFailedAccount();
return e.getMessage() + " (" +
(failedAccount != null ? failedAccount.name : "NULL") + ")";
} }
public boolean isServerFail() { public boolean isServerFail() {
@ -499,11 +476,11 @@ public class RemoteOperationResult implements Serializable {
mRedirectedLocation.toLowerCase().contains("wayf"))); mRedirectedLocation.toLowerCase().contains("wayf")));
} }
/** /** TODO: make this set via constructor
* Checks if is a non https connection * Checks if is a non https connection
* *
* @return boolean true/false * @return boolean true/false
*/
public boolean isNonSecureRedirection() { public boolean isNonSecureRedirection() {
return (mRedirectedLocation != null && !(mRedirectedLocation.toLowerCase().startsWith("https://"))); return (mRedirectedLocation != null && !(mRedirectedLocation.toLowerCase().startsWith("https://")));
} }
@ -519,5 +496,5 @@ public class RemoteOperationResult implements Serializable {
public void setLastPermanentLocation(String lastPermanentLocation) { public void setLastPermanentLocation(String lastPermanentLocation) {
mLastPermanentLocation = lastPermanentLocation; mLastPermanentLocation = lastPermanentLocation;
} }
*/
} }

View File

@ -89,7 +89,6 @@ public class OwnCloudOAuth2RequestBuilder implements OAuth2RequestBuilder {
mGrantType.getValue(), mGrantType.getValue(),
mCode, mCode,
clientConfiguration.getClientId(), clientConfiguration.getClientId(),
clientConfiguration.getClientSecret(),
clientConfiguration.getRedirectUri(), clientConfiguration.getRedirectUri(),
mOAuth2Provider.getAccessTokenEndpointPath()); mOAuth2Provider.getAccessTokenEndpointPath());
@ -97,7 +96,6 @@ public class OwnCloudOAuth2RequestBuilder implements OAuth2RequestBuilder {
return new OAuth2RefreshAccessTokenOperation( return new OAuth2RefreshAccessTokenOperation(
ocContext, ocContext,
clientConfiguration.getClientId(), clientConfiguration.getClientId(),
clientConfiguration.getClientSecret(),
mRefreshToken, mRefreshToken,
mOAuth2Provider.getAccessTokenEndpointPath()); mOAuth2Provider.getAccessTokenEndpointPath());
default: default:

View File

@ -46,12 +46,11 @@ import okhttp3.RequestBody;
import okhttp3.Response; import okhttp3.Response;
public class OAuth2GetAccessTokenOperation extends RemoteOperation { public class OAuth2GetAccessTokenOperation extends RemoteOperation<Map<String, String>> {
private final String mGrantType; private final String mGrantType;
private final String mCode; private final String mCode;
private final String mClientId; private final String mClientId;
private final String mClientSecret;
private final String mRedirectUri; private final String mRedirectUri;
private final String mAccessTokenEndpointPath; private final String mAccessTokenEndpointPath;
private final OAuth2ResponseParser mResponseParser; private final OAuth2ResponseParser mResponseParser;
@ -61,12 +60,10 @@ public class OAuth2GetAccessTokenOperation extends RemoteOperation {
String grantType, String grantType,
String code, String code,
String clientId, String clientId,
String secretId,
String redirectUri, String redirectUri,
String accessTokenEndpointPath) { String accessTokenEndpointPath) {
super(context); super(context);
mClientId = clientId; mClientId = clientId;
mClientSecret = secretId;
mRedirectUri = redirectUri; mRedirectUri = redirectUri;
mGrantType = grantType; mGrantType = grantType;
mCode = code; mCode = code;
@ -80,7 +77,7 @@ public class OAuth2GetAccessTokenOperation extends RemoteOperation {
} }
@Override @Override
public RemoteOperationResult exec() { public Result exec() {
try { try {
final RequestBody requestBody = new MultipartBody.Builder() final RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM) .setType(MultipartBody.FORM)
@ -102,27 +99,20 @@ public class OAuth2GetAccessTokenOperation extends RemoteOperation {
final String responseData = response.body().string(); final String responseData = response.body().string();
if (responseData != null && responseData.length() > 0) { if (responseData != null && responseData.length() > 0) {
JSONObject tokenJson = new JSONObject(responseData); final JSONObject tokenJson = new JSONObject(responseData);
Map<String, String> accessTokenResult = final Map<String, String> accessTokenResult =
mResponseParser.parseAccessTokenResult(tokenJson); mResponseParser.parseAccessTokenResult(tokenJson);
if (accessTokenResult.get(OAuth2Constants.KEY_ERROR) != null ||
accessTokenResult.get(OAuth2Constants.KEY_ACCESS_TOKEN) == null) {
return new RemoteOperationResult(RemoteOperationResult.ResultCode.OAUTH2_ERROR);
} else {
final RemoteOperationResult result = new RemoteOperationResult(true, request, response);
ArrayList<Object> data = new ArrayList<>();
data.add(accessTokenResult);
result.setData(data);
return result;
}
return (accessTokenResult.get(OAuth2Constants.KEY_ERROR) != null ||
accessTokenResult.get(OAuth2Constants.KEY_ACCESS_TOKEN) == null)
? new Result(RemoteOperationResult.ResultCode.OAUTH2_ERROR)
: new Result(true, request, response, accessTokenResult);
} else { } else {
return new RemoteOperationResult(false, request, response); return new Result(false, request, response);
} }
} catch (Exception e) { } catch (Exception e) {
return new RemoteOperationResult(e); return new Result(e);
} }
} }
} }

View File

@ -40,42 +40,36 @@ import okhttp3.Request;
import okhttp3.RequestBody; import okhttp3.RequestBody;
import okhttp3.Response; import okhttp3.Response;
public class OAuth2RefreshAccessTokenOperation extends RemoteOperation { public class OAuth2RefreshAccessTokenOperation extends RemoteOperation<Map<String, String>> {
private static final String TAG = OAuth2RefreshAccessTokenOperation.class.getSimpleName(); private static final String TAG = OAuth2RefreshAccessTokenOperation.class.getSimpleName();
private String mClientId; private final String mClientId;
private String mClientSecret; private final String mRefreshToken;
private String mRefreshToken;
private final String mAccessTokenEndpointPath; private final String mAccessTokenEndpointPath;
private final OAuth2ResponseParser mResponseParser; private final OAuth2ResponseParser mResponseParser;
public OAuth2RefreshAccessTokenOperation( public OAuth2RefreshAccessTokenOperation(
OCContext ocContext, OCContext ocContext,
String clientId, String clientId,
String secretId,
String refreshToken, String refreshToken,
String accessTokenEndpointPath String accessTokenEndpointPath
) { ) {
super(ocContext); super(ocContext);
mClientId = clientId; mClientId = clientId;
mClientSecret = secretId;
mRefreshToken = refreshToken; mRefreshToken = refreshToken;
mAccessTokenEndpointPath = mAccessTokenEndpointPath =
accessTokenEndpointPath != null ? accessTokenEndpointPath != null ?
accessTokenEndpointPath : accessTokenEndpointPath :
OwnCloudOAuth2Provider.ACCESS_TOKEN_ENDPOINT_PATH OwnCloudOAuth2Provider.ACCESS_TOKEN_ENDPOINT_PATH;
;
mResponseParser = new OAuth2ResponseParser(); mResponseParser = new OAuth2ResponseParser();
} }
@Override @Override
public RemoteOperationResult exec() { public Result exec() {
try { try {
final RequestBody requestBody = new MultipartBody.Builder() final RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM) .setType(MultipartBody.FORM)
@ -96,27 +90,20 @@ public class OAuth2RefreshAccessTokenOperation extends RemoteOperation {
Log_OC.d(TAG, "OAUTH2: raw response from POST TOKEN: " + responseData); Log_OC.d(TAG, "OAUTH2: raw response from POST TOKEN: " + responseData);
if (responseData != null && responseData.length() > 0) { if (responseData != null && responseData.length() > 0) {
JSONObject tokenJson = new JSONObject(responseData); final JSONObject tokenJson = new JSONObject(responseData);
Map<String, String> accessTokenResult = final Map<String, String> accessTokenResult =
mResponseParser.parseAccessTokenResult(tokenJson); mResponseParser.parseAccessTokenResult(tokenJson);
if (accessTokenResult.get(OAuth2Constants.KEY_ERROR) != null || return (accessTokenResult.get(OAuth2Constants.KEY_ERROR) != null ||
accessTokenResult.get(OAuth2Constants.KEY_ACCESS_TOKEN) == null) { accessTokenResult.get(OAuth2Constants.KEY_ACCESS_TOKEN) == null)
return new RemoteOperationResult(RemoteOperationResult.ResultCode.OAUTH2_ERROR); ? new Result(RemoteOperationResult.ResultCode.OAUTH2_ERROR)
: new Result(true, request, response, accessTokenResult);
} else {
final RemoteOperationResult result = new RemoteOperationResult(true, request, response);
ArrayList<Object> data = new ArrayList<>();
data.add(accessTokenResult);
result.setData(data);
return result;
}
} else { } else {
return new RemoteOperationResult(false, request, response); return new Result(false, request, response);
} }
} catch (Exception e) { } catch (Exception e) {
return new RemoteOperationResult(e); return new Result(e);
} }
} }
} }

View File

@ -26,12 +26,14 @@ package com.owncloud.android.lib.refactor.operations;
import com.owncloud.android.lib.refactor.OCContext; import com.owncloud.android.lib.refactor.OCContext;
import com.owncloud.android.lib.refactor.RemoteOperation; import com.owncloud.android.lib.refactor.RemoteOperation;
import com.owncloud.android.lib.refactor.RemoteOperationResult;
import at.bitfire.dav4android.DavResource; import at.bitfire.dav4android.DavResource;
import at.bitfire.dav4android.PropertyUtils; import at.bitfire.dav4android.PropertyUtils;
import okhttp3.HttpUrl;
public class PropfindOperation extends RemoteOperation { import static com.owncloud.android.lib.refactor.RemoteOperationResult.ResultCode.OK;
public class PropfindOperation extends RemoteOperation<DavResource> {
private String mRemotePath; private String mRemotePath;
@ -41,16 +43,16 @@ public class PropfindOperation extends RemoteOperation {
} }
@Override @Override
public RemoteOperationResult exec() { public Result exec() {
try { try {
DavResource davResource = new DavResource(getClient(), getWebDavHttpUrl("/")); final HttpUrl location = HttpUrl.parse(getWebDavHttpUrl("/").toString());
DavResource davResource = new DavResource(getClient(), location);
davResource.propfind(1, PropertyUtils.INSTANCE.getAllPropSet()); davResource.propfind(1, PropertyUtils.INSTANCE.getAllPropSet());
return new Result(OK, davResource);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); return new Result(e);
} }
return null;
} }
} }

View File

@ -35,10 +35,12 @@ import okhttp3.MediaType;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.RequestBody; import okhttp3.RequestBody;
import static com.owncloud.android.lib.refactor.RemoteOperationResult.ResultCode.OK;
/** /**
* @author David González Verdugo * @author David González Verdugo
*/ */
public class UploadRemoteFileOperation extends RemoteOperation { public class UploadRemoteFileOperation extends RemoteOperation<Void> {
private static final String CONTENT_TYPE_HEADER = "Content-Type"; private static final String CONTENT_TYPE_HEADER = "Content-Type";
private static final String OC_TOTAL_LENGTH_HEADER = "OC-Total-Length"; private static final String OC_TOTAL_LENGTH_HEADER = "OC-Total-Length";
@ -62,7 +64,7 @@ public class UploadRemoteFileOperation extends RemoteOperation {
} }
@Override @Override
public RemoteOperationResult exec() { public Result exec() {
try { try {
@ -75,9 +77,7 @@ public class UploadRemoteFileOperation extends RemoteOperation {
.addInterceptor(chain -> .addInterceptor(chain ->
chain.proceed( chain.proceed(
addUploadHeaders(chain.request()) addUploadHeaders(chain.request())
.build() .build()))
)
)
.followRedirects(false) .followRedirects(false)
.build(), .build(),
getWebDavHttpUrl(mRemotePath)); getWebDavHttpUrl(mRemotePath));
@ -87,10 +87,10 @@ public class UploadRemoteFileOperation extends RemoteOperation {
false); false);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); return new Result(e);
} }
return null; return new Result(OK);
} }
/** /**

View File

@ -27,11 +27,25 @@ package com.owncloud.android.lib.resources.files;
import java.io.Serializable; import java.io.Serializable;
import java.math.BigDecimal; import java.math.BigDecimal;
import android.net.Uri;
import android.os.Parcel; import android.os.Parcel;
import android.os.Parcelable; import android.os.Parcelable;
import com.owncloud.android.lib.common.network.WebdavEntry; import com.owncloud.android.lib.common.network.WebdavEntry;
import at.bitfire.dav4android.DavResource;
import at.bitfire.dav4android.PropertyCollection;
import at.bitfire.dav4android.property.CreationDate;
import at.bitfire.dav4android.property.GetContentType;
import at.bitfire.dav4android.property.GetETag;
import at.bitfire.dav4android.property.GetLastModified;
import at.bitfire.dav4android.property.QuotaAvailableBytes;
import at.bitfire.dav4android.property.QuotaUsedBytes;
import at.bitfire.dav4android.property.owncloud.OCId;
import at.bitfire.dav4android.property.owncloud.OCPermissions;
import at.bitfire.dav4android.property.owncloud.OCPrivatelink;
import at.bitfire.dav4android.property.owncloud.OCSize;
/** /**
* Contains the data of a Remote File from a WebDavEntry * Contains the data of a Remote File from a WebDavEntry
* *
@ -184,6 +198,31 @@ public class RemoteFile implements Parcelable, Serializable {
this.setPrivateLink(webdavEntry.privateLink()); this.setPrivateLink(webdavEntry.privateLink());
} }
public RemoteFile(final DavResource davResource) {
this(Uri.decode(davResource.getLocation().encodedPath()));
final PropertyCollection properties = davResource.getProperties();
this.setCreationTimestamp(properties.get(CreationDate.class) != null
? Long.parseLong(properties.get(CreationDate.class).getCreationDate())
: 0);
this.setMimeType(properties.get(GetContentType.class) != null
? properties.get(GetContentType.class).getType()
: "");
this.setModifiedTimestamp(properties.get(GetLastModified.class).getLastModified());
this.setEtag(properties.get(GetETag.class).getETag());
this.setPermissions(properties.get(OCPermissions.class).getPermission());
this.setRemoteId(properties.get(OCId.class).getId());
this.setSize(properties.get(OCSize.class).getSize());
this.setQuotaUsedBytes(properties.get(QuotaUsedBytes.class) != null
? BigDecimal.valueOf(
properties.get(QuotaUsedBytes.class).getQuotaUsedBytes())
: BigDecimal.ZERO);
this.setQuotaAvailableBytes(properties.get(QuotaAvailableBytes.class) != null
? BigDecimal.valueOf(
properties.get(QuotaAvailableBytes.class).getQuotaAvailableBytes())
: BigDecimal.ZERO);
this.setPrivateLink(properties.get(OCPrivatelink.class).getLink());
}
/** /**
* Used internally. Reset all file properties * Used internally. Reset all file properties
*/ */