mirror of
https://github.com/owncloud/android-library.git
synced 2025-06-07 16:06:08 +00:00
Merge pull request #364 from owncloud/fix/okhttp_singleton
remove okhttp singleton
This commit is contained in:
commit
4de236b3c7
@ -1,3 +1,27 @@
|
||||
/* ownCloud Android Library is available under MIT license
|
||||
* Copyright (C) 2016 ownCloud GmbH.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
package com.owncloud.android.lib.common
|
||||
|
||||
import android.accounts.AccountManager
|
||||
@ -15,14 +39,19 @@ import timber.log.Timber
|
||||
import java.io.IOException
|
||||
import java.lang.Exception
|
||||
|
||||
/**
|
||||
* ConnectionValidator
|
||||
*
|
||||
* @author Christian Schabesberger
|
||||
*/
|
||||
class ConnectionValidator(
|
||||
val context: Context,
|
||||
val clearCookiesOnValidation: Boolean
|
||||
) {
|
||||
fun validate(baseClient: OwnCloudClient, singleSessionManager: SingleSessionManager): Boolean {
|
||||
fun validate(baseClient: OwnCloudClient, singleSessionManager: SingleSessionManager, context: Context): Boolean {
|
||||
try {
|
||||
var validationRetryCount = 0
|
||||
val client = OwnCloudClient(baseClient.baseUri, null, false, singleSessionManager)
|
||||
val client = OwnCloudClient(baseClient.baseUri, null, false, singleSessionManager, context)
|
||||
if (clearCookiesOnValidation) {
|
||||
client.clearCookies()
|
||||
} else {
|
||||
|
@ -25,6 +25,7 @@
|
||||
|
||||
package com.owncloud.android.lib.common;
|
||||
|
||||
import android.content.Context;
|
||||
import android.net.Uri;
|
||||
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils;
|
||||
@ -76,7 +77,10 @@ public class OwnCloudClient extends HttpClient {
|
||||
public OwnCloudClient(Uri baseUri,
|
||||
ConnectionValidator connectionValidator,
|
||||
boolean synchronizeRequests,
|
||||
SingleSessionManager singleSessionManager) {
|
||||
SingleSessionManager singleSessionManager,
|
||||
Context context) {
|
||||
super(context);
|
||||
|
||||
if (baseUri == null) {
|
||||
throw new IllegalArgumentException("Parameter 'baseUri' cannot be NULL");
|
||||
}
|
||||
@ -99,7 +103,7 @@ public class OwnCloudClient extends HttpClient {
|
||||
}
|
||||
|
||||
public int executeHttpMethod(HttpBaseMethod method) throws Exception {
|
||||
if(mSynchronizeRequests) {
|
||||
if (mSynchronizeRequests) {
|
||||
synchronized (mRequestMutex) {
|
||||
return saveExecuteHttpMethod(method);
|
||||
}
|
||||
@ -112,7 +116,7 @@ public class OwnCloudClient extends HttpClient {
|
||||
int repeatCounter = 0;
|
||||
int status;
|
||||
|
||||
if(mFollowRedirects) {
|
||||
if (mFollowRedirects) {
|
||||
method.setFollowRedirects(true);
|
||||
}
|
||||
|
||||
@ -131,11 +135,11 @@ public class OwnCloudClient extends HttpClient {
|
||||
method.setRequestHeader(AUTHORIZATION_HEADER, mCredentials.getHeaderAuth());
|
||||
}
|
||||
|
||||
status = method.execute();
|
||||
status = method.execute(this);
|
||||
|
||||
if (shouldConnectionValidatorBeCalled(method, status)) {
|
||||
retry = mConnectionValidator.validate(this, mSingleSessionManager); // retry on success fail on no success
|
||||
} else if(method.getFollowPermanentRedirects() && status == HTTP_MOVED_PERMANENTLY) {
|
||||
retry = mConnectionValidator.validate(this, mSingleSessionManager, getContext()); // retry on success fail on no success
|
||||
} else if (method.getFollowPermanentRedirects() && status == HTTP_MOVED_PERMANENTLY) {
|
||||
retry = true;
|
||||
method.setFollowRedirects(true);
|
||||
}
|
||||
@ -146,12 +150,15 @@ public class OwnCloudClient extends HttpClient {
|
||||
}
|
||||
|
||||
private boolean shouldConnectionValidatorBeCalled(HttpBaseMethod method, int status) {
|
||||
return !mFollowRedirects &&
|
||||
!method.getFollowRedirects() &&
|
||||
mConnectionValidator != null &&
|
||||
(status == HttpConstants.HTTP_MOVED_TEMPORARILY ||
|
||||
(!(mCredentials instanceof OwnCloudAnonymousCredentials) &&
|
||||
status == HttpConstants.HTTP_UNAUTHORIZED));
|
||||
|
||||
return mConnectionValidator != null && (
|
||||
(!(mCredentials instanceof OwnCloudAnonymousCredentials) &&
|
||||
status == HttpConstants.HTTP_UNAUTHORIZED
|
||||
) || (!mFollowRedirects &&
|
||||
!method.getFollowRedirects() &&
|
||||
status == HttpConstants.HTTP_MOVED_TEMPORARILY
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -77,10 +77,11 @@ public class SingleSessionManager {
|
||||
sUserAgent = userAgent;
|
||||
}
|
||||
|
||||
private static OwnCloudClient createOwnCloudClient(Uri uri, Context context, ConnectionValidator connectionValidator, SingleSessionManager singleSessionManager) {
|
||||
OwnCloudClient client = new OwnCloudClient(uri, connectionValidator, true, singleSessionManager);
|
||||
HttpClient.setContext(context);
|
||||
|
||||
private static OwnCloudClient createOwnCloudClient(Uri uri,
|
||||
Context context,
|
||||
ConnectionValidator connectionValidator,
|
||||
SingleSessionManager singleSessionManager) {
|
||||
OwnCloudClient client = new OwnCloudClient(uri, connectionValidator, true, singleSessionManager, context);
|
||||
return client;
|
||||
}
|
||||
|
||||
@ -130,9 +131,9 @@ public class SingleSessionManager {
|
||||
// no client to reuse - create a new one
|
||||
client = createOwnCloudClient(
|
||||
account.getBaseUri(),
|
||||
context.getApplicationContext(),
|
||||
context,
|
||||
connectionValidator,
|
||||
this);
|
||||
this); // TODO remove dependency on OwnCloudClientFactory
|
||||
|
||||
//the next two lines are a hack because okHttpclient is used as a singleton instead of being an
|
||||
//injected instance that can be deleted when required
|
||||
@ -140,7 +141,6 @@ public class SingleSessionManager {
|
||||
client.clearCredentials();
|
||||
|
||||
client.setAccount(account);
|
||||
HttpClient.setContext(context);
|
||||
|
||||
account.loadCredentials(context);
|
||||
client.setCredentials(account.getCredentials());
|
||||
|
@ -31,7 +31,6 @@ import com.owncloud.android.lib.common.network.NetworkUtils;
|
||||
import okhttp3.Cookie;
|
||||
import okhttp3.CookieJar;
|
||||
import okhttp3.HttpUrl;
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Protocol;
|
||||
import okhttp3.TlsVersion;
|
||||
@ -41,7 +40,6 @@ import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
@ -55,33 +53,46 @@ import java.util.concurrent.TimeUnit;
|
||||
*/
|
||||
|
||||
public class HttpClient {
|
||||
private static OkHttpClient sOkHttpClient;
|
||||
private static Context sContext;
|
||||
private static HashMap<String, List<Cookie>> sCookieStore = new HashMap<>();
|
||||
private static LogInterceptor sLogInterceptor;
|
||||
private static Interceptor sDebugInterceptor;
|
||||
private Context mContext;
|
||||
private HashMap<String, List<Cookie>> mCookieStore = new HashMap<>();
|
||||
private LogInterceptor mLogInterceptor = new LogInterceptor();
|
||||
|
||||
public static OkHttpClient getOkHttpClient() {
|
||||
if (sOkHttpClient == null) {
|
||||
try {
|
||||
final X509TrustManager trustManager = new AdvancedX509TrustManager(
|
||||
NetworkUtils.getKnownServersStore(sContext));
|
||||
final SSLSocketFactory sslSocketFactory = getNewSslSocketFactory(trustManager);
|
||||
// Automatic cookie handling, NOT PERSISTENT
|
||||
final CookieJar cookieJar = new CookieJarImpl(sCookieStore);
|
||||
private OkHttpClient mOkHttpClient = null;
|
||||
|
||||
// TODO: Not verifying the hostname against certificate. ask owncloud security human if this is ok.
|
||||
//.hostnameVerifier(new BrowserCompatHostnameVerifier());
|
||||
sOkHttpClient = buildNewOkHttpClient(sslSocketFactory, trustManager, cookieJar);
|
||||
|
||||
} catch (Exception e) {
|
||||
Timber.e(e, "Could not setup SSL system.");
|
||||
}
|
||||
protected HttpClient(Context context) {
|
||||
if (context == null) {
|
||||
Timber.e("Context may not be NULL!");
|
||||
throw new NullPointerException("Context may not be NULL!");
|
||||
}
|
||||
return sOkHttpClient;
|
||||
mContext = context;
|
||||
}
|
||||
|
||||
private static SSLContext getSslContext() throws NoSuchAlgorithmException {
|
||||
public OkHttpClient getOkHttpClient() {
|
||||
if (mOkHttpClient == null) {
|
||||
try {
|
||||
final X509TrustManager trustManager = new AdvancedX509TrustManager(
|
||||
NetworkUtils.getKnownServersStore(mContext));
|
||||
|
||||
final SSLContext sslContext = buildSSLContext();
|
||||
sslContext.init(null, new TrustManager[]{trustManager}, null);
|
||||
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
|
||||
|
||||
// Automatic cookie handling, NOT PERSISTENT
|
||||
final CookieJar cookieJar = new CookieJarImpl(mCookieStore);
|
||||
mOkHttpClient = buildNewOkHttpClient(sslSocketFactory, trustManager, cookieJar);
|
||||
|
||||
} catch (NoSuchAlgorithmException nsae) {
|
||||
Timber.e(nsae, "Could not setup SSL system.");
|
||||
throw new RuntimeException("Could not setup okHttp client.", nsae);
|
||||
} catch (Exception e) {
|
||||
Timber.e(e, "Could not setup okHttp client.");
|
||||
throw new RuntimeException("Could not setup okHttp client.", e);
|
||||
}
|
||||
}
|
||||
return mOkHttpClient;
|
||||
}
|
||||
|
||||
private SSLContext buildSSLContext() throws NoSuchAlgorithmException {
|
||||
try {
|
||||
return SSLContext.getInstance(TlsVersion.TLS_1_3.javaName());
|
||||
} catch (NoSuchAlgorithmException tlsv13Exception) {
|
||||
@ -102,15 +113,8 @@ public class HttpClient {
|
||||
}
|
||||
}
|
||||
|
||||
private static SSLSocketFactory getNewSslSocketFactory(X509TrustManager trustManager)
|
||||
throws NoSuchAlgorithmException, KeyManagementException {
|
||||
final SSLContext sslContext = getSslContext();
|
||||
sslContext.init(null, new TrustManager[]{trustManager}, null);
|
||||
return sslContext.getSocketFactory();
|
||||
}
|
||||
|
||||
private static OkHttpClient buildNewOkHttpClient(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager,
|
||||
CookieJar cookieJar) {
|
||||
private OkHttpClient buildNewOkHttpClient(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager,
|
||||
CookieJar cookieJar) {
|
||||
return new OkHttpClient.Builder()
|
||||
.addNetworkInterceptor(getLogInterceptor())
|
||||
.addNetworkInterceptor(DebugInterceptorFactory.INSTANCE.getInterceptor())
|
||||
@ -125,22 +129,19 @@ public class HttpClient {
|
||||
.build();
|
||||
}
|
||||
|
||||
public static LogInterceptor getLogInterceptor() {
|
||||
if (sLogInterceptor == null) {
|
||||
sLogInterceptor = new LogInterceptor();
|
||||
}
|
||||
return sLogInterceptor;
|
||||
}
|
||||
|
||||
public Context getContext() {
|
||||
return sContext;
|
||||
return mContext;
|
||||
}
|
||||
|
||||
public static void setContext(Context context) {
|
||||
sContext = context;
|
||||
public LogInterceptor getLogInterceptor() {
|
||||
return mLogInterceptor;
|
||||
}
|
||||
|
||||
public List<Cookie> getCookiesFromUrl(HttpUrl httpUrl) {
|
||||
return mCookieStore.get(httpUrl.host());
|
||||
}
|
||||
|
||||
public void clearCookies() {
|
||||
sCookieStore.clear();
|
||||
mCookieStore.clear();
|
||||
}
|
||||
}
|
||||
|
@ -38,24 +38,41 @@ import java.net.URL
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
abstract class HttpBaseMethod constructor(url: URL) {
|
||||
var okHttpClient: OkHttpClient
|
||||
var httpUrl: HttpUrl = url.toHttpUrlOrNull() ?: throw MalformedURLException()
|
||||
var request: Request
|
||||
private var _followPermanentRedirects = false
|
||||
var followPermanentRedirects = false
|
||||
abstract var response: Response
|
||||
|
||||
var call: Call? = null
|
||||
|
||||
var followRedirects: Boolean = true
|
||||
var retryOnConnectionFailure: Boolean = false
|
||||
var connectionTimeoutVal: Long? = null
|
||||
var connectionTimeoutUnit: TimeUnit? = null
|
||||
var readTimeoutVal: Long? = null
|
||||
private set
|
||||
var readTimeoutUnit: TimeUnit? = null
|
||||
private set
|
||||
|
||||
init {
|
||||
okHttpClient = HttpClient.getOkHttpClient()
|
||||
request = Request.Builder()
|
||||
.url(httpUrl)
|
||||
.build()
|
||||
}
|
||||
|
||||
@Throws(Exception::class)
|
||||
open fun execute(): Int {
|
||||
return onExecute()
|
||||
open fun execute(httpClient: HttpClient): Int {
|
||||
val okHttpClient = httpClient.okHttpClient.newBuilder().apply {
|
||||
retryOnConnectionFailure.let { retryOnConnectionFailure(it) }
|
||||
followRedirects.let { followRedirects(it) }
|
||||
readTimeoutUnit?.let { unit ->
|
||||
readTimeoutVal?.let { readTimeout(it, unit) }
|
||||
}
|
||||
connectionTimeoutUnit?.let { unit ->
|
||||
connectionTimeoutVal?.let { connectTimeout(it, unit) }
|
||||
}
|
||||
}.build()
|
||||
|
||||
return onExecute(okHttpClient)
|
||||
}
|
||||
|
||||
open fun setUrl(url: HttpUrl) {
|
||||
@ -137,42 +154,21 @@ abstract class HttpBaseMethod constructor(url: URL) {
|
||||
// Setter
|
||||
//////////////////////////////
|
||||
// Connection parameters
|
||||
open fun setRetryOnConnectionFailure(retryOnConnectionFailure: Boolean) {
|
||||
okHttpClient = okHttpClient.newBuilder()
|
||||
.retryOnConnectionFailure(retryOnConnectionFailure)
|
||||
.build()
|
||||
}
|
||||
|
||||
|
||||
open fun setReadTimeout(readTimeout: Long, timeUnit: TimeUnit) {
|
||||
okHttpClient = okHttpClient.newBuilder()
|
||||
.readTimeout(readTimeout, timeUnit)
|
||||
.build()
|
||||
readTimeoutVal = readTimeout
|
||||
readTimeoutUnit = timeUnit
|
||||
}
|
||||
|
||||
open fun setConnectionTimeout(
|
||||
connectionTimeout: Long,
|
||||
timeUnit: TimeUnit
|
||||
) {
|
||||
okHttpClient = okHttpClient.newBuilder()
|
||||
.readTimeout(connectionTimeout, timeUnit)
|
||||
.build()
|
||||
connectionTimeoutVal = connectionTimeout
|
||||
connectionTimeoutUnit = timeUnit
|
||||
}
|
||||
|
||||
open fun setFollowRedirects(followRedirects: Boolean) {
|
||||
okHttpClient = okHttpClient.newBuilder()
|
||||
.followRedirects(followRedirects)
|
||||
.build()
|
||||
}
|
||||
|
||||
open fun getFollowRedirects() = okHttpClient.followRedirects
|
||||
|
||||
open fun setFollowPermanentRedirects(followRedirects: Boolean) {
|
||||
_followPermanentRedirects = followRedirects
|
||||
}
|
||||
|
||||
open fun getFollowPermanentRedirects() = _followPermanentRedirects
|
||||
|
||||
|
||||
/************
|
||||
*** Call ***
|
||||
************/
|
||||
@ -187,5 +183,5 @@ abstract class HttpBaseMethod constructor(url: URL) {
|
||||
// For override
|
||||
//////////////////////////////
|
||||
@Throws(Exception::class)
|
||||
protected abstract fun onExecute(): Int
|
||||
protected abstract fun onExecute(okHttpClient: OkHttpClient): Int
|
||||
}
|
||||
|
@ -23,6 +23,7 @@
|
||||
*/
|
||||
package com.owncloud.android.lib.common.http.methods.nonwebdav
|
||||
|
||||
import okhttp3.OkHttpClient
|
||||
import java.io.IOException
|
||||
import java.net.URL
|
||||
|
||||
@ -33,10 +34,10 @@ import java.net.URL
|
||||
*/
|
||||
class DeleteMethod(url: URL) : HttpMethod(url) {
|
||||
@Throws(IOException::class)
|
||||
override fun onExecute(): Int {
|
||||
override fun onExecute(okHttpClient: OkHttpClient): Int {
|
||||
request = request.newBuilder()
|
||||
.delete()
|
||||
.build()
|
||||
return super.onExecute()
|
||||
return super.onExecute(okHttpClient)
|
||||
}
|
||||
}
|
||||
|
@ -23,6 +23,7 @@
|
||||
*/
|
||||
package com.owncloud.android.lib.common.http.methods.nonwebdav
|
||||
|
||||
import okhttp3.OkHttpClient
|
||||
import java.io.IOException
|
||||
import java.net.URL
|
||||
|
||||
@ -33,10 +34,10 @@ import java.net.URL
|
||||
*/
|
||||
class GetMethod(url: URL) : HttpMethod(url) {
|
||||
@Throws(IOException::class)
|
||||
override fun onExecute(): Int {
|
||||
override fun onExecute(okHttpClient: OkHttpClient): Int {
|
||||
request = request.newBuilder()
|
||||
.get()
|
||||
.build()
|
||||
return super.onExecute()
|
||||
return super.onExecute(okHttpClient)
|
||||
}
|
||||
}
|
||||
|
@ -24,6 +24,7 @@
|
||||
package com.owncloud.android.lib.common.http.methods.nonwebdav
|
||||
|
||||
import com.owncloud.android.lib.common.http.methods.HttpBaseMethod
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Response
|
||||
import java.net.URL
|
||||
|
||||
@ -38,7 +39,7 @@ abstract class HttpMethod(
|
||||
|
||||
override lateinit var response: Response
|
||||
|
||||
public override fun onExecute(): Int {
|
||||
public override fun onExecute(okHttpClient: OkHttpClient): Int {
|
||||
call = okHttpClient.newCall(request)
|
||||
call?.let { response = it.execute() }
|
||||
return super.statusCode
|
||||
|
@ -23,6 +23,7 @@
|
||||
*/
|
||||
package com.owncloud.android.lib.common.http.methods.nonwebdav
|
||||
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.RequestBody
|
||||
import java.io.IOException
|
||||
import java.net.URL
|
||||
@ -37,10 +38,10 @@ class PostMethod(
|
||||
private val postRequestBody: RequestBody
|
||||
) : HttpMethod(url) {
|
||||
@Throws(IOException::class)
|
||||
override fun onExecute(): Int {
|
||||
override fun onExecute(okHttpClient: OkHttpClient): Int {
|
||||
request = request.newBuilder()
|
||||
.post(postRequestBody)
|
||||
.build()
|
||||
return super.onExecute()
|
||||
return super.onExecute(okHttpClient)
|
||||
}
|
||||
}
|
||||
|
@ -23,6 +23,7 @@
|
||||
*/
|
||||
package com.owncloud.android.lib.common.http.methods.nonwebdav
|
||||
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.RequestBody
|
||||
import java.io.IOException
|
||||
import java.net.URL
|
||||
@ -37,10 +38,10 @@ class PutMethod(
|
||||
private val putRequestBody: RequestBody
|
||||
) : HttpMethod(url) {
|
||||
@Throws(IOException::class)
|
||||
override fun onExecute(): Int {
|
||||
override fun onExecute(okHttpClient: OkHttpClient): Int {
|
||||
request = request.newBuilder()
|
||||
.put(putRequestBody)
|
||||
.build()
|
||||
return super.onExecute()
|
||||
return super.onExecute(okHttpClient)
|
||||
}
|
||||
}
|
||||
|
@ -23,6 +23,7 @@
|
||||
*/
|
||||
package com.owncloud.android.lib.common.http.methods.webdav
|
||||
|
||||
import at.bitfire.dav4jvm.DavOCResource
|
||||
import okhttp3.Response
|
||||
import java.net.URL
|
||||
|
||||
@ -38,7 +39,7 @@ class CopyMethod(
|
||||
private val forceOverride: Boolean
|
||||
) : DavMethod(url) {
|
||||
@Throws(Exception::class)
|
||||
public override fun onExecute(): Int {
|
||||
public override fun onDavExecute(davResource: DavOCResource): Int {
|
||||
davResource.copy(
|
||||
destinationUrl,
|
||||
forceOverride,
|
||||
|
@ -29,14 +29,11 @@ import at.bitfire.dav4jvm.exception.HttpException
|
||||
import at.bitfire.dav4jvm.exception.RedirectException
|
||||
import com.owncloud.android.lib.common.http.HttpConstants
|
||||
import com.owncloud.android.lib.common.http.methods.HttpBaseMethod
|
||||
import okhttp3.HttpUrl
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Protocol
|
||||
import okhttp3.Response
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import java.net.MalformedURLException
|
||||
import java.net.URL
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* Wrapper to perform WebDAV (dav4android) calls
|
||||
@ -44,27 +41,25 @@ import java.util.concurrent.TimeUnit
|
||||
* @author David González Verdugo
|
||||
*/
|
||||
abstract class DavMethod protected constructor(url: URL) : HttpBaseMethod(url) {
|
||||
protected var davResource: DavOCResource
|
||||
|
||||
override lateinit var response: Response
|
||||
|
||||
init {
|
||||
val httpUrl = url.toHttpUrlOrNull() ?: throw MalformedURLException()
|
||||
davResource = DavOCResource(
|
||||
okHttpClient,
|
||||
httpUrl,
|
||||
log
|
||||
)
|
||||
}
|
||||
private var davResource: DavOCResource? = null
|
||||
|
||||
override fun abort() {
|
||||
davResource.cancelCall()
|
||||
davResource?.cancelCall()
|
||||
}
|
||||
|
||||
protected abstract fun onDavExecute(davResource: DavOCResource): Int
|
||||
|
||||
@Throws(Exception::class)
|
||||
override fun execute(): Int {
|
||||
override fun onExecute(okHttpClient: OkHttpClient): Int {
|
||||
return try {
|
||||
onExecute()
|
||||
davResource = DavOCResource(
|
||||
okHttpClient.newBuilder().followRedirects(false).build(),
|
||||
httpUrl,
|
||||
log
|
||||
)
|
||||
|
||||
onDavExecute(davResource!!)
|
||||
} catch (httpException: HttpException) {
|
||||
// Modify responses with information gathered from exceptions
|
||||
if (httpException is RedirectException) {
|
||||
@ -91,71 +86,12 @@ abstract class DavMethod protected constructor(url: URL) : HttpBaseMethod(url) {
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////
|
||||
// Setter
|
||||
//////////////////////////////
|
||||
// Connection parameters
|
||||
override fun setReadTimeout(readTimeout: Long, timeUnit: TimeUnit) {
|
||||
super.setReadTimeout(readTimeout, timeUnit)
|
||||
davResource = DavOCResource(
|
||||
okHttpClient,
|
||||
request.url,
|
||||
log
|
||||
)
|
||||
}
|
||||
|
||||
override fun setConnectionTimeout(
|
||||
connectionTimeout: Long,
|
||||
timeUnit: TimeUnit
|
||||
) {
|
||||
super.setConnectionTimeout(connectionTimeout, timeUnit)
|
||||
davResource = DavOCResource(
|
||||
okHttpClient,
|
||||
request.url,
|
||||
log
|
||||
)
|
||||
}
|
||||
|
||||
override fun setFollowRedirects(followRedirects: Boolean) {
|
||||
super.setFollowRedirects(followRedirects)
|
||||
davResource = DavOCResource(
|
||||
okHttpClient,
|
||||
request.url,
|
||||
log
|
||||
)
|
||||
}
|
||||
|
||||
override fun setUrl(url: HttpUrl) {
|
||||
super.setUrl(url)
|
||||
davResource = DavOCResource(
|
||||
okHttpClient,
|
||||
request.url,
|
||||
log
|
||||
)
|
||||
}
|
||||
|
||||
override fun setRequestHeader(name: String, value: String) {
|
||||
super.setRequestHeader(name, value)
|
||||
davResource = DavOCResource(
|
||||
okHttpClient,
|
||||
request.url,
|
||||
log
|
||||
)
|
||||
}
|
||||
|
||||
//////////////////////////////
|
||||
// Getter
|
||||
//////////////////////////////
|
||||
override fun setRetryOnConnectionFailure(retryOnConnectionFailure: Boolean) {
|
||||
super.setRetryOnConnectionFailure(retryOnConnectionFailure)
|
||||
davResource = DavOCResource(
|
||||
okHttpClient,
|
||||
request.url,
|
||||
log
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
override val isAborted: Boolean
|
||||
get() = davResource.isCallAborted()
|
||||
get() = davResource?.isCallAborted() ?: false
|
||||
|
||||
}
|
||||
|
@ -23,6 +23,7 @@
|
||||
*/
|
||||
package com.owncloud.android.lib.common.http.methods.webdav
|
||||
|
||||
import at.bitfire.dav4jvm.DavOCResource
|
||||
import okhttp3.Response
|
||||
import java.net.URL
|
||||
|
||||
@ -34,7 +35,7 @@ import java.net.URL
|
||||
*/
|
||||
class MkColMethod(url: URL) : DavMethod(url) {
|
||||
@Throws(Exception::class)
|
||||
public override fun onExecute(): Int {
|
||||
public override fun onDavExecute(davResource: DavOCResource): Int {
|
||||
davResource.mkCol(
|
||||
xmlBody = null,
|
||||
listOfHeaders = super.getRequestHeadersAsHashMap()
|
||||
|
@ -23,6 +23,7 @@
|
||||
*/
|
||||
package com.owncloud.android.lib.common.http.methods.webdav
|
||||
|
||||
import at.bitfire.dav4jvm.DavOCResource
|
||||
import okhttp3.Response
|
||||
import java.net.URL
|
||||
|
||||
@ -38,7 +39,7 @@ class MoveMethod(
|
||||
private val forceOverride: Boolean
|
||||
) : DavMethod(url) {
|
||||
@Throws(Exception::class)
|
||||
public override fun onExecute(): Int {
|
||||
override fun onDavExecute(davResource: DavOCResource): Int {
|
||||
davResource.move(
|
||||
destinationUrl,
|
||||
forceOverride,
|
||||
|
@ -23,6 +23,7 @@
|
||||
*/
|
||||
package com.owncloud.android.lib.common.http.methods.webdav
|
||||
|
||||
import at.bitfire.dav4jvm.DavOCResource
|
||||
import at.bitfire.dav4jvm.Property
|
||||
import at.bitfire.dav4jvm.Response
|
||||
import at.bitfire.dav4jvm.Response.HrefRelation
|
||||
@ -47,7 +48,7 @@ class PropfindMethod(
|
||||
private set
|
||||
|
||||
@Throws(IOException::class, DavException::class)
|
||||
public override fun onExecute(): Int {
|
||||
public override fun onDavExecute(davResource: DavOCResource): Int {
|
||||
davResource.propfind(
|
||||
depth = depth,
|
||||
reqProp = propertiesToRequest,
|
||||
|
@ -23,6 +23,7 @@
|
||||
*/
|
||||
package com.owncloud.android.lib.common.http.methods.webdav
|
||||
|
||||
import at.bitfire.dav4jvm.DavOCResource
|
||||
import at.bitfire.dav4jvm.exception.HttpException
|
||||
import com.owncloud.android.lib.common.http.HttpConstants
|
||||
import okhttp3.RequestBody
|
||||
@ -39,7 +40,7 @@ class PutMethod(
|
||||
private val putRequestBody: RequestBody
|
||||
) : DavMethod(url) {
|
||||
@Throws(IOException::class, HttpException::class)
|
||||
public override fun onExecute(): Int {
|
||||
public override fun onDavExecute(davResource: DavOCResource): Int {
|
||||
davResource.put(
|
||||
putRequestBody,
|
||||
super.getRequestHeader(HttpConstants.IF_MATCH_HEADER),
|
||||
|
@ -92,7 +92,8 @@ public class CopyRemoteFileOperation extends RemoteOperation<String> {
|
||||
RemoteOperationResult result;
|
||||
try {
|
||||
CopyMethod copyMethod =
|
||||
new CopyMethod(new URL(client.getUserFilesWebDavUri() + WebdavUtils.encodePath(mSrcRemotePath)),
|
||||
new CopyMethod(
|
||||
new URL(client.getUserFilesWebDavUri() + WebdavUtils.encodePath(mSrcRemotePath)),
|
||||
client.getUserFilesWebDavUri() + WebdavUtils.encodePath(mTargetRemotePath),
|
||||
mOverwrite);
|
||||
|
||||
|
@ -87,7 +87,8 @@ public class CreateRemoteFolderOperation extends RemoteOperation {
|
||||
RemoteOperationResult result;
|
||||
try {
|
||||
Uri webDavUri = createChunksFolder ? client.getUploadsWebDavUri() : client.getUserFilesWebDavUri();
|
||||
final MkColMethod mkcol = new MkColMethod(new URL(webDavUri + WebdavUtils.encodePath(mRemotePath)));
|
||||
final MkColMethod mkcol = new MkColMethod(
|
||||
new URL(webDavUri + WebdavUtils.encodePath(mRemotePath)));
|
||||
mkcol.setReadTimeout(READ_TIMEOUT, TimeUnit.SECONDS);
|
||||
mkcol.setConnectionTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS);
|
||||
final int status = client.executeHttpMethod(mkcol);
|
||||
|
@ -76,7 +76,8 @@ public class ReadRemoteFileOperation extends RemoteOperation<RemoteFile> {
|
||||
/// take the duty of check the server for the current state of the file there
|
||||
try {
|
||||
// remote request
|
||||
propfind = new PropfindMethod(new URL(client.getUserFilesWebDavUri() + WebdavUtils.encodePath(mRemotePath)),
|
||||
propfind = new PropfindMethod(
|
||||
new URL(client.getUserFilesWebDavUri() + WebdavUtils.encodePath(mRemotePath)),
|
||||
DEPTH_0,
|
||||
DavUtils.getAllPropset());
|
||||
|
||||
|
@ -91,7 +91,8 @@ public class RenameRemoteFileOperation extends RemoteOperation {
|
||||
return new RemoteOperationResult<>(ResultCode.INVALID_OVERWRITE);
|
||||
}
|
||||
|
||||
final MoveMethod move = new MoveMethod(new URL(client.getUserFilesWebDavUri() +
|
||||
final MoveMethod move = new MoveMethod(
|
||||
new URL(client.getUserFilesWebDavUri() +
|
||||
WebdavUtils.encodePath(mOldRemotePath)),
|
||||
client.getUserFilesWebDavUri() + WebdavUtils.encodePath(mNewRemotePath), false);
|
||||
|
||||
|
@ -50,7 +50,7 @@ class UploadFileFromContentUriOperation(
|
||||
|
||||
override fun run(client: OwnCloudClient): RemoteOperationResult<Unit> {
|
||||
val putMethod = PutMethod(URL(client.userFilesWebDavUri.toString() + WebdavUtils.encodePath(uploadPath)), requestBody).apply {
|
||||
setRetryOnConnectionFailure(false)
|
||||
retryOnConnectionFailure = false
|
||||
addRequestHeader(HttpConstants.OC_TOTAL_LENGTH_HEADER, requestBody.contentLength().toString())
|
||||
addRequestHeader(HttpConstants.OC_X_OC_MTIME_HEADER, lastModified)
|
||||
}
|
||||
|
@ -92,7 +92,8 @@ public class ChunkedUploadRemoteFileOperation extends UploadRemoteFileOperation
|
||||
result = new RemoteOperationResult<>(new OperationCancelledException());
|
||||
break;
|
||||
} else {
|
||||
mPutMethod = new PutMethod(new URL(uriPrefix + File.separator + chunkIndex), mFileRequestBody);
|
||||
mPutMethod = new PutMethod(
|
||||
new URL(uriPrefix + File.separator + chunkIndex), mFileRequestBody);
|
||||
|
||||
if (chunkIndex == chunkCount - 1) {
|
||||
// Added a high timeout to the last chunk due to when the last chunk
|
||||
|
@ -55,7 +55,7 @@ class GetOIDCDiscoveryRemoteOperation : RemoteOperation<OIDCDiscoveryResponse>()
|
||||
addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE)
|
||||
}
|
||||
|
||||
getMethod.setFollowRedirects(true)
|
||||
getMethod.followRedirects = true
|
||||
val status = client.executeHttpMethod(getMethod)
|
||||
|
||||
val responseBody = getMethod.getResponseBodyAsString()
|
||||
|
@ -138,7 +138,6 @@ class CreateRemoteShareOperation(
|
||||
}
|
||||
|
||||
private fun createFormBody(): FormBody {
|
||||
|
||||
val formBodyBuilder = FormBody.Builder()
|
||||
.add(PARAM_PATH, remoteFilePath)
|
||||
.add(PARAM_SHARE_TYPE, shareType.value.toString())
|
||||
|
@ -104,6 +104,7 @@ class RemoveRemoteShareOperation(private val remoteShareId: String) : RemoteOper
|
||||
|
||||
override fun run(client: OwnCloudClient): RemoteOperationResult<ShareResponse> {
|
||||
|
||||
|
||||
val requestUri = buildRequestUri(client.baseUri)
|
||||
|
||||
val deleteMethod = DeleteMethod(URL(requestUri.toString())).apply {
|
||||
|
@ -195,6 +195,7 @@ class UpdateRemoteShareOperation
|
||||
return formBodyBuilder
|
||||
}
|
||||
|
||||
|
||||
override fun run(client: OwnCloudClient): RemoteOperationResult<ShareResponse> {
|
||||
val requestUri = buildRequestUri(client.baseUri)
|
||||
|
||||
@ -205,7 +206,6 @@ class UpdateRemoteShareOperation
|
||||
addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE)
|
||||
}
|
||||
|
||||
|
||||
return try {
|
||||
val status = client.executeHttpMethod(putMethod)
|
||||
val response = putMethod.getResponseBodyAsString()
|
||||
|
@ -53,6 +53,7 @@ class GetRemoteStatusOperation : RemoteOperation<RemoteServerInfo>() {
|
||||
client.baseUri = Uri.parse(newBaseUrl)
|
||||
}
|
||||
|
||||
|
||||
private fun tryToConnect(client: OwnCloudClient): RemoteOperationResult<RemoteServerInfo> {
|
||||
val baseUrl = client.baseUri.toString()
|
||||
return try {
|
||||
|
@ -79,9 +79,9 @@ internal class StatusRequester {
|
||||
fun request(baseLocation: String, client: OwnCloudClient): RequestResult {
|
||||
val currentLocation = baseLocation + OwnCloudClient.STATUS_PATH
|
||||
var status: Int
|
||||
|
||||
val getMethod = getGetMethod(currentLocation)
|
||||
getMethod.setFollowPermanentRedirects(true)
|
||||
|
||||
getMethod.followPermanentRedirects = true
|
||||
status = client.executeHttpMethod(getMethod)
|
||||
|
||||
return RequestResult(getMethod, status, getMethod.getFinalUrl().toString())
|
||||
|
@ -23,12 +23,13 @@
|
||||
*/
|
||||
package com.owncloud.android.lib.resources.status.services
|
||||
|
||||
|
||||
import com.owncloud.android.lib.common.OwnCloudClient
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult
|
||||
import com.owncloud.android.lib.resources.status.RemoteServerInfo
|
||||
|
||||
interface ServerInfoService {
|
||||
fun checkPathExistence(path: String, isUserLogged: Boolean, client: OwnCloudClient): RemoteOperationResult<Boolean>
|
||||
fun checkPathExistence(path: String, isUserLoggedIn: Boolean, client: OwnCloudClient): RemoteOperationResult<Boolean>
|
||||
|
||||
fun getRemoteStatus(path: String, client: OwnCloudClient): RemoteOperationResult<RemoteServerInfo>
|
||||
}
|
||||
|
@ -26,6 +26,7 @@
|
||||
|
||||
package com.owncloud.android.lib.resources.status.services.implementation
|
||||
|
||||
|
||||
import com.owncloud.android.lib.common.OwnCloudClient
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult
|
||||
import com.owncloud.android.lib.resources.files.CheckPathExistenceRemoteOperation
|
||||
@ -37,7 +38,7 @@ class OCServerInfoService : ServerInfoService {
|
||||
|
||||
override fun checkPathExistence(
|
||||
path: String,
|
||||
isUserLogged: Boolean,
|
||||
isUserLoggedIn: Boolean,
|
||||
client: OwnCloudClient
|
||||
): RemoteOperationResult<Boolean> =
|
||||
CheckPathExistenceRemoteOperation(
|
||||
|
@ -1,302 +0,0 @@
|
||||
/* ownCloud Android Library is available under MIT license
|
||||
* Copyright (C) 2020 ownCloud GmbH.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
package com.owncloud.android.lib.sampleclient;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Activity;
|
||||
import android.content.pm.PackageInfo;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.res.AssetManager;
|
||||
import android.graphics.drawable.BitmapDrawable;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.view.View;
|
||||
import android.widget.ListView;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import com.owncloud.android.lib.common.ConnectionValidator;
|
||||
import com.owncloud.android.lib.common.OwnCloudClient;
|
||||
import com.owncloud.android.lib.common.SingleSessionManager;
|
||||
import com.owncloud.android.lib.common.authentication.OwnCloudCredentialsFactory;
|
||||
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.resources.files.DownloadRemoteFileOperation;
|
||||
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 com.owncloud.android.lib.resources.files.UploadRemoteFileOperation;
|
||||
import timber.log.Timber;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class MainActivity extends Activity implements OnRemoteOperationListener, OnDatatransferProgressListener {
|
||||
|
||||
private Handler mHandler;
|
||||
private OwnCloudClient mClient;
|
||||
private FilesArrayAdapter mFilesAdapter;
|
||||
private View mFrame;
|
||||
|
||||
/**
|
||||
* Called when the activity is first created.
|
||||
*/
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.main);
|
||||
|
||||
Timber.plant();
|
||||
mHandler = new Handler();
|
||||
|
||||
final Uri serverUri = Uri.parse(getString(R.string.server_base_url));
|
||||
|
||||
SingleSessionManager.setUserAgent(getUserAgent());
|
||||
SingleSessionManager.setConnectionValidator(new ConnectionValidator(this, false));
|
||||
mClient = new OwnCloudClient(serverUri,
|
||||
SingleSessionManager.getConnectionValidator(),
|
||||
true,
|
||||
SingleSessionManager.getDefaultSingleton());
|
||||
mClient.setCredentials(
|
||||
OwnCloudCredentialsFactory.newBasicCredentials(
|
||||
getString(R.string.username),
|
||||
getString(R.string.password)
|
||||
)
|
||||
);
|
||||
|
||||
mFilesAdapter = new FilesArrayAdapter(this, R.layout.file_in_list);
|
||||
((ListView) findViewById(R.id.list_view)).setAdapter(mFilesAdapter);
|
||||
|
||||
// TODO move to background thread or task
|
||||
AssetManager assets = getAssets();
|
||||
try {
|
||||
String sampleFileName = getString(R.string.sample_file_name);
|
||||
File upFolder = new File(getCacheDir(), getString(R.string.upload_folder_path));
|
||||
upFolder.mkdir();
|
||||
File upFile = new File(upFolder, sampleFileName);
|
||||
FileOutputStream fos = new FileOutputStream(upFile);
|
||||
InputStream is = assets.open(sampleFileName);
|
||||
int count;
|
||||
byte[] buffer = new byte[1024];
|
||||
while ((count = is.read(buffer, 0, buffer.length)) >= 0) {
|
||||
fos.write(buffer, 0, count);
|
||||
}
|
||||
is.close();
|
||||
fos.close();
|
||||
} catch (IOException e) {
|
||||
Toast.makeText(this, R.string.error_copying_sample_file, Toast.LENGTH_SHORT).show();
|
||||
Timber.e(e, getString(R.string.error_copying_sample_file));
|
||||
}
|
||||
|
||||
mFrame = findViewById(R.id.frame);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
File upFolder = new File(getCacheDir(), getString(R.string.upload_folder_path));
|
||||
File upFile = upFolder.listFiles()[0];
|
||||
upFile.delete();
|
||||
upFolder.delete();
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
public void onClickHandler(View button) {
|
||||
switch (button.getId()) {
|
||||
case R.id.button_refresh:
|
||||
startRefresh();
|
||||
break;
|
||||
case R.id.button_upload:
|
||||
startUpload();
|
||||
break;
|
||||
case R.id.button_delete_remote:
|
||||
startRemoteDeletion();
|
||||
break;
|
||||
case R.id.button_download:
|
||||
startDownload();
|
||||
break;
|
||||
case R.id.button_delete_local:
|
||||
startLocalDeletion();
|
||||
break;
|
||||
default:
|
||||
Toast.makeText(this, R.string.youre_doing_it_wrong, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
private void startRefresh() {
|
||||
ReadRemoteFolderOperation refreshOperation = new ReadRemoteFolderOperation(File.separator);
|
||||
refreshOperation.execute(mClient, this, mHandler);
|
||||
}
|
||||
|
||||
private void startUpload() {
|
||||
File upFolder = new File(getCacheDir(), getString(R.string.upload_folder_path));
|
||||
File fileToUpload = upFolder.listFiles()[0];
|
||||
String remotePath = File.separator + fileToUpload.getName();
|
||||
String mimeType = getString(R.string.sample_file_mimetype);
|
||||
|
||||
// Get the last modification date of the file from the file system
|
||||
long timeStampLong = fileToUpload.lastModified() / 1000;
|
||||
String timeStamp = Long.toString(timeStampLong);
|
||||
|
||||
UploadRemoteFileOperation uploadOperation = new UploadRemoteFileOperation(fileToUpload.getAbsolutePath(),
|
||||
remotePath, mimeType, timeStamp);
|
||||
uploadOperation.addDatatransferProgressListener(this);
|
||||
uploadOperation.execute(mClient, this, mHandler);
|
||||
}
|
||||
|
||||
private void startRemoteDeletion() {
|
||||
File upFolder = new File(getCacheDir(), getString(R.string.upload_folder_path));
|
||||
File fileToUpload = upFolder.listFiles()[0];
|
||||
String remotePath = File.separator + fileToUpload.getName();
|
||||
|
||||
RemoveRemoteFileOperation removeOperation = new RemoveRemoteFileOperation(remotePath);
|
||||
removeOperation.execute(mClient, this, mHandler);
|
||||
}
|
||||
|
||||
private void startDownload() {
|
||||
File downFolder = new File(getCacheDir(), getString(R.string.download_folder_path));
|
||||
downFolder.mkdir();
|
||||
File upFolder = new File(getCacheDir(), getString(R.string.upload_folder_path));
|
||||
File fileToUpload = upFolder.listFiles()[0];
|
||||
String remotePath = File.separator + fileToUpload.getName();
|
||||
|
||||
DownloadRemoteFileOperation downloadOperation = new DownloadRemoteFileOperation(remotePath,
|
||||
downFolder.getAbsolutePath());
|
||||
downloadOperation.addDatatransferProgressListener(this);
|
||||
downloadOperation.execute(mClient, this, mHandler);
|
||||
}
|
||||
|
||||
private void startLocalDeletion() {
|
||||
File downFolder = new File(getCacheDir(), getString(R.string.download_folder_path));
|
||||
File downloadedFile = downFolder.listFiles()[0];
|
||||
if (!downloadedFile.delete() && downloadedFile.exists()) {
|
||||
Toast.makeText(this, R.string.error_deleting_local_file, Toast.LENGTH_SHORT).show();
|
||||
} else {
|
||||
((TextView) findViewById(R.id.download_progress)).setText("0%");
|
||||
findViewById(R.id.frame).setBackgroundDrawable(null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
|
||||
if (!result.isSuccess()) {
|
||||
Toast.makeText(this, R.string.todo_operation_finished_in_fail, Toast.LENGTH_SHORT).show();
|
||||
Timber.e(result.getException(), result.getLogMessage());
|
||||
|
||||
} else if (operation instanceof ReadRemoteFolderOperation) {
|
||||
onSuccessfulRefresh(result);
|
||||
|
||||
} else if (operation instanceof com.owncloud.android.lib.resources.files.UploadRemoteFileOperation) {
|
||||
onSuccessfulUpload();
|
||||
|
||||
} else if (operation instanceof RemoveRemoteFileOperation) {
|
||||
onSuccessfulRemoteDeletion();
|
||||
|
||||
} else if (operation instanceof DownloadRemoteFileOperation) {
|
||||
onSuccessfulDownload();
|
||||
|
||||
} else {
|
||||
Toast.makeText(this, R.string.todo_operation_finished_in_success, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
private void onSuccessfulRefresh(RemoteOperationResult result) {
|
||||
mFilesAdapter.clear();
|
||||
List<RemoteFile> files = new ArrayList<>();
|
||||
for (RemoteFile remoteFile : (List<RemoteFile>) result.getData()) {
|
||||
files.add(remoteFile);
|
||||
}
|
||||
for (RemoteFile file : files) {
|
||||
mFilesAdapter.add(file);
|
||||
}
|
||||
mFilesAdapter.remove(mFilesAdapter.getItem(0));
|
||||
mFilesAdapter.notifyDataSetChanged();
|
||||
}
|
||||
|
||||
private void onSuccessfulUpload() {
|
||||
startRefresh();
|
||||
}
|
||||
|
||||
private void onSuccessfulRemoteDeletion() {
|
||||
startRefresh();
|
||||
TextView progressView = findViewById(R.id.upload_progress);
|
||||
if (progressView != null) {
|
||||
progressView.setText("0%");
|
||||
}
|
||||
}
|
||||
|
||||
private void onSuccessfulDownload() {
|
||||
File downFolder = new File(getCacheDir(), getString(R.string.download_folder_path));
|
||||
File downloadedFile = downFolder.listFiles()[0];
|
||||
BitmapDrawable bDraw = new BitmapDrawable(getResources(), downloadedFile.getAbsolutePath());
|
||||
mFrame.setBackgroundDrawable(bDraw);
|
||||
}
|
||||
|
||||
@SuppressLint("SetTextI18n")
|
||||
@Override
|
||||
public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {
|
||||
final long percentage = (totalToTransfer > 0 ? totalTransferredSoFar * 100 / totalToTransfer : 0);
|
||||
final boolean upload = fileName.contains(getString(R.string.upload_folder_path));
|
||||
Timber.d("progressRate %s", percentage);
|
||||
mHandler.post(() -> {
|
||||
TextView progressView;
|
||||
if (upload) {
|
||||
progressView = findViewById(R.id.upload_progress);
|
||||
} else {
|
||||
progressView = findViewById(R.id.download_progress);
|
||||
}
|
||||
if (progressView != null) {
|
||||
progressView.setText(percentage + "%");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// user agent
|
||||
@SuppressLint("StringFormatInvalid")
|
||||
private String getUserAgent() {
|
||||
String appString = getResources().getString(R.string.user_agent);
|
||||
String packageName = getPackageName();
|
||||
String version = "";
|
||||
|
||||
PackageInfo pInfo;
|
||||
try {
|
||||
pInfo = getPackageManager().getPackageInfo(packageName, 0);
|
||||
if (pInfo != null) {
|
||||
version = pInfo.versionName;
|
||||
}
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
Timber.e(e);
|
||||
}
|
||||
|
||||
// Mozilla/5.0 (Android) ownCloud-android/1.7.0
|
||||
return String.format(appString, version);
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user