Initial QSfera import

This commit is contained in:
Курнат Андрей
2026-06-07 10:20:04 +03:00
commit 2315f25754
16485 changed files with 4826827 additions and 0 deletions
+72
View File
@@ -0,0 +1,72 @@
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'com.google.devtools.ksp'
apply plugin: 'kotlin-parcelize'
dependencies {
api 'com.squareup.okhttp3:okhttp:4.9.2'
implementation libs.kotlin.stdlib
api files('libs/qsfera-android-dav-oc_support_2.1.5.jar')
// Androidx
implementation libs.androidx.core.ktx
implementation libs.androidx.lifecycle.livedata.ktx
implementation libs.androidx.annotation
// Moshi
implementation(libs.moshi.kotlin) {
exclude module: "kotlin-reflect"
}
implementation 'org.apache.commons:commons-lang3:3.12.0'
ksp libs.moshi.kotlin.codegen
// Timber
implementation libs.timber
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.robolectric:robolectric:4.15.1'
// MockWebServer for HTTP integration tests
testImplementation 'com.squareup.okhttp3:mockwebserver:4.9.2'
testImplementation 'com.squareup.okhttp3:okhttp-tls:4.9.2'
// AndroidX test core to obtain application context in unit tests
testImplementation libs.androidx.test.core
debugImplementation 'com.facebook.stetho:stetho-okhttp3:1.6.0'
// Detekt
detektPlugins libs.detekt.formatting
detektPlugins libs.detekt.libraries
}
android {
compileSdkVersion sdkCompileVersion
defaultConfig {
minSdkVersion sdkMinVersion
targetSdkVersion sdkTargetVersion
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_17.toString()
}
lint {
abortOnError false
ignoreWarnings true
}
testOptions {
unitTests {
includeAndroidResources = true
}
}
namespace 'eu.qsfera.android.lib'
}
tasks.withType(io.gitlab.arturbosch.detekt.Detekt).configureEach {
jvmTarget = "17"
}
@@ -0,0 +1,30 @@
/* qsfera 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 eu.qsfera.android.lib.common.http
import com.facebook.stetho.okhttp3.StethoInterceptor
object DebugInterceptorFactory {
fun getInterceptor() = StethoInterceptor()
}
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- qsfera Android Library is available under MIT license
Copyright (C) 2023 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.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
@@ -0,0 +1,221 @@
/* qsfera 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 eu.qsfera.android.lib.common
import android.accounts.AccountManager
import android.accounts.AccountsException
import android.content.Context
import eu.qsfera.android.lib.common.authentication.QSferaCredentials
import eu.qsfera.android.lib.common.authentication.QSferaCredentialsFactory.QSferaAnonymousCredentials
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.resources.files.CheckPathExistenceRemoteOperation
import eu.qsfera.android.lib.resources.status.GetRemoteStatusOperation
import eu.qsfera.android.lib.resources.status.RemoteServerInfo
import org.apache.commons.lang3.exception.ExceptionUtils
import timber.log.Timber
import java.io.IOException
/**
* ConnectionValidator
*
* @author Christian Schabesberger
*/
class ConnectionValidator(
val context: Context,
private val clearCookiesOnValidation: Boolean
) {
fun validate(baseClient: QSferaClient, singleSessionManager: SingleSessionManager, context: Context): Boolean {
try {
var validationRetryCount = 0
val client = QSferaClient(baseClient.baseUri, null, false, singleSessionManager, context)
if (clearCookiesOnValidation) {
client.clearCookies()
} else {
client.cookiesForBaseUri = baseClient.cookiesForBaseUri
}
client.account = baseClient.account
client.credentials = baseClient.credentials
while (validationRetryCount < VALIDATION_RETRY_COUNT) {
Timber.d("validationRetryCount %d", validationRetryCount)
var successCounter = 0
var failCounter = 0
client.setFollowRedirects(true)
if (isQSferaStatusOk(client)) {
successCounter++
} else {
failCounter++
}
// Skip the part where we try to check if we can access the parts where we have to be logged in... if we are not logged in
if (baseClient.credentials !is QSferaAnonymousCredentials) {
client.setFollowRedirects(false)
val contentReply = canAccessRootFolder(client)
if (contentReply.httpCode == HttpConstants.HTTP_OK) {
if (contentReply.data == true) { //if data is true it means that the content reply was ok
successCounter++
} else {
failCounter++
}
} else {
failCounter++
if (contentReply.httpCode == HttpConstants.HTTP_UNAUTHORIZED) {
checkUnauthorizedAccess(client, singleSessionManager, contentReply.httpCode)
}
}
}
if (successCounter >= failCounter) {
baseClient.credentials = client.credentials
baseClient.cookiesForBaseUri = client.cookiesForBaseUri
return true
}
validationRetryCount++
}
Timber.d("Could not authenticate or get valid data from qsfera")
} catch (e: Exception) {
Timber.d(ExceptionUtils.getStackTrace(e))
}
return false
}
private fun isQSferaStatusOk(client: QSferaClient): Boolean {
val reply = getQSferaStatus(client)
// dont check status code. It currently relais on the broken redirect code of the qsfera client
// To do: Use okhttp redirect and add this check again
// return reply.httpCode == HttpConstants.HTTP_OK &&
return !reply.isException &&
reply.data != null
}
private fun getQSferaStatus(client: QSferaClient): RemoteOperationResult<RemoteServerInfo> {
val remoteStatusOperation = GetRemoteStatusOperation()
return remoteStatusOperation.execute(client)
}
private fun canAccessRootFolder(client: QSferaClient): RemoteOperationResult<Boolean> {
val checkPathExistenceRemoteOperation = CheckPathExistenceRemoteOperation("/", true)
return checkPathExistenceRemoteOperation.execute(client)
}
/**
* Determines if credentials should be invalidated according the to the HTTPS status
* of a network request just performed.
*
* @param httpStatusCode Result of the last request ran with the 'credentials' belows.
* @return 'True' if credentials should and might be invalidated, 'false' if shouldn't or
* cannot be invalidated with the given arguments.
*/
private fun shouldInvalidateAccountCredentials(credentials: QSferaCredentials, account: QSferaAccount, httpStatusCode: Int): Boolean {
var shouldInvalidateAccountCredentials = httpStatusCode == HttpConstants.HTTP_UNAUTHORIZED
shouldInvalidateAccountCredentials = shouldInvalidateAccountCredentials and // real credentials
(credentials !is QSferaAnonymousCredentials)
// test if have all the needed to effectively invalidate ...
shouldInvalidateAccountCredentials =
shouldInvalidateAccountCredentials and (account.savedAccount != null)
Timber.d(
"""Received error: $httpStatusCode,
account: ${account.name}
credentials are real: ${credentials !is QSferaAnonymousCredentials},
so we need to invalidate credentials for account ${account.name} : $shouldInvalidateAccountCredentials"""
)
return shouldInvalidateAccountCredentials
}
/**
* Invalidates credentials stored for the given account in the system [AccountManager] and in
* current [SingleSessionManager.getDefaultSingleton] instance.
*
*
* [.shouldInvalidateAccountCredentials] should be called first.
*
*/
private fun invalidateAccountCredentials(account: QSferaAccount, credentials: QSferaCredentials) {
Timber.i("Invalidating account credentials for account $account")
val am = AccountManager.get(context)
am.invalidateAuthToken(
account.savedAccount.type,
credentials.authToken
)
am.clearPassword(account.savedAccount) // being strict, only needed for Basic Auth credentials
}
/**
* Checks the status code of an execution and decides if should be repeated with fresh credentials.
*
*
* Invalidates current credentials if the request failed as anauthorized.
*
*
* Refresh current credentials if possible, and marks a retry.
*
* @return
*/
private fun checkUnauthorizedAccess(client: QSferaClient, singleSessionManager: SingleSessionManager, status: Int): Boolean {
var credentialsWereRefreshed = false
val account = client.account
val credentials = account.credentials
if (shouldInvalidateAccountCredentials(credentials, account, status)) {
invalidateAccountCredentials(account, credentials)
if (credentials.authTokenCanBeRefreshed()) {
try {
// This command does the actual refresh
Timber.i("Trying to refresh auth token for account $account")
account.loadCredentials(context)
// if mAccount.getCredentials().length() == 0 --> refresh failed
client.credentials = account.credentials
credentialsWereRefreshed = true
} catch (e: AccountsException) {
Timber.e(
e, "Error while trying to refresh auth token for %s\ntrace: %s",
account.savedAccount.name,
ExceptionUtils.getStackTrace(e)
)
} catch (e: IOException) {
Timber.e(
e, "Error while trying to refresh auth token for %s\ntrace: %s",
account.savedAccount.name,
ExceptionUtils.getStackTrace(e)
)
}
if (!credentialsWereRefreshed) {
// if credentials are not refreshed, client must be removed
// from the QSferaClientManager to prevent it is reused once and again
Timber.w("Credentials were not refreshed, client will be removed from the Session Manager to prevent using it over and over")
singleSessionManager.removeClientFor(account)
}
}
// else: onExecute will finish with status 401
}
return credentialsWereRefreshed
}
companion object {
private const val VALIDATION_RETRY_COUNT = 3
}
}
@@ -0,0 +1,152 @@
/* qsfera 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 eu.qsfera.android.lib.common;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Context;
import android.net.Uri;
import eu.qsfera.android.lib.common.accounts.AccountUtils;
import eu.qsfera.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
import eu.qsfera.android.lib.common.authentication.QSferaCredentials;
import eu.qsfera.android.lib.common.authentication.QSferaCredentialsFactory;
import java.io.IOException;
/**
* QSfera Account
*
* @author David A. Velasco
*/
public class QSferaAccount {
private Uri mBaseUri;
private QSferaCredentials mCredentials;
private String mDisplayName;
private String mSavedAccountName;
private Account mSavedAccount;
/**
* Constructor for already saved OC accounts.
* <p>
* Do not use for anonymous credentials.
*/
public QSferaAccount(Account savedAccount, Context context) throws AccountNotFoundException {
if (savedAccount == null) {
throw new IllegalArgumentException("Parameter 'savedAccount' cannot be null");
}
if (context == null) {
throw new IllegalArgumentException("Parameter 'context' cannot be null");
}
mSavedAccount = savedAccount;
mSavedAccountName = savedAccount.name;
mCredentials = null; // load of credentials is delayed
AccountManager ama = AccountManager.get(context.getApplicationContext());
String baseUrl = ama.getUserData(mSavedAccount, AccountUtils.Constants.KEY_OC_BASE_URL);
if (baseUrl == null) {
throw new AccountNotFoundException(mSavedAccount, "Account not found", null);
}
mBaseUri = Uri.parse(AccountUtils.getBaseUrlForAccount(context, mSavedAccount));
mDisplayName = ama.getUserData(mSavedAccount, AccountUtils.Constants.KEY_DISPLAY_NAME);
}
/**
* Constructor for non yet saved OC accounts.
*
* @param baseUri URI to the OC server to get access to.
* @param credentials Credentials to authenticate in the server. NULL is valid for anonymous credentials.
*/
public QSferaAccount(Uri baseUri, QSferaCredentials credentials) {
if (baseUri == null) {
throw new IllegalArgumentException("Parameter 'baseUri' cannot be null");
}
mSavedAccount = null;
mSavedAccountName = null;
mBaseUri = baseUri;
mCredentials = credentials != null ?
credentials : QSferaCredentialsFactory.getAnonymousCredentials();
String username = mCredentials.getUsername();
if (username != null) {
mSavedAccountName = AccountUtils.buildAccountName(mBaseUri, username);
}
}
/**
* Method for deferred load of account attributes from AccountManager
*
* @param context
* @throws AuthenticatorException
* @throws IOException
* @throws OperationCanceledException
*/
public void loadCredentials(Context context) throws AuthenticatorException, IOException, OperationCanceledException {
if (context == null) {
throw new IllegalArgumentException("Parameter 'context' cannot be null");
}
if (mSavedAccount != null) {
mCredentials = AccountUtils.getCredentialsForAccount(context, mSavedAccount);
}
}
public Uri getBaseUri() {
return mBaseUri;
}
public QSferaCredentials getCredentials() {
return mCredentials;
}
public String getName() {
return mSavedAccountName;
}
public Account getSavedAccount() {
return mSavedAccount;
}
public String getDisplayName() {
if (mDisplayName != null && mDisplayName.length() > 0) {
return mDisplayName;
} else if (mCredentials != null) {
return mCredentials.getUsername();
} else if (mSavedAccount != null) {
return AccountUtils.getUsernameForAccount(mSavedAccount);
} else {
return null;
}
}
}
@@ -0,0 +1,266 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2020 ownCloud GmbH.
* Copyright (C) 2012 Bartek Przybylski
*
* 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 eu.qsfera.android.lib.common;
import android.content.Context;
import android.net.Uri;
import eu.qsfera.android.lib.common.accounts.AccountUtils;
import eu.qsfera.android.lib.common.authentication.QSferaCredentials;
import eu.qsfera.android.lib.common.authentication.QSferaCredentialsFactory;
import eu.qsfera.android.lib.common.authentication.QSferaCredentialsFactory.QSferaAnonymousCredentials;
import eu.qsfera.android.lib.common.http.HttpClient;
import eu.qsfera.android.lib.common.http.HttpConstants;
import eu.qsfera.android.lib.common.http.methods.HttpBaseMethod;
import eu.qsfera.android.lib.common.utils.RandomUtils;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
import timber.log.Timber;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Locale;
import static eu.qsfera.android.lib.common.http.HttpConstants.AUTHORIZATION_HEADER;
import static eu.qsfera.android.lib.common.http.HttpConstants.HTTP_MOVED_PERMANENTLY;
public class QSferaClient extends HttpClient {
public static final String WEBDAV_FILES_PATH_4_0 = "/remote.php/dav/files/";
public static final String STATUS_PATH = "/status.php";
private static final String WEBDAV_UPLOADS_PATH_4_0 = "/remote.php/dav/uploads/";
private static final int MAX_RETRY_COUNT = 2;
private static int sIntanceCounter = 0;
private QSferaCredentials mCredentials = null;
private int mInstanceNumber;
private Uri mBaseUri;
private QSferaAccount mAccount;
private final ConnectionValidator mConnectionValidator;
private Object mRequestMutex = new Object();
// If set to true a mutex will be used to prevent parallel execution of the execute() method
// if false the execute() method can be called even though the mutex is already aquired.
// This is used for the ConnectionValidator, which has to be able to execute OperationsWhile all "normal" operations net
// to be set on hold.
private final Boolean mSynchronizeRequests;
private SingleSessionManager mSingleSessionManager = null;
private boolean mFollowRedirects = false;
public QSferaClient(Uri baseUri,
ConnectionValidator connectionValidator,
boolean synchronizeRequests,
SingleSessionManager singleSessionManager,
Context context) {
super(context);
if (baseUri == null) {
throw new IllegalArgumentException("Parameter 'baseUri' cannot be NULL");
}
mBaseUri = baseUri;
mSynchronizeRequests = synchronizeRequests;
mSingleSessionManager = singleSessionManager;
mInstanceNumber = sIntanceCounter++;
Timber.d("#" + mInstanceNumber + "Creating QSferaClient");
clearCredentials();
clearCookies();
mConnectionValidator = connectionValidator;
}
public void clearCredentials() {
if (!(mCredentials instanceof QSferaAnonymousCredentials)) {
mCredentials = QSferaCredentialsFactory.getAnonymousCredentials();
}
}
public int executeHttpMethod(HttpBaseMethod method) throws Exception {
if (mSynchronizeRequests) {
synchronized (mRequestMutex) {
return saveExecuteHttpMethod(method);
}
} else {
return saveExecuteHttpMethod(method);
}
}
private int saveExecuteHttpMethod(HttpBaseMethod method) throws Exception {
int repeatCounter = 0;
int status;
if (mFollowRedirects) {
method.setFollowRedirects(true);
}
boolean retry;
do {
repeatCounter++;
retry = false;
String requestId = RandomUtils.generateRandomUUID();
// Header to allow tracing requests in apache and qsfera logs
Timber.d("Executing in request with id %s", requestId);
method.setRequestHeader(HttpConstants.OC_X_REQUEST_ID, requestId);
// In tests the user agent may not be initialised; avoid passing null to headers.
String userAgent = SingleSessionManager.getUserAgent();
if (userAgent != null && !userAgent.isEmpty()) {
method.setRequestHeader(HttpConstants.USER_AGENT_HEADER, userAgent);
}
String acceptLanguage = Locale.getDefault().getLanguage();
if (acceptLanguage != null && !acceptLanguage.isEmpty()) {
method.setRequestHeader(HttpConstants.ACCEPT_LANGUAGE_HEADER, acceptLanguage);
}
method.setRequestHeader(HttpConstants.ACCEPT_ENCODING_HEADER, HttpConstants.ACCEPT_ENCODING_IDENTITY);
if (mCredentials.getHeaderAuth() != null && !mCredentials.getHeaderAuth().isEmpty()) {
method.setRequestHeader(AUTHORIZATION_HEADER, mCredentials.getHeaderAuth());
}
status = method.execute(this);
if (shouldConnectionValidatorBeCalled(method, status)) {
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);
}
} while (retry && repeatCounter < MAX_RETRY_COUNT);
return status;
}
private boolean shouldConnectionValidatorBeCalled(HttpBaseMethod method, int status) {
return mConnectionValidator != null && (
(!(mCredentials instanceof QSferaAnonymousCredentials) &&
status == HttpConstants.HTTP_UNAUTHORIZED
) || (!mFollowRedirects &&
!method.getFollowRedirects() &&
status == HttpConstants.HTTP_MOVED_TEMPORARILY
)
);
}
/**
* Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation.
*
* @param responseBodyAsStream InputStream with the HTTP response to exhaust.
*/
public void exhaustResponse(InputStream responseBodyAsStream) {
if (responseBodyAsStream != null) {
try {
responseBodyAsStream.close();
} catch (IOException io) {
Timber.e(io, "Unexpected exception while exhausting not interesting HTTP response; will be IGNORED");
}
}
}
public Uri getBaseFilesWebDavUri() {
return Uri.parse(mBaseUri + WEBDAV_FILES_PATH_4_0);
}
public Uri getUserFilesWebDavUri() {
return (mCredentials instanceof QSferaAnonymousCredentials || mAccount == null)
? Uri.parse(mBaseUri + WEBDAV_FILES_PATH_4_0)
: Uri.parse(mBaseUri + WEBDAV_FILES_PATH_4_0 + AccountUtils.getUserId(
mAccount.getSavedAccount(), getContext()
)
);
}
public Uri getUploadsWebDavUri() {
// Always include the userId segment when an account is present to avoid permission issues
// on servers that scope the uploads collection under the user path.
return (mAccount == null)
? Uri.parse(mBaseUri + WEBDAV_UPLOADS_PATH_4_0)
: Uri.parse(mBaseUri + WEBDAV_UPLOADS_PATH_4_0 + AccountUtils.getUserId(
mAccount.getSavedAccount(), getContext()
)
);
}
public Uri getBaseUri() {
return mBaseUri;
}
/**
* Sets the root URI to the qsfera server.
* <p>
* Use with care.
*
* @param uri
*/
public void setBaseUri(Uri uri) {
if (uri == null) {
throw new IllegalArgumentException("URI cannot be NULL");
}
mBaseUri = uri;
}
public final QSferaCredentials getCredentials() {
return mCredentials;
}
public void setCredentials(QSferaCredentials credentials) {
if (credentials != null) {
mCredentials = credentials;
} else {
clearCredentials();
}
}
public void setCookiesForBaseUri(List<Cookie> cookies) {
getOkHttpClient().cookieJar().saveFromResponse(
HttpUrl.parse(mBaseUri.toString()),
cookies
);
}
public List<Cookie> getCookiesForBaseUri() {
return getOkHttpClient().cookieJar().loadForRequest(
HttpUrl.parse(mBaseUri.toString()));
}
public QSferaAccount getAccount() {
return mAccount;
}
public void setAccount(QSferaAccount account) {
this.mAccount = account;
}
public void setFollowRedirects(boolean followRedirects) {
this.mFollowRedirects = followRedirects;
}
}
@@ -0,0 +1,225 @@
/* qsfera 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 eu.qsfera.android.lib.common;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Context;
import android.net.Uri;
import eu.qsfera.android.lib.common.accounts.AccountUtils;
import eu.qsfera.android.lib.common.authentication.QSferaCredentials;
import timber.log.Timber;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @author David A. Velasco
* @author masensio
* @author Christian Schabesberger
* @author David González Verdugo
*/
public class SingleSessionManager {
private static SingleSessionManager sDefaultSingleton;
private static String sUserAgent;
private static ConnectionValidator sConnectionValidator;
private ConcurrentMap<String, QSferaClient> mClientsWithKnownUsername = new ConcurrentHashMap<>();
private ConcurrentMap<String, QSferaClient> mClientsWithUnknownUsername = new ConcurrentHashMap<>();
public static SingleSessionManager getDefaultSingleton() {
if (sDefaultSingleton == null) {
sDefaultSingleton = new SingleSessionManager();
}
return sDefaultSingleton;
}
public static void setConnectionValidator(ConnectionValidator connectionValidator) {
sConnectionValidator = connectionValidator;
}
public static ConnectionValidator getConnectionValidator() {
return sConnectionValidator;
}
public static String getUserAgent() {
return sUserAgent;
}
public static void setUserAgent(String userAgent) {
sUserAgent = userAgent;
}
private static QSferaClient createQSferaClient(Uri uri,
Context context,
ConnectionValidator connectionValidator,
SingleSessionManager singleSessionManager) {
QSferaClient client = new QSferaClient(uri, connectionValidator, true, singleSessionManager, context);
return client;
}
public QSferaClient getClientFor(QSferaAccount account,
Context context) throws OperationCanceledException,
AuthenticatorException, IOException {
return getClientFor(account, context, getConnectionValidator());
}
public QSferaClient getClientFor(QSferaAccount account,
Context context,
ConnectionValidator connectionValidator) throws OperationCanceledException,
AuthenticatorException, IOException {
Timber.d("getClientFor starting ");
if (account == null) {
throw new IllegalArgumentException("Cannot get an QSferaClient for a null account");
}
QSferaClient client = null;
String accountName = account.getName();
String sessionName = account.getCredentials() == null ? "" :
AccountUtils.buildAccountName(account.getBaseUri(), account.getCredentials().getAuthToken());
if (accountName != null) {
client = mClientsWithKnownUsername.get(accountName);
}
boolean reusingKnown = false; // just for logs
if (client == null) {
if (accountName != null) {
client = mClientsWithUnknownUsername.remove(sessionName);
if (client != null) {
Timber.v("reusing client for session %s", sessionName);
mClientsWithKnownUsername.put(accountName, client);
Timber.v("moved client to account %s", accountName);
}
} else {
client = mClientsWithUnknownUsername.get(sessionName);
}
} else {
Timber.v("reusing client for account %s", accountName);
if (client.getAccount() != null &&
client.getAccount().getCredentials() != null &&
(client.getAccount().getCredentials().getAuthToken() == null || client.getAccount().getCredentials().getAuthToken().isEmpty())
) {
Timber.i("Client " + client.getAccount().getName() + " needs to refresh credentials");
//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
client.clearCookies();
client.clearCredentials();
client.setAccount(account);
account.loadCredentials(context);
client.setCredentials(account.getCredentials());
Timber.i("Client " + account.getName() + " with credentials size" + client.getAccount().getCredentials().getAuthToken().length());
}
reusingKnown = true;
}
if (client == null) {
// no client to reuse - create a new one
client = createQSferaClient(
account.getBaseUri(),
context,
connectionValidator,
this); // TODO remove dependency on QSferaClientFactory
//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
client.clearCookies();
client.clearCredentials();
client.setAccount(account);
account.loadCredentials(context);
client.setCredentials(account.getCredentials());
if (accountName != null) {
mClientsWithKnownUsername.put(accountName, client);
Timber.v("new client for account %s", accountName);
} else {
mClientsWithUnknownUsername.put(sessionName, client);
Timber.v("new client for session %s", sessionName);
}
} else {
if (!reusingKnown) {
Timber.v("reusing client for session %s", sessionName);
}
keepUriUpdated(account, client);
}
Timber.d("getClientFor finishing ");
return client;
}
public void removeClientFor(QSferaAccount account) {
Timber.d("removeClientFor starting ");
if (account == null) {
return;
}
QSferaClient client;
String accountName = account.getName();
if (accountName != null) {
client = mClientsWithKnownUsername.remove(accountName);
if (client != null) {
Timber.v("Removed client for account %s", accountName);
return;
} else {
Timber.v("No client tracked for account %s", accountName);
}
}
mClientsWithUnknownUsername.clear();
Timber.d("removeClientFor finishing ");
}
public void refreshCredentialsForAccount(String accountName, QSferaCredentials credentials) {
QSferaClient qsferaClient = mClientsWithKnownUsername.get(accountName);
if (qsferaClient == null) {
return;
}
qsferaClient.setCredentials(credentials);
mClientsWithKnownUsername.replace(accountName, qsferaClient);
}
// this method is just a patch; we need to distinguish accounts in the same host but
// different paths; but that requires updating the accountNames for apps upgrading
private void keepUriUpdated(QSferaAccount account, QSferaClient reusedClient) {
Uri recentUri = account.getBaseUri();
if (!recentUri.equals(reusedClient.getBaseUri())) {
reusedClient.setBaseUri(recentUri);
}
}
}
@@ -0,0 +1,44 @@
/* qsfera 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 eu.qsfera.android.lib.common.accounts;
/**
* @author masensio
* @author David A. Velasco
*/
public class AccountTypeUtils {
public static String getAuthTokenTypePass(String accountType) {
return accountType + ".password";
}
public static String getAuthTokenTypeAccessToken(String accountType) {
return accountType + ".oauth2.access_token";
}
public static String getAuthTokenTypeRefreshToken(String accountType) {
return accountType + ".oauth2.refresh_token";
}
}
@@ -0,0 +1,228 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2020 ownCloud GmbH.
* Copyright (C) 2012 Bartek Przybylski
*
* 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 eu.qsfera.android.lib.common.accounts;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountsException;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Context;
import android.net.Uri;
import eu.qsfera.android.lib.common.QSferaClient;
import eu.qsfera.android.lib.common.authentication.QSferaCredentials;
import eu.qsfera.android.lib.common.authentication.QSferaCredentialsFactory;
import eu.qsfera.android.lib.resources.status.QSferaVersion;
import timber.log.Timber;
import java.io.IOException;
public class AccountUtils {
/**
* Constructs full url to host and webdav resource basing on host version
*
* @param context Valid Android {@link Context}, needed to access the {@link AccountManager}
* @param account A stored qsfera {@link Account}
* @return Full URL to WebDAV endpoint in the server corresponding to 'account'.
* @throws AccountNotFoundException When 'account' is unknown for the AccountManager
*/
public static String getWebDavUrlForAccount(Context context, Account account)
throws AccountNotFoundException {
return getBaseUrlForAccount(context, account) + QSferaClient.WEBDAV_FILES_PATH_4_0
+ AccountUtils.getUserId(account, context);
}
/**
* Extracts url server from the account
*
* @param context Valid Android {@link Context}, needed to access the {@link AccountManager}
* @param account A stored qsfera {@link Account}
* @return Full URL to the server corresponding to 'account', ending in the base path
* common to all API endpoints.
* @throws AccountNotFoundException When 'account' is unknown for the AccountManager
*/
public static String getBaseUrlForAccount(Context context, Account account)
throws AccountNotFoundException {
AccountManager ama = AccountManager.get(context.getApplicationContext());
String baseurl = ama.getUserData(account, Constants.KEY_OC_BASE_URL);
if (baseurl == null) {
throw new AccountNotFoundException(account, "Account not found", null);
}
return baseurl;
}
/**
* Get the username corresponding to an OC account.
*
* @param account An OC account
* @return Username for the given account, extracted from the account.name
*/
public static String getUsernameForAccount(Account account) {
String username = null;
try {
username = account.name.substring(0, account.name.lastIndexOf('@'));
} catch (Exception e) {
Timber.e(e, "Couldn't get a username for the given account");
}
return username;
}
/**
* @return
* @throws IOException
* @throws AuthenticatorException
* @throws OperationCanceledException
*/
public static QSferaCredentials getCredentialsForAccount(Context context, Account account)
throws OperationCanceledException, AuthenticatorException, IOException {
QSferaCredentials credentials;
AccountManager am = AccountManager.get(context);
String supportsOAuth2 = am.getUserData(account, AccountUtils.Constants.KEY_SUPPORTS_OAUTH2);
boolean isOauth2 = supportsOAuth2 != null && supportsOAuth2.equals(Constants.OAUTH_SUPPORTED_TRUE);
String username = AccountUtils.getUsernameForAccount(account);
if (isOauth2) {
Timber.i("Trying to retrieve credentials for oAuth account" + account.name);
String accessToken = am.blockingGetAuthToken(
account,
AccountTypeUtils.getAuthTokenTypeAccessToken(account.type),
false);
credentials = QSferaCredentialsFactory.newBearerCredentials(username, accessToken);
} else {
String password = am.blockingGetAuthToken(
account,
AccountTypeUtils.getAuthTokenTypePass(account.type),
false);
credentials = QSferaCredentialsFactory.newBasicCredentials(
username,
password
);
}
return credentials;
}
/**
* Get the user id corresponding to an OC account.
*
* @param account qsfera account
* @return user id
*/
public static String getUserId(Account account, Context context) {
AccountManager accountMgr = AccountManager.get(context);
return accountMgr.getUserData(account, Constants.KEY_ID);
}
public static String buildAccountNameOld(Uri serverBaseUrl, String username) {
if (serverBaseUrl.getScheme() == null) {
serverBaseUrl = Uri.parse("https://" + serverBaseUrl.toString());
}
String accountName = username + "@" + serverBaseUrl.getHost();
if (serverBaseUrl.getPort() >= 0) {
accountName += ":" + serverBaseUrl.getPort();
}
return accountName;
}
public static String buildAccountName(Uri serverBaseUrl, String username) {
if (serverBaseUrl.getScheme() == null) {
serverBaseUrl = Uri.parse("https://" + serverBaseUrl.toString());
}
// Remove http:// or https://
String url = serverBaseUrl.toString();
if (url.contains("://")) {
url = url.substring(serverBaseUrl.toString().indexOf("://") + 3);
}
return username + "@" + url;
}
public static class AccountNotFoundException extends AccountsException {
/**
* Generated - should be refreshed every time the class changes!!
*/
private static final long serialVersionUID = -1684392454798508693L;
private Account mFailedAccount;
public AccountNotFoundException() {
super();
}
public AccountNotFoundException(Account failedAccount, String message, Throwable cause) {
super(message, cause);
mFailedAccount = failedAccount;
}
public Account getFailedAccount() {
return mFailedAccount;
}
}
public static class Constants {
/**
* Base url should point to qsfera installation without trailing / ie:
* http://server/path or https://qsfera.server
*/
public static final String KEY_OC_BASE_URL = "oc_base_url";
/**
* Flag signaling if the qsfera server can be accessed with OAuth2 access tokens.
*/
// TODO Please review this constants, move them out of the library, the rest of OAuth variables are in data layer
public static final String KEY_SUPPORTS_OAUTH2 = "oc_supports_oauth2";
public static final String OAUTH_SUPPORTED_TRUE = "TRUE";
/**
* OC account version
*/
public static final String KEY_OC_ACCOUNT_VERSION = "oc_account_version";
/**
* User's id
*/
public static final String KEY_ID = "oc_id";
/**
* User's display name
*/
public static final String KEY_DISPLAY_NAME = "oc_display_name";
public static final int ACCOUNT_VERSION = 1;
}
}
@@ -0,0 +1,64 @@
/* qsfera 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 eu.qsfera.android.lib.common.authentication;
import okhttp3.Credentials;
import static java.nio.charset.StandardCharsets.UTF_8;
public class QSferaBasicCredentials implements QSferaCredentials {
private String mUsername;
private String mPassword;
public QSferaBasicCredentials(String username, String password) {
mUsername = username != null ? username : "";
mPassword = password != null ? password : "";
}
@Override
public String getUsername() {
return mUsername;
}
@Override
public String getAuthToken() {
return mPassword;
}
@Override
public String getHeaderAuth() {
return Credentials.basic(mUsername, mPassword, UTF_8);
}
@Override
public boolean authTokenExpires() {
return false;
}
@Override
public boolean authTokenCanBeRefreshed() {
return false;
}
}
@@ -0,0 +1,63 @@
/* qsfera 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 eu.qsfera.android.lib.common.authentication;
import eu.qsfera.android.lib.common.http.HttpConstants;
public class QSferaBearerCredentials implements QSferaCredentials {
private String mUsername;
private String mAccessToken;
public QSferaBearerCredentials(String username, String accessToken) {
mUsername = username != null ? username : "";
mAccessToken = accessToken != null ? accessToken : "";
}
@Override
public String getUsername() {
// not relevant for authentication, but relevant for informational purposes
return mUsername;
}
@Override
public String getAuthToken() {
return mAccessToken;
}
@Override
public String getHeaderAuth() {
return HttpConstants.BEARER_AUTHORIZATION_KEY + mAccessToken;
}
@Override
public boolean authTokenExpires() {
return true;
}
@Override
public boolean authTokenCanBeRefreshed() {
return true;
}
}
@@ -0,0 +1,38 @@
/* qsfera 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 eu.qsfera.android.lib.common.authentication;
public interface QSferaCredentials {
String getUsername();
String getAuthToken();
String getHeaderAuth();
boolean authTokenExpires();
boolean authTokenCanBeRefreshed();
}
@@ -0,0 +1,79 @@
/* qsfera 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 eu.qsfera.android.lib.common.authentication;
public class QSferaCredentialsFactory {
public static final String CREDENTIAL_CHARSET = "UTF-8";
private static QSferaAnonymousCredentials sAnonymousCredentials;
public static QSferaCredentials newBasicCredentials(String username, String password) {
return new QSferaBasicCredentials(username, password);
}
public static QSferaCredentials newBearerCredentials(String username, String authToken) {
return new QSferaBearerCredentials(username, authToken);
}
public static final QSferaCredentials getAnonymousCredentials() {
if (sAnonymousCredentials == null) {
sAnonymousCredentials = new QSferaAnonymousCredentials();
}
return sAnonymousCredentials;
}
public static final class QSferaAnonymousCredentials implements QSferaCredentials {
protected QSferaAnonymousCredentials() {
}
@Override
public String getAuthToken() {
return "";
}
@Override
public String getHeaderAuth() {
return "";
}
@Override
public boolean authTokenExpires() {
return false;
}
@Override
public boolean authTokenCanBeRefreshed() {
return false;
}
@Override
public String getUsername() {
// no user name
return null;
}
}
}
@@ -0,0 +1,62 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2021 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 eu.qsfera.android.lib.common.http
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
class CookieJarImpl(
private val cookieStore: HashMap<String, List<Cookie>>
) : CookieJar {
fun containsCookieWithName(cookies: List<Cookie>, name: String): Boolean {
for (cookie: Cookie in cookies) {
if (cookie.name == name) {
return true
}
}
return false
}
fun getUpdatedCookies(oldCookies: List<Cookie>, newCookies: List<Cookie>): List<Cookie> {
val updatedList = ArrayList<Cookie>(newCookies)
for (oldCookie: Cookie in oldCookies) {
if (!containsCookieWithName(updatedList, oldCookie.name)) {
updatedList.add(oldCookie)
}
}
return updatedList
}
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
// Avoid duplicated cookies but update
val currentCookies: List<Cookie> = cookieStore[url.host] ?: ArrayList()
val updatedCookies: List<Cookie> = getUpdatedCookies(currentCookies, cookies)
cookieStore[url.host] = updatedCookies
}
override fun loadForRequest(url: HttpUrl) =
cookieStore[url.host] ?: ArrayList()
}
@@ -0,0 +1,31 @@
/* qsfera 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 eu.qsfera.android.lib.common.http
import okhttp3.Interceptor
class DummyInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain) = chain.proceed(chain.request())
}
@@ -0,0 +1,149 @@
/* qsfera 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 eu.qsfera.android.lib.common.http;
import android.content.Context;
import eu.qsfera.android.lib.common.http.logging.LogInterceptor;
import eu.qsfera.android.lib.common.network.AdvancedX509TrustManager;
import eu.qsfera.android.lib.common.network.KnownServersHostnameVerifier;
import eu.qsfera.android.lib.common.network.NetworkUtils;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.TlsVersion;
import timber.log.Timber;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Client used to perform network operations
*
* @author David González Verdugo
*/
public class HttpClient {
private Context mContext;
private HashMap<String, List<Cookie>> mCookieStore = new HashMap<>();
private LogInterceptor mLogInterceptor = new LogInterceptor();
private OkHttpClient mOkHttpClient = null;
protected HttpClient(Context context) {
if (context == null) {
Timber.e("Context may not be NULL!");
throw new NullPointerException("Context may not be NULL!");
}
mContext = context;
}
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) {
try {
Timber.w("TLSv1.3 is not supported in this device; falling through TLSv1.2");
return SSLContext.getInstance(TlsVersion.TLS_1_2.javaName());
} catch (NoSuchAlgorithmException tlsv12Exception) {
try {
Timber.w("TLSv1.2 is not supported in this device; falling through TLSv1.1");
return SSLContext.getInstance(TlsVersion.TLS_1_1.javaName());
} catch (NoSuchAlgorithmException tlsv11Exception) {
Timber.w("TLSv1.1 is not supported in this device; falling through TLSv1.0");
return SSLContext.getInstance(TlsVersion.TLS_1_0.javaName());
// should be available in any device; see reference of supported protocols in
// http://developer.android.com/reference/javax/net/ssl/SSLSocket.html
}
}
}
}
private OkHttpClient buildNewOkHttpClient(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager,
CookieJar cookieJar) {
return new OkHttpClient.Builder()
.addNetworkInterceptor(getLogInterceptor())
.addNetworkInterceptor(DebugInterceptorFactory.INSTANCE.getInterceptor())
.protocols(Collections.singletonList(Protocol.HTTP_1_1))
.readTimeout(HttpConstants.DEFAULT_DATA_TIMEOUT, TimeUnit.MILLISECONDS)
.writeTimeout(HttpConstants.DEFAULT_DATA_TIMEOUT, TimeUnit.MILLISECONDS)
.connectTimeout(HttpConstants.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
.followRedirects(false)
.sslSocketFactory(sslSocketFactory, trustManager)
.hostnameVerifier(new KnownServersHostnameVerifier(mContext))
.cookieJar(cookieJar)
.build();
}
public Context getContext() {
return mContext;
}
public LogInterceptor getLogInterceptor() {
return mLogInterceptor;
}
public List<Cookie> getCookiesFromUrl(HttpUrl httpUrl) {
return mCookieStore.get(httpUrl.host());
}
public void clearCookies() {
mCookieStore.clear();
}
}
@@ -0,0 +1,244 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2024 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 eu.qsfera.android.lib.common.http;
/**
* @author David González Verdugo
*/
public class HttpConstants {
/***********************************************************************************************************
*************************************************** HEADERS ***********************************************
***********************************************************************************************************/
public static final String AUTHORIZATION_HEADER = "Authorization";
public static final String COOKIE_HEADER = "Cookie";
public static final String BEARER_AUTHORIZATION_KEY = "Bearer ";
public static final String USER_AGENT_HEADER = "User-Agent";
public static final String IF_MATCH_HEADER = "If-Match";
public static final String IF_NONE_MATCH_HEADER = "If-None-Match";
public static final String CONTENT_TYPE_HEADER = "Content-Type";
public static final String ACCEPT_LANGUAGE_HEADER = "Accept-Language";
public static final String CONTENT_LENGTH_HEADER = "Content-Length";
public static final String OC_TOTAL_LENGTH_HEADER = "OC-Total-Length";
public static final String OC_X_OC_MTIME_HEADER = "X-OC-Mtime";
public static final String OC_X_REQUEST_ID = "X-Request-ID";
public static final String X_HTTP_METHOD_OVERRIDE = "X-HTTP-Method-Override";
public static final String LOCATION_HEADER = "Location";
public static final String LOCATION_HEADER_LOWER = "location";
public static final String CONTENT_TYPE_URLENCODED_UTF8 = "application/x-www-form-urlencoded; charset=utf-8";
public static final String ACCEPT_ENCODING_HEADER = "Accept-Encoding";
public static final String ACCEPT_ENCODING_IDENTITY = "identity";
public static final String OC_FILE_REMOTE_ID = "OC-FileId";
// TUS protocol headers
public static final String TUS_RESUMABLE = "Tus-Resumable";
public static final String TUS_VERSION = "Tus-Version";
public static final String TUS_EXTENSION = "Tus-Extension";
public static final String TUS_MAX_SIZE = "Tus-Max-Size";
public static final String UPLOAD_OFFSET = "Upload-Offset";
public static final String UPLOAD_LENGTH = "Upload-Length";
public static final String UPLOAD_METADATA = "Upload-Metadata";
public static final String UPLOAD_DEFER_LENGTH = "Upload-Defer-Length";
public static final String UPLOAD_CONCAT = "Upload-Concat";
public static final String UPLOAD_CHECKSUM = "Upload-Checksum";
public static final String UPLOAD_EXPIRES = "Upload-Expires";
// OAuth
public static final String OAUTH_HEADER_AUTHORIZATION_CODE = "code";
public static final String OAUTH_HEADER_GRANT_TYPE = "grant_type";
public static final String OAUTH_HEADER_REDIRECT_URI = "redirect_uri";
public static final String OAUTH_HEADER_REFRESH_TOKEN = "refresh_token";
public static final String OAUTH_HEADER_CODE_VERIFIER = "code_verifier";
public static final String OAUTH_HEADER_SCOPE = "scope";
public static final String OAUTH_BODY_CLIENT_ID = "client_id";
public static final String OAUTH_BODY_CLIENT_SECRET = "client_secret";
/***********************************************************************************************************
************************************************ CONTENT TYPES ********************************************
***********************************************************************************************************/
public static final String CONTENT_TYPE_XML = "application/xml";
public static final String CONTENT_TYPE_JSON = "application/json";
public static final String CONTENT_TYPE_WWW_FORM = "application/x-www-form-urlencoded";
public static final String CONTENT_TYPE_JRD_JSON = "application/jrd+json";
public static final String CONTENT_TYPE_OFFSET_OCTET_STREAM = "application/offset+octet-stream";
/***********************************************************************************************************
************************************************ ARGUMENTS NAMES ********************************************
***********************************************************************************************************/
public static final String PARAM_FORMAT = "format";
/***********************************************************************************************************
************************************************ ARGUMENTS VALUES ********************************************
***********************************************************************************************************/
public static final String VALUE_FORMAT = "json";
public static final String TUS_RESUMABLE_VERSION_1_0_0 = "1.0.0";
/***********************************************************************************************************
************************************************ STATUS CODES *********************************************
***********************************************************************************************************/
/**
* 1xx Informational
*/
// 100 Continue (HTTP/1.1 - RFC 2616)
public static final int HTTP_CONTINUE = 100;
// 101 Switching Protocols (HTTP/1.1 - RFC 2616)
public static final int HTTP_SWITCHING_PROTOCOLS = 101;
// 102 Processing (WebDAV - RFC 2518)
public static final int HTTP_PROCESSING = 102;
/**
* 2xx Success
*/
// 200 OK (HTTP/1.0 - RFC 1945)
public static final int HTTP_OK = 200;
// 201 Created (HTTP/1.0 - RFC 1945)
public static final int HTTP_CREATED = 201;
// 202 Accepted (HTTP/1.0 - RFC 1945)
public static final int HTTP_ACCEPTED = 202;
// 203 Non Authoritative Information (HTTP/1.1 - RFC 2616)
public static final int HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
// 204 No Content</tt> (HTTP/1.0 - RFC 1945)
public static final int HTTP_NO_CONTENT = 204;
// 205 Reset Content</tt> (HTTP/1.1 - RFC 2616)
public static final int HTTP_RESET_CONTENT = 205;
// 206 Partial Content</tt> (HTTP/1.1 - RFC 2616)
public static final int HTTP_PARTIAL_CONTENT = 206;
//207 Multi-Status (WebDAV - RFC 2518) or 207 Partial Update OK (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?)
public static final int HTTP_MULTI_STATUS = 207;
/**
* 3xx Redirection
*/
// 300 Mutliple Choices</tt> (HTTP/1.1 - RFC 2616)
public static final int HTTP_MULTIPLE_CHOICES = 300;
// 301 Moved Permanently</tt> (HTTP/1.0 - RFC 1945)
public static final int HTTP_MOVED_PERMANENTLY = 301;
// 302 Moved Temporarily</tt> (Sometimes <tt>Found) (HTTP/1.0 - RFC 1945)
public static final int HTTP_MOVED_TEMPORARILY = 302;
// 303 See Other (HTTP/1.1 - RFC 2616)
public static final int HTTP_SEE_OTHER = 303;
// 304 Not Modified (HTTP/1.0 - RFC 1945)
public static final int HTTP_NOT_MODIFIED = 304;
// 305 Use Proxy (HTTP/1.1 - RFC 2616)
public static final int HTTP_USE_PROXY = 305;
// 307 Temporary Redirect (HTTP/1.1 - RFC 2616)
public static final int HTTP_TEMPORARY_REDIRECT = 307;
// 308 Permanent Redirect (HTTP/1.1 - RFC 7538)
public static final int HTTP_PERMANENT_REDIRECT = 308;
/**
* 4xx Client Error
*/
// 400 Bad Request (HTTP/1.1 - RFC 2616)
public static final int HTTP_BAD_REQUEST = 400;
// 401 Unauthorized (HTTP/1.0 - RFC 1945)
public static final int HTTP_UNAUTHORIZED = 401;
// 402 Payment Required (HTTP/1.1 - RFC 2616)
public static final int HTTP_PAYMENT_REQUIRED = 402;
// 403 Forbidden (HTTP/1.0 - RFC 1945)
public static final int HTTP_FORBIDDEN = 403;
// 404 Not Found (HTTP/1.0 - RFC 1945)
public static final int HTTP_NOT_FOUND = 404;
// 405 Method Not Allowed (HTTP/1.1 - RFC 2616)
public static final int HTTP_METHOD_NOT_ALLOWED = 405;
// 406 Not Acceptable (HTTP/1.1 - RFC 2616)
public static final int HTTP_NOT_ACCEPTABLE = 406;
// 407 Proxy Authentication Required (HTTP/1.1 - RFC 2616)
public static final int HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
// 408 Request Timeout (HTTP/1.1 - RFC 2616)
public static final int HTTP_REQUEST_TIMEOUT = 408;
// 409 Conflict (HTTP/1.1 - RFC 2616)
public static final int HTTP_CONFLICT = 409;
// 410 Gone (HTTP/1.1 - RFC 2616)
public static final int HTTP_GONE = 410;
// 411 Length Required (HTTP/1.1 - RFC 2616)
public static final int HTTP_LENGTH_REQUIRED = 411;
// 412 Precondition Failed (HTTP/1.1 - RFC 2616)
public static final int HTTP_PRECONDITION_FAILED = 412;
// 413 Request Entity Too Large (HTTP/1.1 - RFC 2616)
public static final int HTTP_REQUEST_TOO_LONG = 413;
// 414 Request-URI Too Long (HTTP/1.1 - RFC 2616)
public static final int HTTP_REQUEST_URI_TOO_LONG = 414;
// 415 Unsupported Media Type (HTTP/1.1 - RFC 2616)
public static final int HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
// 416 Requested Range Not Satisfiable (HTTP/1.1 - RFC 2616)
public static final int HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
// 417 Expectation Failed (HTTP/1.1 - RFC 2616)
public static final int HTTP_EXPECTATION_FAILED = 417;
// 419 Insufficient Space on Resource (WebDAV - draft-ietf-webdav-protocol-05?)
// or <tt>419 Proxy Reauthentication Required (HTTP/1.1 drafts?)
public static final int HTTP_INSUFFICIENT_SPACE_ON_RESOURCE = 419;
// 420 Method Failure (WebDAV - draft-ietf-webdav-protocol-05?)
public static final int HTTP_METHOD_FAILURE = 420;
// 422 Unprocessable Entity (WebDAV - RFC 2518)
public static final int HTTP_UNPROCESSABLE_ENTITY = 422;
// 423 Locked (WebDAV - RFC 2518)
public static final int HTTP_LOCKED = 423;
// 424 Failed Dependency (WebDAV - RFC 2518)
public static final int HTTP_FAILED_DEPENDENCY = 424;
public static final int HTTP_TOO_EARLY = 425;
/**
* 5xx Client Error
*/
// 500 Server Error (HTTP/1.0 - RFC 1945)
public static final int HTTP_INTERNAL_SERVER_ERROR = 500;
// 501 Not Implemented (HTTP/1.0 - RFC 1945)
public static final int HTTP_NOT_IMPLEMENTED = 501;
// 502 Bad Gateway (HTTP/1.0 - RFC 1945)
public static final int HTTP_BAD_GATEWAY = 502;
// 503 Service Unavailable (HTTP/1.0 - RFC 1945)
public static final int HTTP_SERVICE_UNAVAILABLE = 503;
// 504 Gateway Timeout (HTTP/1.1 - RFC 2616)
public static final int HTTP_GATEWAY_TIMEOUT = 504;
// 505 HTTP Version Not Supported (HTTP/1.1 - RFC 2616)
public static final int HTTP_HTTP_VERSION_NOT_SUPPORTED = 505;
// 507 Insufficient Storage (WebDAV - RFC 2518)
public static final int HTTP_INSUFFICIENT_STORAGE = 507;
/***********************************************************************************************************
*************************************************** TIMEOUTS **********************************************
***********************************************************************************************************/
/**
* Default timeout for waiting data from the server
*/
public static final int DEFAULT_DATA_TIMEOUT = 60000;
/**
* Default timeout for establishing a connection
*/
public static final int DEFAULT_CONNECTION_TIMEOUT = 60000;
}
@@ -0,0 +1,82 @@
/* qsfera 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 eu.qsfera.android.lib.common.http;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
public class TLSSocketFactory extends SSLSocketFactory {
private SSLSocketFactory mInternalSSLSocketFactory;
public TLSSocketFactory(SSLSocketFactory delegate) {
mInternalSSLSocketFactory = delegate;
}
@Override
public String[] getDefaultCipherSuites() {
return mInternalSSLSocketFactory.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return mInternalSSLSocketFactory.getSupportedCipherSuites();
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(mInternalSSLSocketFactory.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException {
return enableTLSOnSocket(mInternalSSLSocketFactory.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
return enableTLSOnSocket(mInternalSSLSocketFactory.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(mInternalSSLSocketFactory.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws
IOException {
return enableTLSOnSocket(mInternalSSLSocketFactory.createSocket(address, port, localAddress, localPort));
}
private Socket enableTLSOnSocket(Socket socket) {
if((socket instanceof SSLSocket)) {
((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2", "TLSv1.3"});
}
return socket;
}
}
@@ -0,0 +1,44 @@
/* qsfera 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 eu.qsfera.android.lib.common.http.logging
import eu.qsfera.android.lib.common.http.HttpConstants.CONTENT_TYPE_JRD_JSON
import eu.qsfera.android.lib.common.http.HttpConstants.CONTENT_TYPE_JSON
import eu.qsfera.android.lib.common.http.HttpConstants.CONTENT_TYPE_WWW_FORM
import eu.qsfera.android.lib.common.http.HttpConstants.CONTENT_TYPE_XML
import okhttp3.MediaType
/**
* Check whether a media type is loggable.
*
* @return true if its type is text, xml, json, jrd+json or x-www-form-urlencoded.
*/
fun MediaType?.isLoggable(): Boolean =
this?.let { mediaType ->
val mediaTypeString = mediaType.toString()
(mediaType.type == "text" ||
mediaTypeString.contains(CONTENT_TYPE_XML) ||
mediaTypeString.contains(CONTENT_TYPE_JSON) ||
mediaTypeString.contains(CONTENT_TYPE_WWW_FORM) ||
mediaTypeString.contains(CONTENT_TYPE_JRD_JSON))
} ?: false
@@ -0,0 +1,186 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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 eu.qsfera.android.lib.common.http.logging
import eu.qsfera.android.lib.common.http.HttpConstants.AUTHORIZATION_HEADER
import eu.qsfera.android.lib.common.http.HttpConstants.OC_X_REQUEST_ID
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.Headers
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import okio.Buffer
import timber.log.Timber
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import java.util.concurrent.TimeUnit
class LogInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
if (!httpLogsEnabled) {
return chain.proceed(chain.request())
}
val request = chain.request()
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
val response = chain.proceed(request)
logRequest(moshi, request)
return response.also {
logResponse(moshi, it, request)
}
}
private fun logRequest(moshi: Moshi, request: Request) {
val requestJsonAdapter = moshi.adapter(LogRequest::class.java)
val requestId = request.headers[OC_X_REQUEST_ID] ?: ""
Timber.d(
"REQUEST $requestId ${
requestJsonAdapter.toJson(
LogRequest(
Request(
body = getRequestBodyString(request.body),
headers = logHeaders(request.headers),
info = RequestInfo(
id = requestId,
method = request.method,
url = request.url.toString(),
)
)
)
)
}"
)
}
private fun logHeaders(headers: Headers): Map<String, String> {
val auxHeaders = headers.toMap().toMutableMap()
if (auxHeaders.contains(AUTHORIZATION_HEADER)) {
val authHeaderList = auxHeaders[AUTHORIZATION_HEADER]!!.split(" ")
val authType = authHeaderList[0]
val authInfo = if (redactAuthHeader) "[redacted]" else authHeaderList[1]
auxHeaders[AUTHORIZATION_HEADER] = "$authType $authInfo"
}
return auxHeaders
}
private fun getRequestBodyString(requestBodyParam: RequestBody?): String? {
requestBodyParam?.let { requestBody ->
if (requestBody.isOneShot()) {
return "One shot body -- Omitted"
}
if (requestBody.isDuplex()) {
return "Duplex body -- Omitted"
}
val buffer = Buffer()
requestBody.writeTo(buffer)
val contentType = requestBody.contentType()
val charset: Charset = contentType?.charset(StandardCharsets.UTF_8) ?: StandardCharsets.UTF_8
if (contentType.isLoggable()) {
return buffer.readString(charset)
} else if (requestBody.contentLength() > 0) {
return "$BINARY_OMITTED ${requestBody.contentLength()} $BYTES"
}
}
return null
}
private fun logResponse(moshi: Moshi, response: Response, request: Request) {
val responseJsonAdapter = moshi.adapter(LogResponse::class.java)
val contentType = response.body?.contentType()
val charset: Charset = contentType?.charset(StandardCharsets.UTF_8) ?: StandardCharsets.UTF_8
val source = response.body?.source()
source?.request(LIMIT_BODY_LOG)
val buffer = source?.buffer
val rawResponseBody = buffer?.clone()?.readString(charset)
val bodyLength = rawResponseBody?.toByteArray(charset)?.size ?: 0
val responseBody = getResponseBodyString(contentType, bodyLength, rawResponseBody ?: "")
val duration = response.receivedResponseAtMillis - response.sentRequestAtMillis
val requestId = request.headers[OC_X_REQUEST_ID] ?: ""
Timber.d(
"RESPONSE $requestId ${
responseJsonAdapter.toJson(
LogResponse(
Response(
headers = logHeaders(response.headers),
body = responseBody?.let { Body(data = responseBody, length = bodyLength) },
info = ResponseInfo(
id = requestId,
method = request.method,
reply = Reply(
cached = response.cacheResponse != null,
duration = duration,
durationString = getDurationString(duration),
status = response.code,
version = response.protocol.toString(),
),
url = request.url.toString(),
)
)
)
)
}"
)
}
private fun getResponseBodyString(contentType: MediaType?, contentLength: Int, responseBody: String): String? =
if (contentType?.isLoggable() == true) {
responseBody
} else if (contentLength > 0) {
"$BINARY_OMITTED $contentLength $BYTES"
} else {
null
}
private fun getDurationString(millis: Long): String {
var auxMillis = millis
val hours = TimeUnit.MILLISECONDS.toHours(millis)
auxMillis -= TimeUnit.HOURS.toMillis(hours)
val minutes = TimeUnit.MILLISECONDS.toMinutes(auxMillis)
auxMillis -= TimeUnit.MINUTES.toMillis(minutes)
val seconds = TimeUnit.MILLISECONDS.toSeconds(auxMillis)
auxMillis -= TimeUnit.SECONDS.toMillis(seconds)
return String.format(DURATION_FORMAT, hours, minutes, seconds, auxMillis)
}
companion object {
var httpLogsEnabled: Boolean = false
var redactAuthHeader: Boolean = true
private const val LIMIT_BODY_LOG: Long = 1000000
private const val BINARY_OMITTED = "<-- Body end for response -- Binary -- Omitted:"
private const val BYTES = "bytes -->"
}
}
@@ -0,0 +1,17 @@
package eu.qsfera.android.lib.common.http.logging
data class LogRequest(
val request: Request
)
data class Request(
val body: String?,
val headers: Map<String, String>,
val info: RequestInfo,
)
data class RequestInfo(
val id: String,
val method: String,
val url: String,
)
@@ -0,0 +1,33 @@
package eu.qsfera.android.lib.common.http.logging
data class LogResponse(
val response: Response
)
data class Response(
val body: Body?,
val headers: Map<String, String>,
val info: ResponseInfo,
)
data class ResponseInfo(
val id: String,
val method: String,
val reply: Reply,
val url: String,
)
data class Reply(
val cached: Boolean,
val duration: Long,
val durationString: String,
val status: Int,
val version: String,
)
data class Body(
val data: String?,
val length: Int,
)
const val DURATION_FORMAT = "duration(%dh, %dmin, %ds, %dms)"
@@ -0,0 +1,183 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2022 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 eu.qsfera.android.lib.common.http.methods
import eu.qsfera.android.lib.common.http.HttpClient
import okhttp3.Call
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.InputStream
import java.net.MalformedURLException
import java.net.URL
import java.util.concurrent.TimeUnit
abstract class HttpBaseMethod constructor(url: URL) {
var httpUrl: HttpUrl = url.toHttpUrlOrNull() ?: throw MalformedURLException()
var request: Request
var followPermanentRedirects = false
abstract var response: Response
var call: Call? = null
var followRedirects: Boolean = true
var retryOnConnectionFailure: Boolean = true
var connectionTimeoutVal: Long? = null
var connectionTimeoutUnit: TimeUnit? = null
var readTimeoutVal: Long? = null
private set
var readTimeoutUnit: TimeUnit? = null
private set
val statusCode: Int
get() = response.code
val statusMessage: String
get() = response.message
open val isAborted: Boolean
get() = call?.isCanceled() ?: false
init {
request = Request.Builder()
.url(httpUrl)
.build()
}
@Throws(Exception::class)
open fun execute(httpClient: HttpClient): Int {
val okHttpClient = httpClient.okHttpClient.newBuilder().apply {
retryOnConnectionFailure(retryOnConnectionFailure)
followRedirects(followRedirects)
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) {
request = request.newBuilder()
.url(url)
.build()
}
/****************
*** Requests ***
****************/
fun getRequestHeader(name: String): String? =
request.header(name)
fun getRequestHeadersAsHashMap(): HashMap<String, String?> {
val headers: HashMap<String, String?> = HashMap()
val superHeaders: Set<String> = request.headers.names()
superHeaders.forEach {
headers[it] = getRequestHeader(it)
}
return headers
}
open fun addRequestHeader(name: String, value: String) {
request = request.newBuilder()
.addHeader(name, value)
.build()
}
/**
* Sets a header and replace it if already exists with that name
*
* @param name header name
* @param value header value
*/
open fun setRequestHeader(name: String, value: String) {
request = request.newBuilder()
.header(name, value)
.build()
}
/****************
*** Response ***
****************/
// Headers
open fun getResponseHeaders(): Headers? =
response.headers
open fun getResponseHeader(headerName: String): String? =
response.header(headerName)
// Body
fun getResponseBodyAsString(): String = response.peekBody(Long.MAX_VALUE).string()
open fun getResponseBodyAsStream(): InputStream? =
response.body?.byteStream()
/**
* returns the final url after following the last redirect.
*/
open fun getFinalUrl() = response.request.url
/*************************
*** Connection Params ***
*************************/
//////////////////////////////
// Setter
//////////////////////////////
// Connection parameters
open fun setReadTimeout(readTimeout: Long, timeUnit: TimeUnit) {
readTimeoutVal = readTimeout
readTimeoutUnit = timeUnit
}
open fun setConnectionTimeout(
connectionTimeout: Long,
timeUnit: TimeUnit
) {
connectionTimeoutVal = connectionTimeout
connectionTimeoutUnit = timeUnit
}
/************
*** Call ***
************/
open fun abort() {
call?.cancel()
}
//////////////////////////////
// For override
//////////////////////////////
@Throws(Exception::class)
protected abstract fun onExecute(okHttpClient: OkHttpClient): Int
}
@@ -0,0 +1,43 @@
/* qsfera 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 eu.qsfera.android.lib.common.http.methods.nonwebdav
import okhttp3.OkHttpClient
import java.io.IOException
import java.net.URL
/**
* OkHttp delete calls wrapper
*
* @author David González Verdugo
*/
class DeleteMethod(url: URL) : HttpMethod(url) {
@Throws(IOException::class)
override fun onExecute(okHttpClient: OkHttpClient): Int {
request = request.newBuilder()
.delete()
.build()
return super.onExecute(okHttpClient)
}
}
@@ -0,0 +1,43 @@
/* qsfera 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 eu.qsfera.android.lib.common.http.methods.nonwebdav
import okhttp3.OkHttpClient
import java.io.IOException
import java.net.URL
/**
* OkHttp get calls wrapper
*
* @author David González Verdugo
*/
class GetMethod(url: URL) : HttpMethod(url) {
@Throws(IOException::class)
override fun onExecute(okHttpClient: OkHttpClient): Int {
request = request.newBuilder()
.get()
.build()
return super.onExecute(okHttpClient)
}
}
@@ -0,0 +1,18 @@
package eu.qsfera.android.lib.common.http.methods.nonwebdav
import okhttp3.OkHttpClient
import java.io.IOException
import java.net.URL
/**
* OkHttp HEAD calls wrapper
*/
class HeadMethod(url: URL) : HttpMethod(url) {
@Throws(IOException::class)
override fun onExecute(okHttpClient: OkHttpClient): Int {
request = request.newBuilder()
.head()
.build()
return super.onExecute(okHttpClient)
}
}
@@ -0,0 +1,47 @@
/* qsfera 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 eu.qsfera.android.lib.common.http.methods.nonwebdav
import eu.qsfera.android.lib.common.http.methods.HttpBaseMethod
import okhttp3.OkHttpClient
import okhttp3.Response
import java.net.URL
/**
* Wrapper to perform OkHttp calls
*
* @author David González Verdugo
*/
abstract class HttpMethod(
url: URL
) : HttpBaseMethod(url) {
override lateinit var response: Response
public override fun onExecute(okHttpClient: OkHttpClient): Int {
call = okHttpClient.newCall(request)
call?.let { response = it.execute() }
return super.statusCode
}
}
@@ -0,0 +1,18 @@
package eu.qsfera.android.lib.common.http.methods.nonwebdav
import okhttp3.OkHttpClient
import java.io.IOException
import java.net.URL
/**
* OkHttp OPTIONS calls wrapper
*/
class OptionsMethod(url: URL) : HttpMethod(url) {
@Throws(IOException::class)
override fun onExecute(okHttpClient: OkHttpClient): Int {
request = request.newBuilder()
.method("OPTIONS", null)
.build()
return super.onExecute(okHttpClient)
}
}
@@ -0,0 +1,22 @@
package eu.qsfera.android.lib.common.http.methods.nonwebdav
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import java.io.IOException
import java.net.URL
/**
* OkHttp PATCH calls wrapper
*/
class PatchMethod(
url: URL,
private val patchRequestBody: RequestBody
) : HttpMethod(url) {
@Throws(IOException::class)
override fun onExecute(okHttpClient: OkHttpClient): Int {
request = request.newBuilder()
.patch(patchRequestBody)
.build()
return super.onExecute(okHttpClient)
}
}
@@ -0,0 +1,47 @@
/* qsfera 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 eu.qsfera.android.lib.common.http.methods.nonwebdav
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import java.io.IOException
import java.net.URL
/**
* OkHttp post calls wrapper
*
* @author David González Verdugo
*/
class PostMethod(
url: URL,
private val postRequestBody: RequestBody
) : HttpMethod(url) {
@Throws(IOException::class)
override fun onExecute(okHttpClient: OkHttpClient): Int {
request = request.newBuilder()
.post(postRequestBody)
.build()
return super.onExecute(okHttpClient)
}
}
@@ -0,0 +1,47 @@
/* qsfera 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 eu.qsfera.android.lib.common.http.methods.nonwebdav
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import java.io.IOException
import java.net.URL
/**
* OkHttp put calls wrapper
*
* @author David González Verdugo
*/
class PutMethod(
url: URL,
private val putRequestBody: RequestBody
) : HttpMethod(url) {
@Throws(IOException::class)
override fun onExecute(okHttpClient: OkHttpClient): Int {
request = request.newBuilder()
.put(putRequestBody)
.build()
return super.onExecute(okHttpClient)
}
}
@@ -0,0 +1,52 @@
/* qsfera 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 eu.qsfera.android.lib.common.http.methods.webdav
import at.bitfire.dav4jvm.DavOCResource
import okhttp3.Response
import java.net.URL
/**
* Copy calls wrapper
*
* @author Christian Schabesberger
* @author David González Verdugo
*/
class CopyMethod(
val url: URL,
private val destinationUrl: String,
val forceOverride: Boolean = false
) : DavMethod(url) {
@Throws(Exception::class)
public override fun onDavExecute(davResource: DavOCResource): Int {
davResource.copy(
destinationUrl,
forceOverride,
super.getRequestHeadersAsHashMap()
) { callBackResponse: Response ->
response = callBackResponse
}
return super.statusCode
}
}
@@ -0,0 +1,32 @@
/* qsfera 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 eu.qsfera.android.lib.common.http.methods.webdav
/**
* @author David González Verdugo
*/
object DavConstants {
const val DEPTH_0 = 0
const val DEPTH_1 = 1
}
@@ -0,0 +1,93 @@
/* qsfera 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 eu.qsfera.android.lib.common.http.methods.webdav
import at.bitfire.dav4jvm.Dav4jvm.log
import at.bitfire.dav4jvm.DavOCResource
import at.bitfire.dav4jvm.exception.HttpException
import at.bitfire.dav4jvm.exception.RedirectException
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.HttpBaseMethod
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import java.net.URL
/**
* Wrapper to perform WebDAV (dav4android) calls
*
* @author David González Verdugo
*/
abstract class DavMethod protected constructor(url: URL) : HttpBaseMethod(url) {
override lateinit var response: Response
private var davResource: DavOCResource? = null
//////////////////////////////
// Getter
//////////////////////////////
override val isAborted: Boolean
get() = davResource?.isCallAborted() ?: false
override fun abort() {
davResource?.cancelCall()
}
protected abstract fun onDavExecute(davResource: DavOCResource): Int
@Throws(Exception::class)
override fun onExecute(okHttpClient: OkHttpClient): Int =
try {
davResource = DavOCResource(
okHttpClient.newBuilder().followRedirects(false).build(),
httpUrl,
log
)
onDavExecute(davResource!!)
} catch (httpException: RedirectException) {
// Modify responses with information gathered from exceptions
response = Response.Builder()
.header(
HttpConstants.LOCATION_HEADER, httpException.redirectLocation
)
.code(httpException.code)
.request(request)
.message(httpException.message ?: "")
.protocol(Protocol.HTTP_1_1)
.build()
httpException.code
} catch (httpException: HttpException) {
// The check below should be included in okhttp library, method ResponseBody.create(
// TODO check most recent versions of okhttp to see if this is already fixed and try to update if so
if (response.body?.contentType() != null) {
val responseBody = (httpException.responseBody ?: "").toResponseBody(response.body?.contentType())
response = response.newBuilder()
.body(responseBody)
.build()
}
httpException.code
}
}
@@ -0,0 +1,60 @@
/* qsfera 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 eu.qsfera.android.lib.common.http.methods.webdav
import at.bitfire.dav4jvm.Property
import at.bitfire.dav4jvm.PropertyUtils.getQuotaPropset
import at.bitfire.dav4jvm.property.CreationDate
import at.bitfire.dav4jvm.property.DisplayName
import at.bitfire.dav4jvm.property.GetContentLength
import at.bitfire.dav4jvm.property.GetContentType
import at.bitfire.dav4jvm.property.GetETag
import at.bitfire.dav4jvm.property.GetLastModified
import at.bitfire.dav4jvm.property.OCId
import at.bitfire.dav4jvm.property.OCPermissions
import at.bitfire.dav4jvm.property.OCPrivatelink
import at.bitfire.dav4jvm.property.OCSize
import at.bitfire.dav4jvm.property.ResourceType
import eu.qsfera.android.lib.common.http.methods.webdav.properties.OCShareTypes
object DavUtils {
@JvmStatic val allPropSet: Array<Property.Name>
get() = arrayOf(
DisplayName.NAME,
GetContentType.NAME,
ResourceType.NAME,
GetContentLength.NAME,
GetLastModified.NAME,
CreationDate.NAME,
GetETag.NAME,
OCPermissions.NAME,
OCId.NAME,
OCSize.NAME,
OCPrivatelink.NAME,
OCShareTypes.NAME,
)
val quotaPropSet: Array<Property.Name>
get() = getQuotaPropset()
}
@@ -0,0 +1,47 @@
/* qsfera 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 eu.qsfera.android.lib.common.http.methods.webdav
import at.bitfire.dav4jvm.DavOCResource
import okhttp3.Response
import java.net.URL
/**
* MkCol calls wrapper
*
* @author Christian Schabesberger
* @author David González Verdugo
*/
class MkColMethod(url: URL) : DavMethod(url) {
@Throws(Exception::class)
public override fun onDavExecute(davResource: DavOCResource): Int {
davResource.mkCol(
xmlBody = null,
listOfHeaders = super.getRequestHeadersAsHashMap()
) { callBackResponse: Response ->
response = callBackResponse
}
return super.statusCode
}
}
@@ -0,0 +1,53 @@
/* qsfera 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 eu.qsfera.android.lib.common.http.methods.webdav
import at.bitfire.dav4jvm.DavOCResource
import okhttp3.Response
import java.net.URL
/**
* Move calls wrapper
*
* @author Christian Schabesberger
* @author David González Verdugo
*/
class MoveMethod(
url: URL,
private val destinationUrl: String,
val forceOverride: Boolean = false
) : DavMethod(url) {
@Throws(Exception::class)
override fun onDavExecute(davResource: DavOCResource): Int {
davResource.move(
destinationUrl,
forceOverride,
super.getRequestHeadersAsHashMap()
) { callBackResponse: Response ->
response = callBackResponse
}
return super.statusCode
}
}
@@ -0,0 +1,73 @@
/* qsfera 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 eu.qsfera.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
import at.bitfire.dav4jvm.exception.DavException
import java.io.IOException
import java.net.URL
/**
* Propfind calls wrapper
*
* @author David González Verdugo
*/
class PropfindMethod(
url: URL,
private val depth: Int,
private val propertiesToRequest: Array<Property.Name>
) : DavMethod(url) {
// response
val members: MutableList<Response>
var root: Response?
private set
init {
members = arrayListOf()
this.root = null
}
@Throws(IOException::class, DavException::class)
public override fun onDavExecute(davResource: DavOCResource): Int {
davResource.propfind(
depth = depth,
reqProp = propertiesToRequest,
listOfHeaders = super.getRequestHeadersAsHashMap(),
callback = { response: Response, hrefRelation: HrefRelation ->
when (hrefRelation) {
HrefRelation.MEMBER -> members.add(response)
HrefRelation.SELF -> this.root = response
HrefRelation.OTHER -> {
}
}
}, rawCallback = { callBackResponse: okhttp3.Response ->
response = callBackResponse
})
return statusCode
}
}
@@ -0,0 +1,53 @@
/* qsfera 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 eu.qsfera.android.lib.common.http.methods.webdav
import at.bitfire.dav4jvm.DavOCResource
import at.bitfire.dav4jvm.exception.HttpException
import eu.qsfera.android.lib.common.http.HttpConstants
import okhttp3.RequestBody
import java.io.IOException
import java.net.URL
/**
* Put calls wrapper
*
* @author David González Verdugo
*/
class PutMethod(
url: URL,
private val putRequestBody: RequestBody
) : DavMethod(url) {
@Throws(IOException::class, HttpException::class)
public override fun onDavExecute(davResource: DavOCResource): Int {
davResource.put(
putRequestBody,
super.getRequestHeader(HttpConstants.IF_MATCH_HEADER),
getRequestHeadersAsHashMap()
) { callBackResponse ->
response = callBackResponse
}
return super.statusCode
}
}
@@ -0,0 +1,47 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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 eu.qsfera.android.lib.common.http.methods.webdav.properties
import at.bitfire.dav4jvm.Property
import at.bitfire.dav4jvm.PropertyFactory
import at.bitfire.dav4jvm.XmlUtils
import org.xmlpull.v1.XmlPullParser
data class OCFileId(val fileId: String) : Property {
class Factory : PropertyFactory {
override fun getName() = NAME
override fun create(parser: XmlPullParser): OCFileId? {
XmlUtils.readText(parser)?.let {
return OCFileId(it)
}
return null
}
}
companion object {
@JvmField
val NAME = Property.Name(XmlUtils.NS_OWNCLOUD, "fileid")
}
}
@@ -0,0 +1,47 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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 eu.qsfera.android.lib.common.http.methods.webdav.properties
import at.bitfire.dav4jvm.Property
import at.bitfire.dav4jvm.PropertyFactory
import at.bitfire.dav4jvm.XmlUtils
import org.xmlpull.v1.XmlPullParser
data class OCMetaPathForUser(val path: String) : Property {
class Factory : PropertyFactory {
override fun getName() = NAME
override fun create(parser: XmlPullParser): OCMetaPathForUser? {
XmlUtils.readText(parser)?.let {
return OCMetaPathForUser(it)
}
return null
}
}
companion object {
@JvmField
val NAME = Property.Name(XmlUtils.NS_OWNCLOUD, "meta-path-for-user")
}
}
@@ -0,0 +1,44 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2022 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 eu.qsfera.android.lib.common.http.methods.webdav.properties
import at.bitfire.dav4jvm.Property
import at.bitfire.dav4jvm.XmlUtils
import org.xmlpull.v1.XmlPullParser
class OCShareTypes : ShareTypeListProperty() {
class Factory : ShareTypeListProperty.Factory() {
override fun create(parser: XmlPullParser) =
create(parser, OCShareTypes())
override fun getName(): Property.Name = NAME
}
companion object {
@JvmField
val NAME = Property.Name(XmlUtils.NS_OWNCLOUD, "share-types")
}
}
@@ -0,0 +1,47 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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 eu.qsfera.android.lib.common.http.methods.webdav.properties
import at.bitfire.dav4jvm.Property
import at.bitfire.dav4jvm.PropertyFactory
import at.bitfire.dav4jvm.XmlUtils
import org.xmlpull.v1.XmlPullParser
data class OCSpaceId(val spaceId: String) : Property {
class Factory : PropertyFactory {
override fun getName() = NAME
override fun create(parser: XmlPullParser): OCSpaceId? {
XmlUtils.readText(parser)?.let {
return OCSpaceId(it)
}
return null
}
}
companion object {
@JvmField
val NAME = Property.Name(XmlUtils.NS_OWNCLOUD, "spaceid")
}
}
@@ -0,0 +1,46 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2022 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 eu.qsfera.android.lib.common.http.methods.webdav.properties
import at.bitfire.dav4jvm.Property
import at.bitfire.dav4jvm.PropertyFactory
import at.bitfire.dav4jvm.XmlUtils
import org.xmlpull.v1.XmlPullParser
import java.util.LinkedList
abstract class ShareTypeListProperty : Property {
val shareTypes = LinkedList<String>()
override fun toString() = "share types =[" + shareTypes.joinToString(", ") + "]"
abstract class Factory : PropertyFactory {
fun create(parser: XmlPullParser, list: ShareTypeListProperty): ShareTypeListProperty {
XmlUtils.readTextPropertyList(parser, Property.Name(XmlUtils.NS_OWNCLOUD, "share-type"), list.shareTypes)
return list
}
}
}
@@ -0,0 +1,147 @@
/* qsfera 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 eu.qsfera.android.lib.common.network;
import timber.log.Timber;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
/**
* @author David A. Velasco
*/
public class AdvancedX509TrustManager implements X509TrustManager {
private X509TrustManager mStandardTrustManager;
private KeyStore mKnownServersKeyStore;
/**
* Constructor for AdvancedX509TrustManager
*
* @param knownServersKeyStore Local certificates store with server certificates explicitly trusted by the user.
*/
public AdvancedX509TrustManager(KeyStore knownServersKeyStore) throws NoSuchAlgorithmException, KeyStoreException {
super();
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init((KeyStore) null);
mStandardTrustManager = findX509TrustManager(factory);
mKnownServersKeyStore = knownServersKeyStore;
}
/**
* Locates the first X509TrustManager provided by a given TrustManagerFactory
*
* @param factory TrustManagerFactory to inspect in the search for a X509TrustManager
* @return The first X509TrustManager found in factory.
*/
private X509TrustManager findX509TrustManager(TrustManagerFactory factory) {
TrustManager[] tms = factory.getTrustManagers();
for (TrustManager tm : tms) {
if (tm instanceof X509TrustManager) {
return (X509TrustManager) tm;
}
}
return null;
}
/**
* @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],
* String authType)
*/
public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
mStandardTrustManager.checkClientTrusted(certificates, authType);
}
public static final ThreadLocal<X509Certificate> sLastCert = new ThreadLocal<>();
/**
* @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],
* String authType)
*/
public void checkServerTrusted(X509Certificate[] certificates, String authType) {
if (certificates != null && certificates.length > 0) {
sLastCert.set(certificates[0]);
}
if (!isKnownServer(certificates[0])) {
CertificateCombinedException result = new CertificateCombinedException(certificates[0]);
try {
certificates[0].checkValidity();
} catch (CertificateExpiredException c) {
result.setCertificateExpiredException(c);
} catch (CertificateNotYetValidException c) {
result.setCertificateNotYetException(c);
}
try {
mStandardTrustManager.checkServerTrusted(certificates, authType);
} catch (CertificateException c) {
Throwable cause = c.getCause();
Throwable previousCause = null;
while (cause != null && cause != previousCause && !(cause instanceof CertPathValidatorException)) { // getCause() is not funny
previousCause = cause;
cause = cause.getCause();
}
if (cause instanceof CertPathValidatorException) {
result.setCertPathValidatorException((CertPathValidatorException) cause);
} else {
result.setOtherCertificateException(c);
}
}
if (result.isException()) {
throw result;
}
}
}
/**
* @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
*/
public X509Certificate[] getAcceptedIssuers() {
return mStandardTrustManager.getAcceptedIssuers();
}
public boolean isKnownServer(X509Certificate cert) {
try {
return (mKnownServersKeyStore.getCertificateAlias(cert) != null);
} catch (KeyStoreException e) {
Timber.e(e, "Fail while checking certificate in the known-servers store");
return false;
}
}
}
@@ -0,0 +1,138 @@
/* qsfera 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 eu.qsfera.android.lib.common.network;
import javax.net.ssl.SSLPeerUnverifiedException;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
/**
* Exception joining all the problems that {@link AdvancedX509TrustManager} can find in
* a certificate chain for a server.
* <p>
* This was initially created as an extension of CertificateException, but some
* implementations of the SSL socket layer in existing devices are REPLACING the CertificateException
* instances thrown by {@link javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[], String)}
* with SSLPeerUnverifiedException FORGETTING THE CAUSING EXCEPTION instead of wrapping it.
* <p>
* Due to this, extending RuntimeException is necessary to get that the CertificateCombinedException
* instance reaches {@link AdvancedSslSocketFactory#verifyPeerIdentity}.
* <p>
* BE CAREFUL. As a RuntimeException extensions, Java compilers do not require to handle it
* in client methods. Be sure to use it only when you know exactly where it will go.
*
* @author David A. Velasco
*/
public class CertificateCombinedException extends RuntimeException {
/**
* Generated - to refresh every time the class changes
*/
private static final long serialVersionUID = -8875782030758554999L;
private X509Certificate mServerCert = null;
private String mHostInUrl;
private CertificateExpiredException mCertificateExpiredException = null;
private CertificateNotYetValidException mCertificateNotYetValidException = null;
private CertPathValidatorException mCertPathValidatorException = null;
private CertificateException mOtherCertificateException = null;
private SSLPeerUnverifiedException mSslPeerUnverifiedException = null;
public CertificateCombinedException(X509Certificate x509Certificate) {
mServerCert = x509Certificate;
}
public X509Certificate getServerCertificate() {
return mServerCert;
}
public String getHostInUrl() {
return mHostInUrl;
}
public void setHostInUrl(String host) {
mHostInUrl = host;
}
public CertificateExpiredException getCertificateExpiredException() {
return mCertificateExpiredException;
}
public void setCertificateExpiredException(CertificateExpiredException c) {
mCertificateExpiredException = c;
}
public CertificateNotYetValidException getCertificateNotYetValidException() {
return mCertificateNotYetValidException;
}
public void setCertificateNotYetException(CertificateNotYetValidException c) {
mCertificateNotYetValidException = c;
}
public CertPathValidatorException getCertPathValidatorException() {
return mCertPathValidatorException;
}
public void setCertPathValidatorException(CertPathValidatorException c) {
mCertPathValidatorException = c;
}
public CertificateException getOtherCertificateException() {
return mOtherCertificateException;
}
public void setOtherCertificateException(CertificateException c) {
mOtherCertificateException = c;
}
public SSLPeerUnverifiedException getSslPeerUnverifiedException() {
return mSslPeerUnverifiedException;
}
public void setSslPeerUnverifiedException(SSLPeerUnverifiedException s) {
mSslPeerUnverifiedException = s;
}
public boolean isException() {
return (mCertificateExpiredException != null ||
mCertificateNotYetValidException != null ||
mCertPathValidatorException != null ||
mOtherCertificateException != null ||
mSslPeerUnverifiedException != null);
}
public boolean isRecoverable() {
return (mCertificateExpiredException != null ||
mCertificateNotYetValidException != null ||
mCertPathValidatorException != null ||
mSslPeerUnverifiedException != null);
}
}
@@ -0,0 +1,99 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2022 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 eu.qsfera.android.lib.common.network
import eu.qsfera.android.lib.resources.files.chunks.ChunkedUploadFromFileSystemOperation.Companion.CHUNK_SIZE
import okhttp3.MediaType
import okio.BufferedSink
import timber.log.Timber
import java.io.File
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
/**
* A Request body that represents a file chunk and include information about the progress when uploading it
*
* @author David González Verdugo
*/
class ChunkFromFileRequestBody(
file: File,
contentType: MediaType?,
private val channel: FileChannel,
private val chunkSize: Long = CHUNK_SIZE
) : FileRequestBody(file, contentType) {
private var offset: Long = 0
private var alreadyTransferred: Long = 0
private val buffer = ByteBuffer.allocate(4_096)
init {
require(chunkSize > 0) { "Chunk size must be greater than zero" }
}
override fun contentLength(): Long =
chunkSize.coerceAtMost((channel.size() - offset).coerceAtLeast(0))
override fun writeTo(sink: BufferedSink) {
var readCount: Int
var iterator: Iterator<OnDatatransferProgressListener>
try {
channel.position(offset)
val maxCount = (offset + chunkSize).coerceAtMost(channel.size())
while (channel.position() < maxCount) {
val remainingForChunk = (maxCount - channel.position()).toInt()
if (remainingForChunk <= 0) break
// limit how much we read so we never consume past the chunk boundary
val toRead = minOf(buffer.capacity(), remainingForChunk)
buffer.limit(toRead)
readCount = channel.read(buffer)
if (readCount == -1) break
sink.buffer.write(buffer.array(), 0, readCount)
sink.flush()
buffer.clear()
if (readCount > 0) {
alreadyTransferred = (alreadyTransferred + readCount.toLong()).coerceAtMost(chunkSize)
}
val totalTransferred = offset + alreadyTransferred
synchronized(dataTransferListeners) {
iterator = dataTransferListeners.iterator()
while (iterator.hasNext()) {
iterator.next().onTransferProgress(readCount.toLong(), totalTransferred, file.length(), file.absolutePath)
}
}
}
} catch (exception: Exception) {
Timber.e(exception, "Transferred " + alreadyTransferred + " bytes from a total of " + file.length())
}
}
fun setOffset(newOffset: Long) {
offset = newOffset
alreadyTransferred = 0
}
}
@@ -0,0 +1,116 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2022 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 eu.qsfera.android.lib.common.network
import android.content.ContentResolver
import android.net.Uri
import android.provider.OpenableColumns
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okio.BufferedSink
import okio.Source
import okio.source
import timber.log.Timber
import java.io.IOException
class ContentUriRequestBody(
private val contentResolver: ContentResolver,
private val contentUri: Uri
) : RequestBody(), ProgressiveDataTransferer {
private val dataTransferListeners: MutableSet<OnDatatransferProgressListener> = HashSet()
val fileSize: Long = contentResolver.query(contentUri, null, null, null, null)?.use { cursor ->
val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
cursor.moveToFirst()
cursor.getLong(sizeIndex)
} ?: -1
override fun contentType(): MediaType? {
val contentType = contentResolver.getType(contentUri) ?: return null
return contentType.toMediaTypeOrNull()
}
override fun contentLength(): Long =
fileSize
override fun writeTo(sink: BufferedSink) {
val inputStream = contentResolver.openInputStream(contentUri)
?: throw IOException("Couldn't open content URI for reading: $contentUri")
val previousTime = System.currentTimeMillis()
sink.writeAndUpdateProgress(inputStream.source())
inputStream.source().close()
val laterTime = System.currentTimeMillis()
Timber.d("Difference - ${laterTime - previousTime} milliseconds")
}
private fun BufferedSink.writeAndUpdateProgress(source: Source) {
var iterator: Iterator<OnDatatransferProgressListener>
try {
var totalBytesRead = 0L
var read: Long
while (source.read(this.buffer, BYTES_TO_READ).also { read = it } != -1L) {
totalBytesRead += read
this.flush()
synchronized(dataTransferListeners) {
iterator = dataTransferListeners.iterator()
while (iterator.hasNext()) {
iterator.next().onTransferProgress(read, totalBytesRead, fileSize, contentUri.toString())
}
}
}
} catch (e: Exception) {
Timber.e(e)
}
}
override fun addDatatransferProgressListener(listener: OnDatatransferProgressListener) {
synchronized(dataTransferListeners) {
dataTransferListeners.add(listener)
}
}
override fun addDatatransferProgressListeners(listeners: MutableCollection<OnDatatransferProgressListener>) {
synchronized(dataTransferListeners) {
dataTransferListeners.addAll(listeners)
}
}
override fun removeDatatransferProgressListener(listener: OnDatatransferProgressListener) {
synchronized(dataTransferListeners) {
dataTransferListeners.remove(listener)
}
}
companion object {
private const val BYTES_TO_READ = 4_096L
}
}
@@ -0,0 +1,95 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2022 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 eu.qsfera.android.lib.common.network
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.BufferedSink
import okio.Source
import okio.source
import timber.log.Timber
import java.io.File
import java.util.HashSet
/**
* A Request body that represents a file and include information about the progress when uploading it
*
* @author David González Verdugo
*/
open class FileRequestBody(
val file: File,
private val contentType: MediaType?,
) : RequestBody(), ProgressiveDataTransferer {
val dataTransferListeners: MutableSet<OnDatatransferProgressListener> = HashSet()
override fun isOneShot(): Boolean = true
override fun contentType(): MediaType? = contentType
override fun contentLength(): Long = file.length()
override fun writeTo(sink: BufferedSink) {
// Don't swallow IO errors here — a missing source file used to silently produce
// a 0-byte PUT that the server happily stored (issue #78).
val source: Source = file.source()
var transferred: Long = 0
var read: Long
source.use { src ->
while (src.read(sink.buffer, BYTES_TO_READ).also { read = it } != -1L) {
transferred += read
sink.flush()
synchronized(dataTransferListeners) {
val it = dataTransferListeners.iterator()
while (it.hasNext()) {
it.next().onTransferProgress(read, transferred, file.length(), file.absolutePath)
}
}
}
}
Timber.d("File with name ${file.name} and size ${file.length()} written in request body")
}
override fun addDatatransferProgressListener(listener: OnDatatransferProgressListener) {
synchronized(dataTransferListeners) {
dataTransferListeners.add(listener)
}
}
override fun addDatatransferProgressListeners(listeners: Collection<OnDatatransferProgressListener>) {
synchronized(dataTransferListeners) {
dataTransferListeners.addAll(listeners)
}
}
override fun removeDatatransferProgressListener(listener: OnDatatransferProgressListener) {
synchronized(dataTransferListeners) {
dataTransferListeners.remove(listener)
}
}
companion object {
private const val BYTES_TO_READ = 4_096L
}
}
@@ -0,0 +1,79 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2026 qsfera Contributors.
*
* 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 eu.qsfera.android.lib.common.network;
import android.content.Context;
import okhttp3.internal.tls.OkHostnameVerifier;
import timber.log.Timber;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
/**
* HostnameVerifier with a fallback for self-signed servers explicitly trusted by the user.
* <p>
* The RFC 2818/6125 check from {@link OkHostnameVerifier} is applied first. If it fails, the peer
* certificate is compared against the user-managed known-servers store. A match means the user
* already opted in to trust exactly this certificate (typically after accepting the untrusted-cert
* dialog), so the hostname mismatch is tolerated — this covers local self-hosted setups where the
* URL uses a LAN hostname that is not part of the server certificate's SAN.
*/
public class KnownServersHostnameVerifier implements HostnameVerifier {
private final Context mContext;
private final HostnameVerifier mDelegate;
public KnownServersHostnameVerifier(Context context) {
this(context, OkHostnameVerifier.INSTANCE);
}
KnownServersHostnameVerifier(Context context, HostnameVerifier delegate) {
if (context == null) {
throw new IllegalArgumentException("Context may not be NULL!");
}
mContext = context.getApplicationContext() != null ? context.getApplicationContext() : context;
mDelegate = delegate;
}
@Override
public boolean verify(String hostname, SSLSession session) {
if (mDelegate.verify(hostname, session)) {
return true;
}
try {
Certificate[] peerCerts = session.getPeerCertificates();
if (peerCerts.length > 0 && peerCerts[0] instanceof X509Certificate) {
return NetworkUtils.isCertInKnownServersStore(peerCerts[0], mContext);
}
} catch (SSLPeerUnverifiedException e) {
Timber.d(e, "No peer certificates during hostname verification for %s", hostname);
}
return false;
}
}
@@ -0,0 +1,109 @@
/* qsfera 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 eu.qsfera.android.lib.common.network;
import android.content.Context;
import timber.log.Timber;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
public class NetworkUtils {
private static String LOCAL_TRUSTSTORE_FILENAME = "knownServers.bks";
private static String LOCAL_TRUSTSTORE_PASSWORD = "password";
private static KeyStore mKnownServersStore = null;
/**
* Returns the local store of reliable server certificates, explicitly accepted by the user.
* <p>
* Returns a KeyStore instance with empty content if the local store was never created.
* <p>
* Loads the store from the storage environment if needed.
*
* @param context Android context where the operation is being performed.
* @return KeyStore instance with explicitly-accepted server certificates.
* @throws KeyStoreException When the KeyStore instance could not be created.
* @throws IOException When an existing local trust store could not be loaded.
* @throws NoSuchAlgorithmException When the existing local trust store was saved with an unsupported algorithm.
* @throws CertificateException When an exception occurred while loading the certificates from the local
* trust store.
*/
public static KeyStore getKnownServersStore(Context context)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
if (mKnownServersStore == null) {
//mKnownServersStore = KeyStore.getInstance("BKS");
mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType());
File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME);
Timber.d("Searching known-servers store at %s", localTrustStoreFile.getAbsolutePath());
if (localTrustStoreFile.exists()) {
InputStream in = new FileInputStream(localTrustStoreFile);
try {
mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
} finally {
in.close();
}
} else {
// next is necessary to initialize an empty KeyStore instance
mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
}
}
return mKnownServersStore;
}
public static void addCertToKnownServersStore(Certificate cert, Context context)
throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
KeyStore knownServers = getKnownServersStore(context);
knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert);
try (FileOutputStream fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE)) {
knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
}
}
public static boolean isCertInKnownServersStore(Certificate cert, Context context) {
if (cert == null || context == null) {
return false;
}
try {
return getKnownServersStore(context).getCertificateAlias(cert) != null;
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
Timber.e(e, "Fail while checking certificate in the known-servers store");
return false;
}
}
}
@@ -0,0 +1,30 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2016 ownCloud GmbH.
* Copyright (C) 2012 Bartek Przybylski
*
* 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 eu.qsfera.android.lib.common.network;
public interface OnDatatransferProgressListener {
void onTransferProgress(long read, long transferred, long percent, String absolutePath);
}
@@ -0,0 +1,37 @@
/* qsfera 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 eu.qsfera.android.lib.common.network;
import java.util.Collection;
public interface ProgressiveDataTransferer {
void addDatatransferProgressListener(OnDatatransferProgressListener listener);
void addDatatransferProgressListeners(Collection<OnDatatransferProgressListener> listeners);
void removeDatatransferProgressListener(OnDatatransferProgressListener listener);
}
@@ -0,0 +1,123 @@
/* qsfera Android Library is available under MIT license
*
* @author David A. Velasco
*
* 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 eu.qsfera.android.lib.common.network;
import eu.qsfera.android.lib.common.http.HttpConstants;
import java.util.Arrays;
/**
* Aggregate saving the list of URLs followed in a sequence of redirections during the exceution of a
* {@link RemoteOperation}, and the status codes corresponding to all
* of them.
* <p>
* The last status code saved corresponds to the first response not being a redirection, unless the sequence exceeds
* the maximum length of redirections allowed by the {@link eu.qsfera.android.lib.common.QSferaClient} instance
* that ran the operation.
* <p>
* If no redirection was followed, the last (and first) status code contained corresponds to the original URL in the
* request.
*/
public class RedirectionPath {
private int[] mStatuses = null;
private int mLastStatus = -1;
private String[] mLocations = null;
private int mLastLocation = -1;
/**
* Public constructor.
*
* @param status Status code resulting of executing a request on the original URL.
* @param maxRedirections Maximum number of redirections that will be contained.
* @throws IllegalArgumentException If 'maxRedirections' is < 0
*/
public RedirectionPath(int status, int maxRedirections) {
if (maxRedirections < 0) {
throw new IllegalArgumentException("maxRedirections MUST BE zero or greater");
}
mStatuses = new int[maxRedirections + 1];
Arrays.fill(mStatuses, -1);
mStatuses[++mLastStatus] = status;
}
/**
* Adds a new location URL to the list of followed redirections.
*
* @param location URL extracted from a 'Location' header in a redirection.
*/
public void addLocation(String location) {
if (mLocations == null) {
mLocations = new String[mStatuses.length - 1];
}
if (mLastLocation < mLocations.length - 1) {
mLocations[++mLastLocation] = location;
}
}
/**
* Adds a new status code to the list of status corresponding to followed redirections.
*
* @param status Status code from the response of another followed redirection.
*/
public void addStatus(int status) {
if (mLastStatus < mStatuses.length - 1) {
mStatuses[++mLastStatus] = status;
}
}
/**
* @return Last status code saved.
*/
public int getLastStatus() {
return mStatuses[mLastStatus];
}
/**
* @return Last location followed corresponding to a permanent redirection (status code 301).
*/
public String getLastPermanentLocation() {
for (int i = mLastStatus; i >= 0; i--) {
if (mStatuses[i] == HttpConstants.HTTP_MOVED_PERMANENTLY && i <= mLastLocation) {
return mLocations[i];
}
}
return null;
}
/**
* @return Count of locations.
*/
public int getRedirectionsCount() {
return mLastLocation + 1;
}
}
@@ -0,0 +1,117 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2016 ownCloud GmbH.
* Copyright (C) 2012 Bartek Przybylski
*
* 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 eu.qsfera.android.lib.common.network;
import android.net.Uri;
import eu.qsfera.android.lib.common.http.methods.HttpBaseMethod;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class WebdavUtils {
private static final SimpleDateFormat[] DATETIME_FORMATS = {
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US),
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US),
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss'Z'", Locale.US),
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US),
new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US),
new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US),
new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US),
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.US)
};
public static Date parseResponseDate(String date) {
Date returnDate;
SimpleDateFormat format;
for (SimpleDateFormat datetimeFormat : DATETIME_FORMATS) {
try {
format = datetimeFormat;
synchronized (format) {
returnDate = format.parse(date);
}
return returnDate;
} catch (ParseException e) {
// this is not the format
}
}
return null;
}
/**
* Encodes a path according to URI RFC 2396.
* <p>
* If the received path doesn't start with "/", the method adds it.
*
* @param remoteFilePath Path
* @return Encoded path according to RFC 2396, always starting with "/"
*/
public static String encodePath(String remoteFilePath) {
String encodedPath = Uri.encode(remoteFilePath, "/");
if (!encodedPath.startsWith("/")) {
encodedPath = "/" + encodedPath;
}
return encodedPath;
}
/**
* @param httpBaseMethod from which to get the etag
* @return etag from response
*/
public static String getEtagFromResponse(HttpBaseMethod httpBaseMethod) {
String eTag = httpBaseMethod.getResponseHeader("OC-ETag");
if (eTag == null) {
eTag = httpBaseMethod.getResponseHeader("oc-etag");
}
if (eTag == null) {
eTag = httpBaseMethod.getResponseHeader("ETag");
}
if (eTag == null) {
eTag = httpBaseMethod.getResponseHeader("etag");
}
String result = "";
if (eTag != null) {
result = eTag;
}
return result;
}
public static String normalizeProtocolPrefix(String url, boolean isSslConn) {
if (!url.toLowerCase().startsWith("http://") &&
!url.toLowerCase().startsWith("https://")) {
if (isSslConn) {
return "https://" + url;
} else {
return "http://" + url;
}
}
return url;
}
}
@@ -0,0 +1,143 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2017 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 eu.qsfera.android.lib.common.operations;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
/**
* Parser for server exceptions
*
* @author davidgonzalez
*/
public class ErrorMessageParser {
// No namespaces
private static final String ns = null;
// Nodes for XML Parser
private static final String NODE_ERROR = "d:error";
private static final String NODE_MESSAGE = "s:message";
/**
* Parse exception response
*
* @param is
* @return errorMessage for an exception
* @throws XmlPullParserException
* @throws IOException
*/
public String parseXMLResponse(InputStream is) throws XmlPullParserException,
IOException {
String errorMessage = "";
try {
// XMLPullParser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(is, null);
parser.nextTag();
errorMessage = readError(parser);
} finally {
is.close();
}
return errorMessage;
}
/**
* Parse OCS node
*
* @param parser
* @return reason for exception
* @throws XmlPullParserException
* @throws IOException
*/
private String readError(XmlPullParser parser) throws XmlPullParserException, IOException {
String errorMessage = "";
parser.require(XmlPullParser.START_TAG, ns, NODE_ERROR);
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
// read NODE_MESSAGE
if (name.equalsIgnoreCase(NODE_MESSAGE)) {
errorMessage = readText(parser);
} else {
skip(parser);
}
}
return errorMessage;
}
/**
* Skip tags in parser procedure
*
* @param parser
* @throws XmlPullParserException
* @throws IOException
*/
private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
if (parser.getEventType() != XmlPullParser.START_TAG) {
throw new IllegalStateException();
}
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
/**
* Read the text from a node
*
* @param parser
* @return Text of the node
* @throws IOException
* @throws XmlPullParserException
*/
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
}
@@ -0,0 +1,150 @@
/* qsfera 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 eu.qsfera.android.lib.common.operations;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
/**
* Parser for Invalid Character server exception
*
* @author masensio
*/
public class InvalidCharacterExceptionParser {
private static final String EXCEPTION_STRING = "OC\\Connector\\Sabre\\Exception\\InvalidPath";
private static final String EXCEPTION_UPLOAD_STRING = "OCP\\Files\\InvalidPathException";
// No namespaces
private static final String ns = null;
// Nodes for XML Parser
private static final String NODE_ERROR = "d:error";
private static final String NODE_EXCEPTION = "s:exception";
/**
* Parse is as an Invalid Path Exception
*
* @param is
* @return if The exception is an Invalid Char Exception
* @throws XmlPullParserException
* @throws IOException
*/
public boolean parseXMLResponse(InputStream is) throws XmlPullParserException,
IOException {
boolean result = false;
try {
// XMLPullParser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(is, null);
parser.nextTag();
result = readError(parser);
} finally {
is.close();
}
return result;
}
/**
* Parse OCS node
*
* @param parser
* @return List of ShareRemoteFiles
* @throws XmlPullParserException
* @throws IOException
*/
private boolean readError(XmlPullParser parser) throws XmlPullParserException, IOException {
String exception = "";
parser.require(XmlPullParser.START_TAG, ns, NODE_ERROR);
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
// read NODE_EXCEPTION
if (name.equalsIgnoreCase(NODE_EXCEPTION)) {
exception = readText(parser);
} else {
skip(parser);
}
}
return exception.equalsIgnoreCase(EXCEPTION_STRING) ||
exception.equalsIgnoreCase(EXCEPTION_UPLOAD_STRING);
}
/**
* Skip tags in parser procedure
*
* @param parser
* @throws XmlPullParserException
* @throws IOException
*/
private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
if (parser.getEventType() != XmlPullParser.START_TAG) {
throw new IllegalStateException();
}
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
/**
* Read the text from a node
*
* @param parser
* @return Text of the node
* @throws IOException
* @throws XmlPullParserException
*/
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
}
@@ -0,0 +1,31 @@
/* qsfera 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 eu.qsfera.android.lib.common.operations;
public interface OnRemoteOperationListener {
void onRemoteOperationFinish(RemoteOperation caller, RemoteOperationResult result);
}
@@ -0,0 +1,34 @@
/* qsfera 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 eu.qsfera.android.lib.common.operations;
public class OperationCancelledException extends Exception {
/**
* Generated serial version - to avoid Java warning
*/
private static final long serialVersionUID = -6350981497740424983L;
}
@@ -0,0 +1,292 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2022 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 eu.qsfera.android.lib.common.operations;
import android.accounts.Account;
import android.accounts.AccountsException;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Context;
import android.os.Handler;
import eu.qsfera.android.lib.common.QSferaAccount;
import eu.qsfera.android.lib.common.QSferaClient;
import eu.qsfera.android.lib.common.SingleSessionManager;
import eu.qsfera.android.lib.common.accounts.AccountUtils;
import okhttp3.OkHttpClient;
import timber.log.Timber;
import java.io.IOException;
@SuppressWarnings("WeakerAccess")
public abstract class RemoteOperation<T> implements Runnable {
/**
* OCS API header name
*/
public static final String OCS_API_HEADER = "OCS-APIREQUEST";
/**
* OCS API header value
*/
public static final String OCS_API_HEADER_VALUE = "true";
/**
* qsfera account in the remote qsfera server to operate
*/
protected Account mAccount = null;
/**
* Android Application context
*/
protected Context mContext = null;
/**
* Object to interact with the remote server
*/
private QSferaClient mClient = null;
/**
* Object to interact with the remote server
*/
private OkHttpClient mHttpClient = null;
/**
* Callback object to notify about the execution of the remote operation
*/
private OnRemoteOperationListener mListener = null;
/**
* Handler to the thread where mListener methods will be called
*/
private Handler mListenerHandler = null;
/**
* Asynchronously executes the remote operation
* <p>
* This method should be used whenever an qsfera account is available,
* instead of {@link #execute(QSferaClient, OnRemoteOperationListener, Handler))}.
*
* @param account qsfera account in remote qsfera server to reach during the
* execution of the operation.
* @param context Android context for the component calling the method.
* @param listener Listener to be notified about the execution of the operation.
* @param listenerHandler Handler associated to the thread where the methods of the listener
* objects must be called.
* @return Thread were the remote operation is executed.
*/
public Thread execute(Account account, Context context,
OnRemoteOperationListener listener, Handler listenerHandler) {
if (account == null) {
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Account");
}
if (context == null) {
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Context");
}
// mAccount and mContext in the runnerThread to create below
mAccount = account;
mContext = context.getApplicationContext();
mClient = null; // the client instance will be created from
mListener = listener;
mListenerHandler = listenerHandler;
Thread runnerThread = new Thread(this);
runnerThread.start();
return runnerThread;
}
/**
* Asynchronously executes the remote operation
*
* @param client Client object to reach an qsfera server
* during the execution of the operation.
* @param listener Listener to be notified about the execution of the operation.
* @param listenerHandler Handler, if passed in, associated to the thread where the methods of
* the listener objects must be called.
* @return Thread were the remote operation is executed.
*/
public Thread execute(QSferaClient client, OnRemoteOperationListener listener, Handler listenerHandler) {
if (client == null) {
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL QSferaClient");
}
mClient = client;
if (client.getAccount() != null) {
mAccount = client.getAccount().getSavedAccount();
}
mContext = client.getContext();
if (listener == null) {
throw new IllegalArgumentException
("Trying to execute a remote operation asynchronously without a listener to notify the result");
}
mListener = listener;
if (listenerHandler != null) {
mListenerHandler = listenerHandler;
}
Thread runnerThread = new Thread(this);
runnerThread.start();
return runnerThread;
}
private void grantQSferaClient() throws
AccountUtils.AccountNotFoundException, OperationCanceledException, AuthenticatorException, IOException {
if (mClient == null) {
if (mAccount != null && mContext != null) {
QSferaAccount ocAccount = new QSferaAccount(mAccount, mContext);
mClient = SingleSessionManager.getDefaultSingleton().
getClientFor(ocAccount, mContext, SingleSessionManager.getConnectionValidator());
} else {
throw new IllegalStateException("Trying to run a remote operation " +
"asynchronously with no client and no chance to create one (no account)");
}
}
}
/**
* Returns the current client instance to access the remote server.
*
* @return Current client instance to access the remote server.
*/
public final QSferaClient getClient() {
return mClient;
}
/**
* Abstract method to implement the operation in derived classes.
*/
protected abstract RemoteOperationResult<T> run(QSferaClient client);
/**
* Synchronously executes the remote operation on the received qsfera account.
* <p>
* Do not call this method from the main thread.
* <p>
* This method should be used whenever an qsfera account is available, instead of
* {@link #execute(QSferaClient)}.
*
* @param account qsfera account in remote qsfera server to reach during the
* execution of the operation.
* @param context Android context for the component calling the method.
* @return Result of the operation.
*/
public RemoteOperationResult<T> execute(Account account, Context context) {
if (account == null) {
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Account");
}
if (context == null) {
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Context");
}
mAccount = account;
mContext = context.getApplicationContext();
return runOperation();
}
/**
* Synchronously executes the remote operation
* <p>
* Do not call this method from the main thread.
*
* @param client Client object to reach an qsfera server during the execution of
* the operation.
* @return Result of the operation.
*/
public RemoteOperationResult<T> execute(QSferaClient client) {
if (client == null) {
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL QSferaClient");
}
mClient = client;
if (client.getAccount() != null) {
mAccount = client.getAccount().getSavedAccount();
}
mContext = client.getContext();
return runOperation();
}
/**
* Synchronously executes the remote operation
* <p>
* Do not call this method from the main thread.
*
* @param client Client object to reach an qsfera server during the execution of
* the operation.
* @return Result of the operation.
*/
public RemoteOperationResult<T> execute(OkHttpClient client, Context context) {
if (client == null) {
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL QSferaClient");
}
mHttpClient = client;
mContext = context;
return runOperation();
}
/**
* Run operation for asynchronous or synchronous 'onExecute' method.
* <p>
* Considers and performs silent refresh of account credentials if possible
*
* @return Remote operation result
*/
private RemoteOperationResult<T> runOperation() {
RemoteOperationResult<T> result;
try {
grantQSferaClient();
result = run(mClient);
} catch (AccountsException | IOException e) {
Timber.e(e, "Error while trying to access to %s", mAccount.name);
result = new RemoteOperationResult<>(e);
}
return result;
}
/**
* Asynchronous execution of the operation
* started by {@link RemoteOperation#execute(QSferaClient,
* OnRemoteOperationListener, Handler)},
* and result posting.
*/
@Override
public final void run() {
final RemoteOperationResult resultToSend = runOperation();
if (mListenerHandler != null && mListener != null) {
mListenerHandler.post(() ->
mListener.onRemoteOperationFinish(RemoteOperation.this, resultToSend));
} else if (mListener != null) {
mListener.onRemoteOperationFinish(RemoteOperation.this, resultToSend);
}
}
}
@@ -0,0 +1,613 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2022 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 eu.qsfera.android.lib.common.operations;
import android.accounts.Account;
import android.accounts.AccountsException;
import at.bitfire.dav4jvm.exception.DavException;
import at.bitfire.dav4jvm.exception.HttpException;
import eu.qsfera.android.lib.common.accounts.AccountUtils;
import eu.qsfera.android.lib.common.http.HttpConstants;
import eu.qsfera.android.lib.common.http.methods.HttpBaseMethod;
import eu.qsfera.android.lib.common.network.AdvancedX509TrustManager;
import eu.qsfera.android.lib.common.network.CertificateCombinedException;
import okhttp3.Headers;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.json.JSONException;
import timber.log.Timber;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLPeerUnverifiedException;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class RemoteOperationResult<T>
implements Serializable {
/**
* Generated - should be refreshed every time the class changes!!
*/
private static final long serialVersionUID = 4968939884332372230L;
private static final String LOCATION = "location";
private static final String WWW_AUTHENTICATE = "www-authenticate";
private boolean mSuccess = false;
private int mHttpCode = -1;
private String mHttpPhrase = null;
private Exception mException = null;
private ResultCode mCode = ResultCode.UNKNOWN_ERROR;
private String mRedirectedLocation = "";
private List<String> mAuthenticate = new ArrayList<>();
private String mLastPermanentLocation = null;
private T mData = null;
/**
* Public constructor from result code.
* <p>
* To be used when the caller takes the responsibility of interpreting the result of a {@link RemoteOperation}
*
* @param code {@link ResultCode} decided by the caller.
*/
public RemoteOperationResult(ResultCode code) {
mCode = code;
mSuccess = (code == ResultCode.OK || code == ResultCode.OK_SSL ||
code == ResultCode.OK_NO_SSL ||
code == ResultCode.OK_REDIRECT_TO_NON_SECURE_CONNECTION);
}
/**
* Create a new RemoteOperationResult based on the result given by a previous one.
* It does not copy the data.
*
* @param prevRemoteOperation
*/
public RemoteOperationResult(RemoteOperationResult prevRemoteOperation) {
mCode = prevRemoteOperation.mCode;
mHttpCode = prevRemoteOperation.mHttpCode;
mHttpPhrase = prevRemoteOperation.mHttpPhrase;
mAuthenticate = prevRemoteOperation.mAuthenticate;
mException = prevRemoteOperation.mException;
mLastPermanentLocation = prevRemoteOperation.mLastPermanentLocation;
mSuccess = prevRemoteOperation.mSuccess;
mRedirectedLocation = prevRemoteOperation.mRedirectedLocation;
}
/**
* Public constructor from exception.
* <p>
* To be used when an exception prevented the end of the {@link RemoteOperation}.
* <p>
* Determines a {@link ResultCode} depending on the type of the exception.
*
* @param e Exception that interrupted the {@link RemoteOperation}
*/
public RemoteOperationResult(Exception e) {
mException = e;
//TODO: Do propper exception handling and remove this
Timber.e("---------------------------------" +
"\nCreate RemoteOperationResult from exception." +
"\n Message: %s" +
"\n Stacktrace: %s" +
"\n---------------------------------",
ExceptionUtils.getMessage(e),
ExceptionUtils.getStackTrace(e));
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 MalformedURLException) {
mCode = ResultCode.INCORRECT_ADDRESS;
} else if (e instanceof UnknownHostException) {
mCode = ResultCode.HOST_NOT_AVAILABLE;
} else if (e instanceof AccountUtils.AccountNotFoundException) {
mCode = ResultCode.ACCOUNT_NOT_FOUND;
} else if (e instanceof AccountsException) {
mCode = ResultCode.ACCOUNT_EXCEPTION;
} else if (e instanceof SSLException || e instanceof RuntimeException) {
if (e instanceof SSLPeerUnverifiedException) {
java.security.cert.X509Certificate lastCert = AdvancedX509TrustManager.sLastCert.get();
AdvancedX509TrustManager.sLastCert.remove();
CertificateCombinedException sslPeerUnverifiedException =
new CertificateCombinedException(lastCert);
sslPeerUnverifiedException.setSslPeerUnverifiedException((SSLPeerUnverifiedException) e);
sslPeerUnverifiedException.initCause(e);
mException = sslPeerUnverifiedException;
mCode = ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED;
} else {
CertificateCombinedException se = getCertificateCombinedException(e);
if (se != null) {
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 if (e instanceof ProtocolException) {
mCode = ResultCode.NETWORK_ERROR;
} else {
mCode = ResultCode.UNKNOWN_ERROR;
}
}
/**
* Public constructor from separate elements of an HTTP or DAV response.
* <p>
* To be used when the result needs to be interpreted from the response of an HTTP/DAV method.
* <p>
* Determines a {@link ResultCode} from the already executed method received as a parameter. Generally,
* will depend on the HTTP code and HTTP response headers received. In some cases will inspect also the
* response body
*
* @param httpMethod
* @throws IOException
*/
public RemoteOperationResult(HttpBaseMethod httpMethod) throws IOException {
this(httpMethod.getStatusCode(),
httpMethod.getStatusMessage(),
httpMethod.getResponseHeaders()
);
if (mHttpCode == HttpConstants.HTTP_BAD_REQUEST) { // 400
String bodyResponse = httpMethod.getResponseBodyAsString();
// do not get for other HTTP codes!; could not be available
if (bodyResponse.length() > 0) {
InputStream is = new ByteArrayInputStream(bodyResponse.getBytes());
InvalidCharacterExceptionParser xmlParser = new InvalidCharacterExceptionParser();
try {
if (xmlParser.parseXMLResponse(is)) {
mCode = ResultCode.INVALID_CHARACTER_DETECT_IN_SERVER;
} else {
parseErrorMessageAndSetCode(
httpMethod.getResponseBodyAsString(),
ResultCode.SPECIFIC_BAD_REQUEST
);
}
} catch (Exception e) {
Timber.w("Error reading exception from server: %s", e.getMessage());
// mCode stays as set in this(success, httpCode, headers)
}
}
}
// before
switch (mHttpCode) {
case HttpConstants.HTTP_FORBIDDEN:
parseErrorMessageAndSetCode(
httpMethod.getResponseBodyAsString(),
ResultCode.SPECIFIC_FORBIDDEN
);
break;
case HttpConstants.HTTP_UNSUPPORTED_MEDIA_TYPE:
parseErrorMessageAndSetCode(
httpMethod.getResponseBodyAsString(),
ResultCode.SPECIFIC_UNSUPPORTED_MEDIA_TYPE
);
break;
case HttpConstants.HTTP_SERVICE_UNAVAILABLE:
parseErrorMessageAndSetCode(
httpMethod.getResponseBodyAsString(),
ResultCode.SPECIFIC_SERVICE_UNAVAILABLE
);
break;
case HttpConstants.HTTP_METHOD_NOT_ALLOWED:
parseErrorMessageAndSetCode(
httpMethod.getResponseBodyAsString(),
ResultCode.SPECIFIC_METHOD_NOT_ALLOWED
);
break;
case HttpConstants.HTTP_PRECONDITION_FAILED:
// For TUS, 412 typically indicates Upload-Offset precondition mismatch
mCode = ResultCode.CONFLICT;
break;
case HttpConstants.HTTP_TOO_EARLY:
mCode = ResultCode.TOO_EARLY;
break;
default:
break;
}
}
/**
* Public constructor from separate elements of an HTTP or DAV response.
* <p>
* To be used when the result needs to be interpreted from HTTP response elements that could come from
* different requests (WARNING: black magic, try to avoid).
* <p>
* <p>
* Determines a {@link ResultCode} depending on the HTTP code and HTTP response headers received.
*
* @param httpCode HTTP status code returned by an HTTP/DAV method.
* @param httpPhrase HTTP status line phrase returned by an HTTP/DAV method
* @param headers HTTP response header returned by an HTTP/DAV method
*/
public RemoteOperationResult(int httpCode, String httpPhrase, Headers headers) {
this(httpCode, httpPhrase);
if (headers != null) {
for (Map.Entry<String, List<String>> header : headers.toMultimap().entrySet()) {
if (LOCATION.equalsIgnoreCase(header.getKey())) {
mRedirectedLocation = header.getValue().get(0);
continue;
}
if (WWW_AUTHENTICATE.equalsIgnoreCase(header.getKey())) {
for (String value : header.getValue()) {
mAuthenticate.add(value.toLowerCase());
}
}
}
}
}
/**
* Private constructor for results built interpreting a HTTP or DAV response.
* <p>
* Determines a {@link ResultCode} depending of the type of the exception.
*
* @param httpCode HTTP status code returned by the HTTP/DAV method.
* @param httpPhrase HTTP status line phrase returned by the HTTP/DAV method
*/
private RemoteOperationResult(int httpCode, String httpPhrase) {
mHttpCode = httpCode;
mHttpPhrase = httpPhrase;
if (httpCode > 0) {
switch (httpCode) {
case HttpConstants.HTTP_UNAUTHORIZED: // 401
mCode = ResultCode.UNAUTHORIZED;
break;
case HttpConstants.HTTP_FORBIDDEN: // 403
mCode = ResultCode.FORBIDDEN;
break;
case HttpConstants.HTTP_NOT_FOUND: // 404
mCode = ResultCode.FILE_NOT_FOUND;
break;
case HttpConstants.HTTP_CONFLICT: // 409
mCode = ResultCode.CONFLICT;
break;
case HttpConstants.HTTP_LOCKED: // 423
mCode = ResultCode.RESOURCE_LOCKED;
break;
case HttpConstants.HTTP_INTERNAL_SERVER_ERROR: // 500
mCode = ResultCode.UNHANDLED_HTTP_CODE; // treat as generic server error
break;
case HttpConstants.HTTP_SERVICE_UNAVAILABLE: // 503
mCode = ResultCode.SERVICE_UNAVAILABLE;
break;
case HttpConstants.HTTP_INSUFFICIENT_STORAGE: // 507
mCode = ResultCode.QUOTA_EXCEEDED; // surprise!
break;
default:
mCode = ResultCode.UNHANDLED_HTTP_CODE; // UNKNOWN ERROR
Timber.d("RemoteOperationResult has processed UNHANDLED_HTTP_CODE: " + mHttpCode + " " + mHttpPhrase);
}
}
}
/**
* Parse the error message included in the body response, if any, and set the specific result
* code
*
* @param bodyResponse okHttp response body
* @param resultCode our own custom result code
*/
private void parseErrorMessageAndSetCode(String bodyResponse, ResultCode resultCode) {
if (bodyResponse != null && bodyResponse.length() > 0) {
InputStream is = new ByteArrayInputStream(bodyResponse.getBytes());
ErrorMessageParser xmlParser = new ErrorMessageParser();
try {
String errorMessage = xmlParser.parseXMLResponse(is);
if (!errorMessage.equals("")) {
mCode = resultCode;
mHttpPhrase = errorMessage;
}
} catch (Exception e) {
Timber.w("Error reading exception from server: %s\nTrace: %s", e.getMessage(), ExceptionUtils.getStackTrace(e));
// mCode stays as set in this(success, httpCode, headers)
}
}
}
public boolean isSuccess() {
return mSuccess;
}
public void setSuccess(boolean success) {
this.mSuccess = success;
}
public boolean isCancelled() {
return mCode == ResultCode.CANCELLED;
}
public int getHttpCode() {
return mHttpCode;
}
public String getHttpPhrase() {
return mHttpPhrase;
}
public ResultCode getCode() {
return mCode;
}
public Exception getException() {
return mException;
}
public boolean isSslRecoverableException() {
return mCode == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED;
}
public boolean isRedirectToNonSecureConnection() {
return mCode == ResultCode.OK_REDIRECT_TO_NON_SECURE_CONNECTION;
}
private CertificateCombinedException getCertificateCombinedException(Exception e) {
CertificateCombinedException result = null;
if (e instanceof CertificateCombinedException) {
return (CertificateCombinedException) e;
}
Throwable cause = mException.getCause();
Throwable previousCause = null;
while (cause != null && cause != previousCause &&
!(cause instanceof CertificateCombinedException)) {
previousCause = cause;
cause = cause.getCause();
}
if (cause instanceof CertificateCombinedException) {
result = (CertificateCombinedException) cause;
}
return result;
}
public String getLogMessage() {
if (mException != null) {
if (mException instanceof OperationCancelledException) {
return "Operation cancelled by the caller";
} else if (mException instanceof SocketException) {
return "Socket exception";
} else if (mException instanceof SocketTimeoutException) {
return "Socket timeout exception";
} else if (mException instanceof MalformedURLException) {
return "Malformed URL exception";
} else if (mException instanceof UnknownHostException) {
return "Unknown host exception";
} else if (mException instanceof CertificateCombinedException) {
if (((CertificateCombinedException) mException).isRecoverable()) {
return "SSL recoverable exception";
} else {
return "SSL exception";
}
} else if (mException instanceof SSLException) {
return "SSL exception";
} else if (mException instanceof DavException) {
return "Unexpected WebDAV exception";
} else if (mException instanceof HttpException) {
return "HTTP violation";
} else if (mException instanceof IOException) {
return "Unrecovered transport exception";
} else if (mException instanceof AccountUtils.AccountNotFoundException) {
Account failedAccount =
((AccountUtils.AccountNotFoundException) mException).getFailedAccount();
return mException.getMessage() + " (" +
(failedAccount != null ? failedAccount.name : "NULL") + ")";
} else if (mException instanceof AccountsException) {
return "Exception while using account";
} else if (mException instanceof JSONException) {
return "JSON exception";
} else {
return "Unexpected exception";
}
}
if (mCode == ResultCode.INSTANCE_NOT_CONFIGURED) {
return "The qsfera server is not configured!";
} else if (mCode == ResultCode.NO_NETWORK_CONNECTION) {
return "No network connection";
} else if (mCode == ResultCode.BAD_OC_VERSION) {
return "No valid qsfera version was found at the server";
} else if (mCode == ResultCode.LOCAL_STORAGE_FULL) {
return "Local storage full";
} else if (mCode == ResultCode.LOCAL_STORAGE_NOT_MOVED) {
return "Error while moving file to final directory";
} else if (mCode == ResultCode.ACCOUNT_NOT_NEW) {
return "Account already existing when creating a new one";
} else if (mCode == ResultCode.ACCOUNT_NOT_THE_SAME) {
return "Authenticated with a different account than the one updating";
} else if (mCode == ResultCode.INVALID_CHARACTER_IN_NAME) {
return "The file name contains an forbidden character";
} else if (mCode == ResultCode.FILE_NOT_FOUND) {
return "Local file does not exist";
} else if (mCode == ResultCode.SYNC_CONFLICT) {
return "Synchronization conflict";
}
return "Operation finished with HTTP status code " + mHttpCode + " (" +
(isSuccess() ? "success" : "fail") + ")";
}
public boolean isServerFail() {
return (mHttpCode >= HttpConstants.HTTP_INTERNAL_SERVER_ERROR);
}
public boolean isException() {
return (mException != null);
}
public boolean isTemporalRedirection() {
return (mHttpCode == 302 || mHttpCode == 307);
}
public String getRedirectedLocation() {
return mRedirectedLocation;
}
/**
* Checks if is a non https connection
*
* @return boolean true/false
*/
public boolean isNonSecureRedirection() {
return (mRedirectedLocation != null && !(mRedirectedLocation.toLowerCase().startsWith("https://")));
}
public List<String> getAuthenticateHeaders() {
return mAuthenticate;
}
public String getLastPermanentLocation() {
return mLastPermanentLocation;
}
public void setLastPermanentLocation(String lastPermanentLocation) {
mLastPermanentLocation = lastPermanentLocation;
}
public T getData() {
return mData;
}
public void setData(T data) {
mData = data;
}
public void setHttpPhrase(String httpPhrase) {
mHttpPhrase = httpPhrase;
}
public enum ResultCode {
OK,
OK_SSL,
OK_NO_SSL,
UNHANDLED_HTTP_CODE,
UNAUTHORIZED,
FILE_NOT_FOUND,
INSTANCE_NOT_CONFIGURED,
UNKNOWN_ERROR,
WRONG_CONNECTION,
TIMEOUT,
INCORRECT_ADDRESS,
HOST_NOT_AVAILABLE,
NO_NETWORK_CONNECTION,
SSL_ERROR,
SSL_RECOVERABLE_PEER_UNVERIFIED,
BAD_OC_VERSION,
CANCELLED,
INVALID_LOCAL_FILE_NAME,
INVALID_OVERWRITE,
CONFLICT,
OAUTH2_ERROR,
SYNC_CONFLICT,
LOCAL_STORAGE_FULL,
LOCAL_STORAGE_NOT_MOVED,
LOCAL_STORAGE_NOT_COPIED,
OAUTH2_ERROR_ACCESS_DENIED,
QUOTA_EXCEEDED,
ACCOUNT_NOT_FOUND,
ACCOUNT_EXCEPTION,
ACCOUNT_NOT_NEW,
ACCOUNT_NOT_THE_SAME,
INVALID_CHARACTER_IN_NAME,
SHARE_NOT_FOUND,
LOCAL_STORAGE_NOT_REMOVED,
FORBIDDEN,
SHARE_FORBIDDEN,
SPECIFIC_FORBIDDEN,
OK_REDIRECT_TO_NON_SECURE_CONNECTION,
INVALID_MOVE_INTO_DESCENDANT,
INVALID_COPY_INTO_DESCENDANT,
PARTIAL_MOVE_DONE,
PARTIAL_COPY_DONE,
SHARE_WRONG_PARAMETER,
WRONG_SERVER_RESPONSE,
INVALID_CHARACTER_DETECT_IN_SERVER,
DELAYED_FOR_WIFI,
LOCAL_FILE_NOT_FOUND,
SERVICE_UNAVAILABLE,
SPECIFIC_SERVICE_UNAVAILABLE,
SPECIFIC_UNSUPPORTED_MEDIA_TYPE,
SPECIFIC_METHOD_NOT_ALLOWED,
SPECIFIC_BAD_REQUEST,
TOO_EARLY,
NETWORK_ERROR,
RESOURCE_LOCKED
}
}
@@ -0,0 +1,28 @@
/* qsfera 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 eu.qsfera.android.lib.common.utils
fun Any.isOneOf(vararg values: Any): Boolean =
this in values
@@ -0,0 +1,46 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2022 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 eu.qsfera.android.lib.common.utils
import timber.log.Timber
import java.io.File
object LoggingHelper {
fun startLogging(directory: File, storagePath: String) {
ocFileLoggingTree()?.let {
Timber.uproot(it)
}
if (!directory.exists())
directory.mkdirs()
Timber.plant(OCFileLoggingTree(directory, filename = storagePath))
}
fun stopLogging() {
ocFileLoggingTree()?.let {
Timber.uproot(it)
}
}
}
@@ -0,0 +1,171 @@
/**
* qsfera Android client application
*
* @author Hannes Achleitner
* @author Manuel Plazas Palacio
*
* Copyright (C) 2023 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package eu.qsfera.android.lib.common.utils
import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import timber.log.Timber
import java.io.File
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.UUID
class OCFileLoggingTree(
externalCacheDir: File,
context: Context? = null,
filename: String = UUID.randomUUID().toString(),
private val newLogcat: Boolean = true,
) : Timber.DebugTree() {
private var file: File
private var logImpossible = false
private var codeIdentifier = ""
private var method = ""
init {
externalCacheDir.let {
if (!it.exists() && !it.mkdirs()) {
Log.e(LOG_TAG, "couldn't create ${it.absoluteFile}")
}
var fileNameTimestamp = SimpleDateFormat(LOG_FILE_TIME_FORMAT, Locale.getDefault()).format(Date())
it.list()?.let { logFiles ->
if (logFiles.isNotEmpty()) {
var lastDateLogFileString = if (context != null) {
logFiles.last().substringAfterLast("${context.packageName}.").substringBeforeLast(".log")
} else {
logFiles.last().substringAfterLast("$filename.").substringBeforeLast(".log")
}
val dateFormat = SimpleDateFormat(LOG_FILE_TIME_FORMAT)
if (lastDateLogFileString.matches("^\\d{4}-\\d{2}-\\d{2}$".toRegex())) {
lastDateLogFileString = "${lastDateLogFileString}_00.00.00"
}
val lastDayLogFileDate = dateFormat.parse(lastDateLogFileString)
val newDayLogFileDate = dateFormat.parse(fileNameTimestamp)
val lastDayDateLogFileString = SimpleDateFormat(LOG_FILE_DAY_FORMAT, Locale.getDefault()).format(lastDayLogFileDate!!)
val newDayDateLogFileString = SimpleDateFormat(LOG_FILE_DAY_FORMAT, Locale.getDefault()).format(newDayLogFileDate!!)
if (lastDayDateLogFileString == newDayDateLogFileString) {
fileNameTimestamp = lastDateLogFileString
}
}
}
file = if (context != null) {
File(it, "${context.packageName}.$fileNameTimestamp.log")
} else {
File(it, "$filename.$fileNameTimestamp.log")
}
}
}
override fun createStackElementTag(element: StackTraceElement): String {
if (newLogcat) {
method = String.format(
Locale.US,
"%s.%s()",
// method is fully qualified only when class differs on filename otherwise it can be cropped on long lambda expressions
super.createStackElementTag(element)?.replaceFirst(element.fileName.takeWhile { it != '.' }, ""),
element.methodName
)
codeIdentifier = String.format(
Locale.US,
"(%s:%d)",
element.fileName,
element.lineNumber // format ensures line numbers have at least 3 places to align consecutive output from the same file
)
return "(${element.fileName}:${element.lineNumber})"
} else {
return String.format(
Locale.US,
"(%s:%d) %s.%s()",
element.fileName,
element.lineNumber, // format ensures line numbers have at least 3 places to align consecutive output from the same file
// method is fully qualified only when class differs on filename otherwise it can be cropped on long lambda expressions
super.createStackElementTag(element)?.replaceFirst(element.fileName.takeWhile { it != '.' }, ""),
element.methodName
)
}
}
@SuppressLint("LogNotTimber")
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
try {
val logTimeStamp = SimpleDateFormat(LOG_MESSAGE_TIME_FORMAT, Locale.getDefault()).format(Date())
val priorityText = when (priority) {
2 -> "V:"
3 -> "D:"
4 -> "I:"
5 -> "W:"
6 -> "E:"
7 -> "A:"
else -> "$priority"
}
Log.d(tag, "$priorityText $message")
val textLine = "$priorityText $logTimeStamp$tag$message\n"
CoroutineScope(Dispatchers.IO).launch {
runCatching {
val writer = FileWriter(file, true)
writer.append(textLine)
writer.flush()
writer.close()
}
}
} catch (e: Exception) {
// Log to prevent an endless loop
if (!logImpossible) {
// log this output just once
Log.w(LOG_TAG, "Can't log into file : $e")
logImpossible = true
}
}
// Don't call super, otherwise it logs twice
// super.log(priority, tag, message, t)
}
companion object {
private val LOG_TAG = OCFileLoggingTree::class.java.simpleName
private const val LOG_FILE_TIME_FORMAT = "yyyy-MM-dd_HH.mm.ss"
private const val LOG_FILE_DAY_FORMAT = "dd"
private const val LOG_MESSAGE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss:SSS"
}
}
fun ocFileLoggingTree() = Timber.forest().filterIsInstance<OCFileLoggingTree>().firstOrNull()
@@ -0,0 +1,70 @@
/* qsfera 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 eu.qsfera.android.lib.common.utils;
import java.util.Random;
import java.util.UUID;
/**
* Class with methods to generate random values
*
* @author David González Verdugo
*/
public class RandomUtils {
private static final String CANDIDATECHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"1234567890-+/_=.:";
/**
* @param length the number of random chars to be generated
* @return String containing random chars
*/
public static String generateRandomString(int length) {
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(CANDIDATECHARS.charAt(random.nextInt(CANDIDATECHARS.length())));
}
return sb.toString();
}
/**
* @param min minimum integer to obtain randomly
* @param max maximum integer to obtain randomly
* @return random integer between min and max
*/
public static int generateRandomInteger(int min, int max) {
Random r = new Random();
return r.nextInt(max - min) + min;
}
/**
* @return random UUID
*/
public static String generateRandomUUID() {
return UUID.randomUUID().toString();
}
}
@@ -0,0 +1,52 @@
/* qsfera 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 eu.qsfera.android.lib.resources
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
// Response retrieved by OCS Rest API, used to obtain capabilities, shares and user info among others.
// QSfera OCS capabilities response.
@JsonClass(generateAdapter = true)
data class CommonOcsResponse<T>(
val ocs: OCSResponse<T>
)
@JsonClass(generateAdapter = true)
data class OCSResponse<T>(
val meta: MetaData,
val data: T?
)
@JsonClass(generateAdapter = true)
data class MetaData(
val status: String,
@Json(name = "statuscode")
val statusCode: Int,
val message: String?,
@Json(name = "itemsperpage")
val itemsPerPage: String?,
@Json(name = "totalitems")
val totalItems: String?
)
@@ -0,0 +1,37 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2022 ownCloud GmbH.
*
* @author David González Verdugo
*
* 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 eu.qsfera.android.lib.resources
import eu.qsfera.android.lib.common.QSferaClient
/**
* Facade to perform network calls without the verbosity of remote operations
*/
interface Service {
val client: QSferaClient
}
@@ -0,0 +1,108 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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 eu.qsfera.android.lib.resources.appregistry
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.nonwebdav.PostMethod
import eu.qsfera.android.lib.common.network.WebdavUtils
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.operations.RemoteOperationResult.ResultCode
import com.squareup.moshi.Json
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonClass
import com.squareup.moshi.Moshi
import okhttp3.FormBody
import okhttp3.RequestBody
import timber.log.Timber
import java.net.URL
import java.util.concurrent.TimeUnit
class CreateRemoteFileWithAppProviderOperation(
private val createFileWithAppProviderEndpoint: String,
private val parentContainerId: String,
private val filename: String,
) : RemoteOperation<String>() {
override fun run(client: QSferaClient): RemoteOperationResult<String> =
try {
val createFileWithAppProviderRequestBody = CreateFileWithAppProviderParams(parentContainerId, filename)
.toRequestBody()
val stringUrl = client.baseUri.toString() + WebdavUtils.encodePath(createFileWithAppProviderEndpoint)
val postMethod = PostMethod(URL(stringUrl), createFileWithAppProviderRequestBody).apply {
setReadTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
setConnectionTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
}
val status = client.executeHttpMethod(postMethod)
Timber.d("Create file $filename with app provider in folder with ID $parentContainerId" +
" - $status${if (!isSuccess(status)) "(FAIL)" else ""}")
if (isSuccess(status)) RemoteOperationResult<String>(ResultCode.OK).apply {
val moshi = Moshi.Builder().build()
val adapter: JsonAdapter<CreateFileWithAppProviderResponse> = moshi.adapter(CreateFileWithAppProviderResponse::class.java)
data = postMethod.getResponseBodyAsString()?.let { adapter.fromJson(it)!!.fileId }
}
else RemoteOperationResult<String>(postMethod).apply { data = "" }
} catch (e: Exception) {
val result = RemoteOperationResult<String>(e)
Timber.e(e, "Create file $filename with app provider in folder with ID $parentContainerId failed")
result
}
private fun isSuccess(status: Int) = status == HttpConstants.HTTP_OK
data class CreateFileWithAppProviderParams(
val parentContainerId: String,
val filename: String,
) {
fun toRequestBody(): RequestBody =
FormBody.Builder()
.add(PARAM_PARENT_CONTAINER_ID, parentContainerId)
.add(PARAM_FILENAME, filename)
.build()
companion object {
const val PARAM_PARENT_CONTAINER_ID = "parent_container_id"
const val PARAM_FILENAME = "filename"
}
}
@JsonClass(generateAdapter = true)
data class CreateFileWithAppProviderResponse(
@Json(name = "file_id")
val fileId: String,
)
companion object {
private const val TIMEOUT: Long = 5_000
}
}
@@ -0,0 +1,88 @@
/* qsfera Android Library is available under MIT license
* @author Abel García de Prada
*
* Copyright (C) 2023 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 eu.qsfera.android.lib.resources.appregistry
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.nonwebdav.GetMethod
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.operations.RemoteOperationResult.ResultCode.OK
import eu.qsfera.android.lib.resources.appregistry.responses.AppRegistryResponse
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import timber.log.Timber
import java.net.URL
class GetRemoteAppRegistryOperation(private val appUrl: String?) : RemoteOperation<AppRegistryResponse>() {
override fun run(client: QSferaClient): RemoteOperationResult<AppRegistryResponse> {
var result: RemoteOperationResult<AppRegistryResponse>
try {
val urlFormatted = removeSubfolder(client.baseUri.toString()) + appUrl
val getMethod = GetMethod(URL(urlFormatted))
val status = client.executeHttpMethod(getMethod)
val response = getMethod.getResponseBodyAsString()
if (status == HttpConstants.HTTP_OK) {
Timber.d("Successful response $response")
// Parse the response
val moshi: Moshi = Moshi.Builder().build()
val adapter: JsonAdapter<AppRegistryResponse> = moshi.adapter(AppRegistryResponse::class.java)
val appRegistryResponse: AppRegistryResponse = response?.let { adapter.fromJson(it) } ?: AppRegistryResponse(value = emptyList())
result = RemoteOperationResult(OK)
result.data = appRegistryResponse
Timber.d("Get AppRegistry completed and parsed to ${result.data}")
} else {
result = RemoteOperationResult(getMethod)
Timber.e("Failed response while getting app registry from the server status code: $status; response message: $response")
}
} catch (e: Exception) {
result = RemoteOperationResult(e)
Timber.e(e, "Exception while getting app registry")
}
return result
}
private fun removeSubfolder(url: String): String {
val doubleSlashIndex = url.indexOf("//")
val nextSlashIndex = url.indexOf('/', doubleSlashIndex + 2)
return if (nextSlashIndex >= 0) {
val result = url.substring(0, nextSlashIndex)
if (result.endsWith("/")) result else "$result/"
} else {
if (url.endsWith("/")) url else "$url/"
}
}
}
@@ -0,0 +1,106 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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 eu.qsfera.android.lib.resources.appregistry
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.nonwebdav.PostMethod
import eu.qsfera.android.lib.common.network.WebdavUtils
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.operations.RemoteOperationResult.ResultCode
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonClass
import com.squareup.moshi.Moshi
import okhttp3.FormBody
import okhttp3.RequestBody
import timber.log.Timber
import java.net.URL
import java.util.concurrent.TimeUnit
class GetUrlToOpenInWebRemoteOperation(
private val openWithWebEndpoint: String,
private val fileId: String,
private val appName: String,
) : RemoteOperation<String>() {
override fun run(client: QSferaClient): RemoteOperationResult<String> =
try {
val openInWebRequestBody = OpenInWebParams(fileId, appName).toRequestBody()
val stringUrl =
client.baseUri.toString() + WebdavUtils.encodePath(openWithWebEndpoint)
val postMethod = PostMethod(URL(stringUrl), openInWebRequestBody).apply {
setReadTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
setConnectionTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
}
val status = client.executeHttpMethod(postMethod)
Timber.d("Open in web for file: $fileId - $status${if (!isSuccess(status)) "(FAIL)" else ""}")
if (isSuccess(status)) RemoteOperationResult<String>(ResultCode.OK).apply {
val moshi = Moshi.Builder().build()
val adapter: JsonAdapter<OpenInWebResponse> = moshi.adapter(OpenInWebResponse::class.java)
data = postMethod.getResponseBodyAsString()?.let { adapter.fromJson(it)!!.uri }
}
else RemoteOperationResult<String>(postMethod).apply { data = "" }
} catch (e: Exception) {
val result = RemoteOperationResult<String>(e)
Timber.e(e, "Open in web for file: $fileId failed")
result
}
private fun isSuccess(status: Int) = status == HttpConstants.HTTP_OK
data class OpenInWebParams(
val fileId: String,
val appName: String,
) {
fun toRequestBody(): RequestBody =
FormBody.Builder()
.add(PARAM_FILE_ID, fileId)
.add(PARAM_APP_NAME, appName)
.build()
companion object {
const val PARAM_FILE_ID = "file_id"
const val PARAM_APP_NAME = "app_name"
}
}
@JsonClass(generateAdapter = true)
data class OpenInWebResponse(val uri: String)
companion object {
/**
* Maximum time to wait for a response from the server in milliseconds.
*/
private const val TIMEOUT = 5_000L
}
}
@@ -0,0 +1,58 @@
/* qsfera Android Library is available under MIT license
* @author Abel García de Prada
*
* Copyright (C) 2023 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 eu.qsfera.android.lib.resources.appregistry.responses
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class AppRegistryResponse(
@Json(name = "mime-types")
val value: List<AppRegistryMimeTypeResponse>
)
@JsonClass(generateAdapter = true)
data class AppRegistryMimeTypeResponse(
@Json(name = "mime_type") val mimeType: String,
val ext: String? = null,
@Json(name = "app_providers")
val appProviders: List<AppRegistryProviderResponse>,
val name: String? = null,
val icon: String? = null,
val description: String? = null,
@Json(name = "allow_creation")
val allowCreation: Boolean? = null,
@Json(name = "default_application")
val defaultApplication: String? = null
)
@JsonClass(generateAdapter = true)
data class AppRegistryProviderResponse(
val name: String,
@Json(name = "product_name")
val productName: String,
val icon: String,
)
@@ -0,0 +1,44 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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 eu.qsfera.android.lib.resources.appregistry.services
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.resources.Service
import eu.qsfera.android.lib.resources.appregistry.responses.AppRegistryResponse
interface AppRegistryService : Service {
fun getAppRegistry(appUrl: String?): RemoteOperationResult<AppRegistryResponse>
fun getUrlToOpenInWeb(
openWebEndpoint: String,
fileId: String,
appName: String,
): RemoteOperationResult<String>
fun createFileWithAppProvider(
createFileWithAppProviderEndpoint: String,
parentContainerId: String,
filename: String,
): RemoteOperationResult<String>
}
@@ -0,0 +1,54 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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 eu.qsfera.android.lib.resources.appregistry.services
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.resources.appregistry.CreateRemoteFileWithAppProviderOperation
import eu.qsfera.android.lib.resources.appregistry.GetRemoteAppRegistryOperation
import eu.qsfera.android.lib.resources.appregistry.GetUrlToOpenInWebRemoteOperation
import eu.qsfera.android.lib.resources.appregistry.responses.AppRegistryResponse
class OCAppRegistryService(override val client: QSferaClient) : AppRegistryService {
override fun getAppRegistry(appUrl: String?): RemoteOperationResult<AppRegistryResponse> =
GetRemoteAppRegistryOperation(appUrl).execute(client)
override fun getUrlToOpenInWeb(openWebEndpoint: String, fileId: String, appName: String): RemoteOperationResult<String> =
GetUrlToOpenInWebRemoteOperation(
openWithWebEndpoint = openWebEndpoint,
fileId = fileId,
appName = appName
).execute(client)
override fun createFileWithAppProvider(
createFileWithAppProviderEndpoint: String,
parentContainerId: String,
filename: String
): RemoteOperationResult<String> =
CreateRemoteFileWithAppProviderOperation(
createFileWithAppProviderEndpoint = createFileWithAppProviderEndpoint,
parentContainerId = parentContainerId,
filename = filename,
).execute(client)
}
@@ -0,0 +1,96 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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 eu.qsfera.android.lib.resources.files
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.webdav.DavUtils.allPropSet
import eu.qsfera.android.lib.common.http.methods.webdav.PropfindMethod
import eu.qsfera.android.lib.common.network.WebdavUtils
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.operations.RemoteOperationResult.ResultCode
import timber.log.Timber
import java.net.URL
import java.util.concurrent.TimeUnit
/**
* Operation to check the existence of a path in a remote server.
*
* @author David A. Velasco
* @author David González Verdugo
* @author Abel García de Prada
* @author Juan Carlos Garrote Gascón
*
* @param remotePath Path to append to the URL owned by the client instance.
* @param isUserLoggedIn When `true`, the username won't be added at the end of the PROPFIND url since is not
* needed to check user credentials
*/
class CheckPathExistenceRemoteOperation(
val remotePath: String? = "",
val isUserLoggedIn: Boolean,
val spaceWebDavUrl: String? = null,
) : RemoteOperation<Boolean>() {
override fun run(client: QSferaClient): RemoteOperationResult<Boolean> {
val baseStringUrl = spaceWebDavUrl ?: if (isUserLoggedIn) client.userFilesWebDavUri.toString() else client.baseFilesWebDavUri.toString()
val stringUrl = if (isUserLoggedIn) baseStringUrl + WebdavUtils.encodePath(remotePath) else baseStringUrl
return try {
val propFindMethod = PropfindMethod(URL(stringUrl), 0, allPropSet).apply {
setReadTimeout(TIMEOUT.toLong(), TimeUnit.SECONDS)
setConnectionTimeout(TIMEOUT.toLong(), TimeUnit.SECONDS)
}
val status = client.executeHttpMethod(propFindMethod)
/* PROPFIND method
* 404 NOT FOUND: path doesn't exist,
* 207 MULTI_STATUS: path exists.
*/
Timber.d(
"Existence check for $stringUrl finished with HTTP status $status${if (!isSuccess(status)) "(FAIL)" else ""}"
)
if (isSuccess(status)) RemoteOperationResult<Boolean>(ResultCode.OK).apply { data = true }
else RemoteOperationResult<Boolean>(propFindMethod).apply { data = false }
} catch (e: Exception) {
val result = RemoteOperationResult<Boolean>(e)
Timber.e(
e,
"Existence check for $stringUrl : ${result.logMessage}"
)
result.data = false
result
}
}
private fun isSuccess(status: Int) = status == HttpConstants.HTTP_OK || status == HttpConstants.HTTP_MULTI_STATUS
companion object {
/**
* Maximum time to wait for a response from the server in milliseconds.
*/
private const val TIMEOUT = 10000
}
}
@@ -0,0 +1,130 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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 eu.qsfera.android.lib.resources.files
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.webdav.CopyMethod
import eu.qsfera.android.lib.common.network.WebdavUtils
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.operations.RemoteOperationResult.ResultCode
import eu.qsfera.android.lib.common.utils.isOneOf
import timber.log.Timber
import java.net.URL
import java.util.concurrent.TimeUnit
/**
* Remote operation copying a remote file or folder in the qsfera server to a different folder
* in the same account.
*
* Allows renaming the copying file/folder at the same time.
*
* @author David A. Velasco
* @author Christian Schabesberger
* @author David González V.
* @author Juan Carlos Garrote Gascón
* @author Manuel Plazas Palacio
*
* @param sourceRemotePath Remote path of the file/folder to copy.
* @param targetRemotePath Remote path desired for the file/folder to copy it.
*/
class CopyRemoteFileOperation(
private val sourceRemotePath: String,
private val targetRemotePath: String,
private val sourceSpaceWebDavUrl: String? = null,
private val targetSpaceWebDavUrl: String? = null,
private val forceOverride: Boolean = false,
) : RemoteOperation<String>() {
/**
* Performs the rename operation.
*
* @param client Client object to communicate with the remote qsfera server.
*/
override fun run(client: QSferaClient): RemoteOperationResult<String> {
if (targetRemotePath == sourceRemotePath && sourceSpaceWebDavUrl == targetSpaceWebDavUrl) {
// nothing to do!
return RemoteOperationResult(ResultCode.OK)
}
/// perform remote operation
var result: RemoteOperationResult<String>
try {
val copyMethod = CopyMethod(
url = URL((sourceSpaceWebDavUrl ?: client.userFilesWebDavUri.toString()) + WebdavUtils.encodePath(sourceRemotePath)),
destinationUrl = (targetSpaceWebDavUrl ?: client.userFilesWebDavUri.toString()) + WebdavUtils.encodePath(targetRemotePath),
forceOverride = forceOverride,
).apply {
addRequestHeaders(this)
setReadTimeout(COPY_READ_TIMEOUT, TimeUnit.SECONDS)
setConnectionTimeout(COPY_CONNECTION_TIMEOUT, TimeUnit.SECONDS)
}
val status = client.executeHttpMethod(copyMethod)
when {
isSuccess(status) -> {
val fileRemoteId = copyMethod.getResponseHeader(HttpConstants.OC_FILE_REMOTE_ID)
result = RemoteOperationResult(ResultCode.OK)
result.setData(fileRemoteId)
}
isPreconditionFailed(status) -> {
result = RemoteOperationResult(ResultCode.INVALID_OVERWRITE)
client.exhaustResponse(copyMethod.getResponseBodyAsStream())
/// for other errors that could be explicitly handled, check first:
/// http://www.webdav.org/specs/rfc4918.html#rfc.section.9.9.4
}
else -> {
result = RemoteOperationResult(copyMethod)
client.exhaustResponse(copyMethod.getResponseBodyAsStream())
}
}
Timber.i("Copy $sourceRemotePath to $targetRemotePath - HTTP status code: $status")
} catch (e: Exception) {
result = RemoteOperationResult(e)
Timber.e(e, "Copy $sourceRemotePath to $targetRemotePath: ${result.logMessage}")
}
return result
}
private fun addRequestHeaders(copyMethod: CopyMethod) {
//Adding this because the library has an error with override
if (copyMethod.forceOverride) {
copyMethod.setRequestHeader(OVERWRITE, TRUE)
}
}
private fun isSuccess(status: Int) = status.isOneOf(HttpConstants.HTTP_CREATED, HttpConstants.HTTP_NO_CONTENT)
private fun isPreconditionFailed(status: Int) = status == HttpConstants.HTTP_PRECONDITION_FAILED
companion object {
private const val COPY_READ_TIMEOUT = 10L
private const val COPY_CONNECTION_TIMEOUT = 6L
private const val OVERWRITE = "overwrite"
private const val TRUE = "T"
}
}
@@ -0,0 +1,110 @@
/* qsfera 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 eu.qsfera.android.lib.resources.files
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.webdav.MkColMethod
import eu.qsfera.android.lib.common.network.WebdavUtils
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.operations.RemoteOperationResult.ResultCode
import timber.log.Timber
import java.net.URL
import java.util.concurrent.TimeUnit
/**
* Remote operation performing the creation of a new folder in the qsfera server.
*
* @author David A. Velasco
* @author masensio
*
* @param remotePath Full path to the new directory to create in the remote server.
* @param createFullPath 'True' means that all the ancestor folders should be created.
*/
class CreateRemoteFolderOperation(
val remotePath: String,
private val createFullPath: Boolean,
private val isChunksFolder: Boolean = false,
val spaceWebDavUrl: String? = null,
) : RemoteOperation<Unit>() {
override fun run(client: QSferaClient): RemoteOperationResult<Unit> {
var result = createFolder(client)
if (!result.isSuccess && createFullPath && result.code == ResultCode.CONFLICT) {
result = createParentFolder(FileUtils.getParentPath(remotePath), client)
if (result.isSuccess) {
// Second and last try
result = createFolder(client)
}
}
return result
}
private fun createFolder(client: QSferaClient): RemoteOperationResult<Unit> {
var result: RemoteOperationResult<Unit>
try {
val webDavUri = if (isChunksFolder) {
client.uploadsWebDavUri.toString()
} else {
spaceWebDavUrl ?: client.userFilesWebDavUri.toString()
}
val mkCol = MkColMethod(
URL(webDavUri + WebdavUtils.encodePath(remotePath))
).apply {
setReadTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
setConnectionTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
}
val status = client.executeHttpMethod(mkCol)
result =
if (status == HttpConstants.HTTP_CREATED) {
RemoteOperationResult(ResultCode.OK)
} else {
RemoteOperationResult(mkCol)
}
Timber.d("Create directory $remotePath - HTTP status code: $status")
client.exhaustResponse(mkCol.getResponseBodyAsStream())
} catch (e: Exception) {
result = RemoteOperationResult(e)
Timber.e(e, "Create directory $remotePath: ${result.logMessage}")
}
return result
}
private fun createParentFolder(parentPath: String, client: QSferaClient): RemoteOperationResult<Unit> {
val operation: RemoteOperation<Unit> = CreateRemoteFolderOperation(parentPath, createFullPath)
return operation.execute(client)
}
companion object {
private const val READ_TIMEOUT: Long = 30_000
private const val CONNECTION_TIMEOUT: Long = 5_000
}
}
@@ -0,0 +1,195 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2024 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 eu.qsfera.android.lib.resources.files
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.nonwebdav.GetMethod
import eu.qsfera.android.lib.common.http.methods.webdav.DavConstants
import eu.qsfera.android.lib.common.http.methods.webdav.DavUtils
import eu.qsfera.android.lib.common.http.methods.webdav.PropfindMethod
import eu.qsfera.android.lib.common.network.OnDatatransferProgressListener
import eu.qsfera.android.lib.common.network.WebdavUtils
import eu.qsfera.android.lib.common.operations.OperationCancelledException
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import timber.log.Timber
import java.io.BufferedInputStream
import java.io.File
import java.io.FileOutputStream
import java.net.URL
import java.util.concurrent.atomic.AtomicBoolean
/**
* Remote operation performing the download of a remote file in the qsfera server.
*
* @author David A. Velasco
* @author masensio
*/
class DownloadRemoteFileOperation(
private val remotePath: String,
localFolderPath: String,
private val spaceWebDavUrl: String? = null,
) : RemoteOperation<Unit>() {
private val cancellationRequested = AtomicBoolean(false)
private val dataTransferListeners: MutableSet<OnDatatransferProgressListener> = HashSet()
var modificationTimestamp: Long = 0
private set
var etag: String = ""
private set
private val tmpPath: String = localFolderPath + remotePath
override fun run(client: QSferaClient): RemoteOperationResult<Unit> {
// download will be performed to a temporal file, then moved to the final location
val tmpFile = File(tmpPath)
val propfindMethod = PropfindMethod(
URL(client.userFilesWebDavUri.toString()),
DavConstants.DEPTH_1,
DavUtils.allPropSet
)
val status = client.executeHttpMethod(propfindMethod)
// perform the download
return try {
tmpFile.parentFile?.mkdirs()
downloadFile(client, tmpFile).also {
Timber.i("Download of $remotePath to $tmpPath - HTTP status code: $status")
}
} catch (e: Exception) {
RemoteOperationResult<Unit>(e).also { result ->
Timber.e(e, "Download of $remotePath to $tmpPath: ${result.logMessage}")
}
}
}
@Throws(Exception::class)
private fun downloadFile(client: QSferaClient, targetFile: File): RemoteOperationResult<Unit> {
val result: RemoteOperationResult<Unit>
var it: Iterator<OnDatatransferProgressListener>
var fos: FileOutputStream? = null
var bis: BufferedInputStream? = null
var savedFile = false
val webDavUri = spaceWebDavUrl ?: client.userFilesWebDavUri.toString()
val getMethod = GetMethod(URL(webDavUri + WebdavUtils.encodePath(remotePath)))
try {
val status = client.executeHttpMethod(getMethod)
if (isSuccess(status)) {
targetFile.createNewFile()
bis = BufferedInputStream(getMethod.getResponseBodyAsStream())
fos = FileOutputStream(targetFile)
var transferred: Long = 0
val contentLength = getMethod.getResponseHeader(HttpConstants.CONTENT_LENGTH_HEADER)
val totalToTransfer = if (!contentLength.isNullOrEmpty()) {
contentLength.toLong()
} else {
-1L
}
val bytes = ByteArray(4096)
var readResult: Int
while (bis.read(bytes).also { readResult = it } != -1) {
synchronized(cancellationRequested) {
if (cancellationRequested.get()) {
getMethod.abort()
throw OperationCancelledException()
}
}
fos.write(bytes, 0, readResult)
transferred += readResult.toLong()
synchronized(dataTransferListeners) {
it = dataTransferListeners.iterator()
while (it.hasNext()) {
it.next()
.onTransferProgress(readResult.toLong(), transferred, totalToTransfer, targetFile.name)
}
}
}
if (totalToTransfer == -1L || transferred == totalToTransfer) { // Check if the file is completed
savedFile = true
val modificationTime =
getMethod.getResponseHeaders()?.get("Last-Modified")
?: getMethod.getResponseHeader("last-modified")
if (modificationTime != null) {
val modificationDate = WebdavUtils.parseResponseDate(modificationTime)
modificationTimestamp = modificationDate?.time ?: 0
} else {
Timber.e("Could not read modification time from response downloading %s", remotePath)
}
etag = WebdavUtils.getEtagFromResponse(getMethod)
// Get rid of extra quotas
etag = etag.replace("\"", "")
if (etag.isEmpty()) {
Timber.e("Could not read eTag from response downloading %s", remotePath)
}
} else {
Timber.e("Content-Length not equal to transferred bytes.")
Timber.d("totalToTransfer = $totalToTransfer, transferred = $transferred")
client.exhaustResponse(getMethod.getResponseBodyAsStream())
// TODO some kind of error control!
}
} else if (status != HttpConstants.HTTP_FORBIDDEN && status != HttpConstants.HTTP_SERVICE_UNAVAILABLE) {
client.exhaustResponse(getMethod.getResponseBodyAsStream())
} // else, body read by RemoteOperationResult constructor
result =
if (isSuccess(status)) {
RemoteOperationResult(RemoteOperationResult.ResultCode.OK)
} else {
RemoteOperationResult(getMethod)
}
} finally {
fos?.close()
bis?.close()
if (!savedFile && targetFile.exists()) {
targetFile.delete()
}
}
return result
}
private fun isSuccess(status: Int) = status == HttpConstants.HTTP_OK
fun addDatatransferProgressListener(listener: OnDatatransferProgressListener) {
synchronized(dataTransferListeners) { dataTransferListeners.add(listener) }
}
fun removeDatatransferProgressListener(listener: OnDatatransferProgressListener?) {
synchronized(dataTransferListeners) { dataTransferListeners.remove(listener) }
}
fun cancel() {
cancellationRequested.set(true) // atomic set; there is no need of synchronizing it
}
}
@@ -0,0 +1,57 @@
/* qsfera 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 eu.qsfera.android.lib.resources.files;
import timber.log.Timber;
import java.io.File;
public class FileUtils {
public static final String FINAL_CHUNKS_FILE = ".file";
public static final String MIME_DIR = "DIR";
public static final String MIME_DIR_UNIX = "httpd/unix-directory";
public static final String MODE_READ_ONLY = "r";
static String getParentPath(String remotePath) {
String parentPath = new File(remotePath).getParent();
parentPath = parentPath.endsWith(File.separator) ? parentPath : parentPath + File.separator;
return parentPath;
}
/**
* Validate the fileName to detect if contains any forbidden character: / , \ , < , > ,
* : , " , | , ? , *
*
*/
public static boolean isValidName(String fileName) {
boolean result = true;
Timber.d("fileName =======%s", fileName);
if (fileName.contains(File.separator)) {
result = false;
}
return result;
}
}
@@ -0,0 +1,76 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2022 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 eu.qsfera.android.lib.resources.files
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.webdav.DavUtils
import eu.qsfera.android.lib.common.http.methods.webdav.PropfindMethod
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import timber.log.Timber
import java.net.URL
import java.util.concurrent.TimeUnit
/**
* Operation to get the base url, which might differ in case of a redirect.
*
* @author Christian Schabesberger
*/
class GetBaseUrlRemoteOperation : RemoteOperation<String?>() {
override fun run(client: QSferaClient): RemoteOperationResult<String?> =
try {
val stringUrl = client.baseFilesWebDavUri.toString()
val propFindMethod = PropfindMethod(URL(stringUrl), 0, DavUtils.allPropSet).apply {
setReadTimeout(TIMEOUT, TimeUnit.SECONDS)
setConnectionTimeout(TIMEOUT, TimeUnit.SECONDS)
}
val status = client.executeHttpMethod(propFindMethod)
if (isSuccess(status) || status == HttpConstants.HTTP_NOT_FOUND) { // A light user returns 404 (NOT FOUND)
RemoteOperationResult<String?>(RemoteOperationResult.ResultCode.OK).apply {
data = propFindMethod.getFinalUrl().toString()
}
} else {
RemoteOperationResult<String?>(propFindMethod).apply {
data = null
}
}
} catch (e: Exception) {
Timber.e(e, "Could not get actuall (or redirected) base URL from base url (/).")
RemoteOperationResult<String?>(e)
}
private fun isSuccess(status: Int) = status == HttpConstants.HTTP_OK || status == HttpConstants.HTTP_MULTI_STATUS
companion object {
/**
* Maximum time to wait for a response from the server in milliseconds.
*/
private const val TIMEOUT = 10_000L
}
}
@@ -0,0 +1,96 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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 eu.qsfera.android.lib.resources.files
import at.bitfire.dav4jvm.PropertyRegistry
import at.bitfire.dav4jvm.property.OCId
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.webdav.DavConstants
import eu.qsfera.android.lib.common.http.methods.webdav.PropfindMethod
import eu.qsfera.android.lib.common.http.methods.webdav.properties.OCFileId
import eu.qsfera.android.lib.common.http.methods.webdav.properties.OCMetaPathForUser
import eu.qsfera.android.lib.common.http.methods.webdav.properties.OCSpaceId
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import timber.log.Timber
import java.net.URL
import java.util.concurrent.TimeUnit
class GetRemoteMetaFileOperation(val fileId: String) : RemoteOperation<RemoteMetaFile>() {
override fun run(client: QSferaClient): RemoteOperationResult<RemoteMetaFile> {
PropertyRegistry.register(OCMetaPathForUser.Factory())
PropertyRegistry.register(OCFileId.Factory())
PropertyRegistry.register(OCSpaceId.Factory())
val stringUrl = "${client.baseUri}$META_PATH$fileId"
return try {
val propFindMethod =
PropfindMethod(URL(stringUrl), DavConstants.DEPTH_0,
arrayOf(OCMetaPathForUser.NAME, OCId.NAME, OCFileId.NAME, OCSpaceId.NAME)
).apply {
setReadTimeout(TIMEOUT, TimeUnit.SECONDS)
setConnectionTimeout(TIMEOUT, TimeUnit.SECONDS)
}
val status = client.executeHttpMethod(propFindMethod)
if (isSuccess(status)) RemoteOperationResult<RemoteMetaFile>(RemoteOperationResult.ResultCode.OK).apply {
val remoteMetaFile = RemoteMetaFile()
propFindMethod.root?.properties?.let { properties ->
properties.forEach { property ->
when (property) {
is OCMetaPathForUser -> {
remoteMetaFile.metaPathForUser = property.path
}
is OCId -> {
remoteMetaFile.id = property.id
}
is OCFileId -> {
remoteMetaFile.fileId = property.fileId
}
is OCSpaceId -> {
remoteMetaFile.spaceId = property.spaceId
}
}
}
}
data = remoteMetaFile
}
else RemoteOperationResult<RemoteMetaFile>(propFindMethod)
} catch (e: Exception) {
Timber.e(e, "Exception while getting remote meta file")
RemoteOperationResult<RemoteMetaFile>(e)
}
}
private fun isSuccess(status: Int) = status == HttpConstants.HTTP_OK || status == HttpConstants.HTTP_MULTI_STATUS
companion object {
private const val META_PATH = "/remote.php/dav/meta/"
private const val TIMEOUT = 10_000L
}
}
@@ -0,0 +1,146 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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 eu.qsfera.android.lib.resources.files
import android.net.Uri
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.webdav.MoveMethod
import eu.qsfera.android.lib.common.network.WebdavUtils
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.operations.RemoteOperationResult.ResultCode
import eu.qsfera.android.lib.common.utils.isOneOf
import timber.log.Timber
import java.net.URL
import java.util.concurrent.TimeUnit
/**
* Remote operation moving a remote file or folder in the qsfera server to a different folder
* in the same account and space.
*
* Allows renaming the moving file/folder at the same time.
*
* @author David A. Velasco
* @author David González Verdugo
* @author Abel García de Prada
* @author Juan Carlos Garrote Gascón
* @author Manuel Plazas Palacio
*
* @param sourceRemotePath Remote path of the file/folder to copy.
* @param targetRemotePath Remote path desired for the file/folder to copy it.
*/
open class MoveRemoteFileOperation(
private val sourceRemotePath: String,
private val targetRemotePath: String,
private val spaceWebDavUrl: String? = null,
private val forceOverride: Boolean = false,
) : RemoteOperation<Unit>() {
/**
* Performs the rename operation.
*
* @param client Client object to communicate with the remote qsfera server.
*/
override fun run(client: QSferaClient): RemoteOperationResult<Unit> =
if (targetRemotePath == sourceRemotePath) {
// nothing to do!
RemoteOperationResult(ResultCode.OK)
} else if (targetRemotePath.startsWith(sourceRemotePath)) {
RemoteOperationResult(ResultCode.INVALID_MOVE_INTO_DESCENDANT)
} else {
/// perform remote operation
var result: RemoteOperationResult<Unit>
try {
// After finishing a chunked upload, we have to move the resulting file from uploads folder to files one,
// so this uri has to be customizable
val srcWebDavUri = getSrcWebDavUriForClient(client)
val moveMethod = MoveMethod(
url = URL((spaceWebDavUrl ?: srcWebDavUri.toString()) + WebdavUtils.encodePath(sourceRemotePath)),
destinationUrl = (spaceWebDavUrl ?: client.userFilesWebDavUri.toString()) + WebdavUtils.encodePath(targetRemotePath),
forceOverride = forceOverride,
).apply {
addRequestHeaders(this)
setReadTimeout(MOVE_READ_TIMEOUT, TimeUnit.SECONDS)
setConnectionTimeout(MOVE_CONNECTION_TIMEOUT, TimeUnit.SECONDS)
}
val status = client.executeHttpMethod(moveMethod)
when {
isSuccess(status) -> {
result = RemoteOperationResult<Unit>(ResultCode.OK)
}
isPreconditionFailed(status) -> {
result = RemoteOperationResult<Unit>(ResultCode.INVALID_OVERWRITE)
client.exhaustResponse(moveMethod.getResponseBodyAsStream())
/// for other errors that could be explicitly handled, check first:
/// http://www.webdav.org/specs/rfc4918.html#rfc.section.9.9.4
}
else -> {
result = RemoteOperationResult<Unit>(moveMethod)
client.exhaustResponse(moveMethod.getResponseBodyAsStream())
}
}
Timber.i("Move $sourceRemotePath to $targetRemotePath - HTTP status code: $status")
} catch (e: Exception) {
result = RemoteOperationResult<Unit>(e)
Timber.e(e, "Move $sourceRemotePath to $targetRemotePath: ${result.logMessage}")
}
result
}
/**
* For standard moves, we will use [QSferaClient.getUserFilesWebDavUri].
* In case we need a different source Uri, override this method.
*/
open fun getSrcWebDavUriForClient(client: QSferaClient): Uri = client.userFilesWebDavUri
/**
* For standard moves, we won't need any special headers.
* In case new headers are needed, override this method
*/
open fun addRequestHeaders(moveMethod: MoveMethod) {
//Adding this because the library has an error with override
if (moveMethod.forceOverride) {
moveMethod.setRequestHeader(OVERWRITE, TRUE)
}
}
private fun isSuccess(status: Int) = status.isOneOf(HttpConstants.HTTP_CREATED, HttpConstants.HTTP_NO_CONTENT)
private fun isPreconditionFailed(status: Int) = status == HttpConstants.HTTP_PRECONDITION_FAILED
companion object {
private const val MOVE_READ_TIMEOUT = 10L
private const val MOVE_CONNECTION_TIMEOUT = 6L
private const val OVERWRITE = "overwrite"
private const val TRUE = "T"
}
}
@@ -0,0 +1,110 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2024 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 eu.qsfera.android.lib.resources.files
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.accounts.AccountUtils
import eu.qsfera.android.lib.common.http.HttpConstants.HTTP_MULTI_STATUS
import eu.qsfera.android.lib.common.http.HttpConstants.HTTP_OK
import eu.qsfera.android.lib.common.http.methods.webdav.DavConstants.DEPTH_0
import eu.qsfera.android.lib.common.http.methods.webdav.DavUtils
import eu.qsfera.android.lib.common.http.methods.webdav.PropfindMethod
import eu.qsfera.android.lib.common.network.WebdavUtils
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.utils.isOneOf
import timber.log.Timber
import java.net.URL
import java.util.concurrent.TimeUnit
/**
* Remote operation performing the read a file from the qsfera server.
*
* @author David A. Velasco
* @author masensio
* @author David González Verdugo
* @author Juan Carlos Garrote Gascón
*/
class ReadRemoteFileOperation(
val remotePath: String,
val spaceWebDavUrl: String? = null,
) : RemoteOperation<RemoteFile>() {
/**
* Performs the read operation.
*
* @param client Client object to communicate with the remote qsfera server.
*/
override fun run(client: QSferaClient): RemoteOperationResult<RemoteFile> {
try {
if (client.account == null) {
throw AccountUtils.AccountNotFoundException()
}
val propFind = PropfindMethod(
url = getFinalWebDavUrl(),
depth = DEPTH_0,
propertiesToRequest = DavUtils.allPropSet
).apply {
setReadTimeout(SYNC_READ_TIMEOUT, TimeUnit.SECONDS)
setConnectionTimeout(SYNC_CONNECTION_TIMEOUT, TimeUnit.SECONDS)
}
val status = client.executeHttpMethod(propFind)
Timber.i("Read remote file $remotePath with status ${propFind.statusCode}")
return if (isSuccess(status)) {
val remoteFile = RemoteFile.getRemoteFileFromDav(
davResource = propFind.root!!,
userId = AccountUtils.getUserId(mAccount, mContext),
userName = mAccount.name,
spaceWebDavUrl = spaceWebDavUrl,
)
RemoteOperationResult<RemoteFile>(RemoteOperationResult.ResultCode.OK).apply {
data = remoteFile
}
} else {
RemoteOperationResult<RemoteFile>(propFind).also {
client.exhaustResponse(propFind.getResponseBodyAsStream())
}
}
} catch (exception: Exception) {
return RemoteOperationResult(exception)
}
}
private fun getFinalWebDavUrl(): URL {
val baseWebDavUrl = spaceWebDavUrl ?: client.userFilesWebDavUri.toString()
return URL(baseWebDavUrl + WebdavUtils.encodePath(remotePath))
}
private fun isSuccess(status: Int) = status.isOneOf(HTTP_MULTI_STATUS, HTTP_OK)
companion object {
private const val SYNC_READ_TIMEOUT = 40_000L
private const val SYNC_CONNECTION_TIMEOUT = 5_000L
}
}
@@ -0,0 +1,118 @@
/* qsfera 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 eu.qsfera.android.lib.resources.files
import at.bitfire.dav4jvm.PropertyRegistry
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.accounts.AccountUtils
import eu.qsfera.android.lib.common.http.HttpConstants.HTTP_MULTI_STATUS
import eu.qsfera.android.lib.common.http.HttpConstants.HTTP_OK
import eu.qsfera.android.lib.common.http.methods.webdav.DavConstants
import eu.qsfera.android.lib.common.http.methods.webdav.DavUtils
import eu.qsfera.android.lib.common.http.methods.webdav.PropfindMethod
import eu.qsfera.android.lib.common.http.methods.webdav.properties.OCShareTypes
import eu.qsfera.android.lib.common.network.WebdavUtils
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.operations.RemoteOperationResult.ResultCode
import eu.qsfera.android.lib.common.utils.isOneOf
import timber.log.Timber
import java.net.URL
/**
* Remote operation performing the read of remote file or folder in the qsfera server.
*
* @author David A. Velasco
* @author masensio
* @author David González Verdugo
*/
class ReadRemoteFolderOperation(
val remotePath: String,
val spaceWebDavUrl: String? = null,
) : RemoteOperation<ArrayList<RemoteFile>>() {
/**
* Performs the read operation.
*
* @param client Client object to communicate with the remote qsfera server.
*/
override fun run(client: QSferaClient): RemoteOperationResult<ArrayList<RemoteFile>> {
try {
PropertyRegistry.register(OCShareTypes.Factory())
val propfindMethod = PropfindMethod(
getFinalWebDavUrl(),
DavConstants.DEPTH_1,
DavUtils.allPropSet
)
val status = client.executeHttpMethod(propfindMethod)
return if (isSuccess(status)) {
val mFolderAndFiles = ArrayList<RemoteFile>()
val remoteFolder = RemoteFile.getRemoteFileFromDav(
davResource = propfindMethod.root!!,
userId = AccountUtils.getUserId(mAccount, mContext),
userName = mAccount.name,
spaceWebDavUrl = spaceWebDavUrl,
)
mFolderAndFiles.add(remoteFolder)
// loop to update every child
propfindMethod.members.forEach { resource ->
val remoteFile = RemoteFile.getRemoteFileFromDav(
davResource = resource,
userId = AccountUtils.getUserId(mAccount, mContext),
userName = mAccount.name,
spaceWebDavUrl = spaceWebDavUrl,
)
mFolderAndFiles.add(remoteFile)
}
// Result of the operation
RemoteOperationResult<ArrayList<RemoteFile>>(ResultCode.OK).apply {
data = mFolderAndFiles
Timber.i("Synchronized $remotePath with ${mFolderAndFiles.size} files. - HTTP status code: $status")
}
} else { // synchronization failed
RemoteOperationResult<ArrayList<RemoteFile>>(propfindMethod).also {
Timber.w("Synchronized $remotePath ${it.logMessage}")
}
}
} catch (e: Exception) {
return RemoteOperationResult<ArrayList<RemoteFile>>(e).also {
Timber.e(it.exception, "Synchronized $remotePath")
}
}
}
private fun getFinalWebDavUrl(): URL {
val baseWebDavUrl = spaceWebDavUrl ?: client.userFilesWebDavUri.toString()
return URL(baseWebDavUrl + WebdavUtils.encodePath(remotePath))
}
private fun isSuccess(status: Int): Boolean = status.isOneOf(HTTP_OK, HTTP_MULTI_STATUS)
}
@@ -0,0 +1,196 @@
/* qsfera 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 eu.qsfera.android.lib.resources.files
import android.os.Parcelable
import androidx.annotation.VisibleForTesting
import at.bitfire.dav4jvm.PropStat
import at.bitfire.dav4jvm.Property
import at.bitfire.dav4jvm.Response
import at.bitfire.dav4jvm.property.CreationDate
import at.bitfire.dav4jvm.property.GetContentLength
import at.bitfire.dav4jvm.property.GetContentType
import at.bitfire.dav4jvm.property.GetETag
import at.bitfire.dav4jvm.property.GetLastModified
import at.bitfire.dav4jvm.property.OCId
import at.bitfire.dav4jvm.property.OCPermissions
import at.bitfire.dav4jvm.property.OCPrivatelink
import at.bitfire.dav4jvm.property.OCSize
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.webdav.properties.OCShareTypes
import eu.qsfera.android.lib.common.utils.isOneOf
import eu.qsfera.android.lib.resources.shares.ShareType
import eu.qsfera.android.lib.resources.shares.ShareType.Companion.fromValue
import kotlinx.parcelize.Parcelize
import okhttp3.HttpUrl
import timber.log.Timber
import java.net.URLDecoder
import java.nio.charset.StandardCharsets
/**
* Contains the data of a Remote File from a WebDavEntry
*
* The path received must be URL-decoded. Path separator must be File.separator, and it must be the first character in 'path'.
*
* @author masensio
* @author Christian Schabesberger
* @author Abel García de Prada
*/
@Parcelize
data class RemoteFile(
var remotePath: String,
var mimeType: String = "DIR",
var length: Long = 0,
var creationTimestamp: Long = 0,
var modifiedTimestamp: Long = 0,
var etag: String? = null,
var permissions: String? = null,
var remoteId: String? = null,
var size: Long = 0,
var privateLink: String? = null,
var owner: String,
var sharedByLink: Boolean = false,
var sharedWithSharee: Boolean = false,
) : Parcelable {
// To do: Quotas not used. Use or remove them.
// init {
// require(
// !(remotePath.isEmpty() || !remotePath.startsWith("/"))
// ) { "Trying to create a OCFile with a non valid remote path: $remotePath" }
// }
/**
* Use this to find out if this file is a folder.
*
* @return true if it is a folder
*/
val isFolder
get() = mimeType.isOneOf(MIME_DIR, MIME_DIR_UNIX)
companion object {
const val MIME_DIR = "DIR"
const val MIME_DIR_UNIX = "httpd/unix-directory"
fun getRemoteFileFromDav(
davResource: Response,
userId: String,
userName: String,
spaceWebDavUrl: String? = null
): RemoteFile {
val remotePath = getRemotePathFromUrl(davResource.href, userId, spaceWebDavUrl)
val remoteFile = RemoteFile(remotePath = remotePath, owner = userName)
val properties = getPropertiesEvenIfPostProcessing(davResource)
for (property in properties) {
when (property) {
is CreationDate -> {
remoteFile.creationTimestamp = property.creationDate.toLong()
}
is GetContentLength -> {
remoteFile.length = property.contentLength
}
is GetContentType -> {
property.type?.let { remoteFile.mimeType = it }
}
is GetLastModified -> {
remoteFile.modifiedTimestamp = property.lastModified
}
is GetETag -> {
remoteFile.etag = property.eTag
}
is OCPermissions -> {
remoteFile.permissions = property.permission
}
is OCId -> {
remoteFile.remoteId = property.id
}
is OCSize -> {
remoteFile.size = property.size
}
is OCPrivatelink -> {
remoteFile.privateLink = property.link
}
is OCShareTypes -> {
val list = property.shareTypes
for (i in list.indices) {
val shareType = fromValue(list[i].toInt())
if (shareType == null) {
Timber.d("Illegal share type value: " + list[i])
continue
}
if (shareType == ShareType.PUBLIC_LINK) {
remoteFile.sharedByLink = true
} else if (shareType == ShareType.USER || shareType == ShareType.FEDERATED || shareType == ShareType.GROUP) {
remoteFile.sharedWithSharee = true
}
}
}
}
}
return remoteFile
}
/**
* Retrieves a relative path from a remote file url
*
*
* Example legacy:
* /remote.php/dav/files/username/Documents/text.txt => /Documents/text.txt
*
* Example spaces:
* /dav/spaces/8871f4f3-fc6f-4a66-8bed-62f175f76f38$05bca744-d89f-4e9c-a990-25a0d7f03fe9/Documents/text.txt => /Documents/text.txt
*
* @param url remote file url
* @param userId file owner
* @param spaceWebDavUrl custom web dav url for space
* @return remote relative path of the file
*/
@VisibleForTesting
fun getRemotePathFromUrl(
url: HttpUrl,
userId: String,
spaceWebDavUrl: String? = null,
): String {
val davFilesPath = spaceWebDavUrl ?: ("/remote.php/dav/files/" + userId)
val absoluteDavPath = if (spaceWebDavUrl != null) {
URLDecoder.decode(url.toString(), StandardCharsets.UTF_8.name())
} else {
URLDecoder.decode(url.encodedPath, StandardCharsets.UTF_8.name())
}
val pathToOc = absoluteDavPath.split(davFilesPath).first()
return absoluteDavPath.replace(pathToOc + davFilesPath, "")
}
private fun getPropertiesEvenIfPostProcessing(response: Response): List<Property> =
if (response.isSuccess())
response.propstat.filter { propStat -> propStat.isSuccessOrPostProcessing() }.map { it.properties }.flatten()
else
emptyList()
private fun PropStat.isSuccessOrPostProcessing() = (status.code / 100 == 2 || status.code == HttpConstants.HTTP_TOO_EARLY)
}
}
@@ -0,0 +1,31 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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 eu.qsfera.android.lib.resources.files
data class RemoteMetaFile(
var metaPathForUser: String? = "",
var id: String? = null,
var fileId: String? = null,
var spaceId: String? = null,
)
@@ -0,0 +1,81 @@
/* qsfera 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 eu.qsfera.android.lib.resources.files
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants.HTTP_NO_CONTENT
import eu.qsfera.android.lib.common.http.HttpConstants.HTTP_OK
import eu.qsfera.android.lib.common.http.methods.nonwebdav.DeleteMethod
import eu.qsfera.android.lib.common.network.WebdavUtils
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.operations.RemoteOperationResult.ResultCode
import eu.qsfera.android.lib.common.utils.isOneOf
import timber.log.Timber
import java.net.URL
/**
* Remote operation performing the removal of a remote file or folder in the qsfera server.
*
* @author David A. Velasco
* @author masensio
* @author David González Verdugo
* @author Abel García de Prada
*/
open class RemoveRemoteFileOperation(
private val remotePath: String,
val spaceWebDavUrl: String? = null,
) : RemoteOperation<Unit>() {
override fun run(client: QSferaClient): RemoteOperationResult<Unit> {
var result: RemoteOperationResult<Unit>
try {
val srcWebDavUri = getSrcWebDavUriForClient(client)
val deleteMethod = DeleteMethod(
URL(srcWebDavUri + WebdavUtils.encodePath(remotePath))
)
val status = client.executeHttpMethod(deleteMethod)
result = if (isSuccess(status)) {
RemoteOperationResult<Unit>(ResultCode.OK)
} else {
RemoteOperationResult<Unit>(deleteMethod)
}
Timber.i("Remove $remotePath - HTTP status code: $status")
} catch (e: Exception) {
result = RemoteOperationResult<Unit>(e)
Timber.e(e, "Remove $remotePath: ${result.logMessage}")
}
return result
}
/**
* For standard removals, we will use [QSferaClient.getUserFilesWebDavUri].
* In case we need a different source Uri, override this method.
*/
open fun getSrcWebDavUriForClient(client: QSferaClient): String = spaceWebDavUrl ?: client.userFilesWebDavUri.toString()
private fun isSuccess(status: Int) = status.isOneOf(HTTP_OK, HTTP_NO_CONTENT)
}
@@ -0,0 +1,118 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2021 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 eu.qsfera.android.lib.resources.files
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.webdav.MoveMethod
import eu.qsfera.android.lib.common.network.WebdavUtils
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.operations.RemoteOperationResult.ResultCode
import eu.qsfera.android.lib.common.utils.isOneOf
import timber.log.Timber
import java.io.File
import java.net.URL
import java.util.concurrent.TimeUnit
/**
* Remote operation performing the rename of a remote file or folder in the qsfera server.
*
* @author David A. Velasco
* @author masensio
*/
class RenameRemoteFileOperation(
private val oldName: String,
private val oldRemotePath: String,
private val newName: String,
isFolder: Boolean,
val spaceWebDavUrl: String? = null,
) : RemoteOperation<Unit>() {
private var newRemotePath: String
init {
var parent = (File(oldRemotePath)).parent ?: throw IllegalArgumentException("Parent path is null")
if (!parent.endsWith(File.separator)) {
parent = parent.plus(File.separator)
}
newRemotePath = parent.plus(newName)
if (isFolder) {
newRemotePath.plus(File.separator)
}
}
override fun run(client: QSferaClient): RemoteOperationResult<Unit> {
var result: RemoteOperationResult<Unit>
return try {
if (newName == oldName) {
RemoteOperationResult<Unit>(ResultCode.OK)
} else if (targetPathIsUsed(client)) {
RemoteOperationResult<Unit>(ResultCode.INVALID_OVERWRITE)
} else {
val moveMethod: MoveMethod = MoveMethod(
url = URL((spaceWebDavUrl ?: client.userFilesWebDavUri.toString()) + WebdavUtils.encodePath(oldRemotePath)),
destinationUrl = (spaceWebDavUrl ?: client.userFilesWebDavUri.toString()) + WebdavUtils.encodePath(newRemotePath),
).apply {
setReadTimeout(RENAME_READ_TIMEOUT, TimeUnit.MILLISECONDS)
setConnectionTimeout(RENAME_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
}
val status = client.executeHttpMethod(moveMethod)
result = if (isSuccess(status)) {
RemoteOperationResult<Unit>(ResultCode.OK)
} else {
RemoteOperationResult<Unit>(moveMethod)
}
Timber.i("Rename $oldRemotePath to $newRemotePath - HTTP status code: $status")
client.exhaustResponse(moveMethod.getResponseBodyAsStream())
result
}
} catch (exception: Exception) {
result = RemoteOperationResult<Unit>(exception)
Timber.e(exception, "Rename $oldRemotePath to $newName: ${result.logMessage}")
result
}
}
/**
* Checks if a file with the new name already exists.
*
* @return 'True' if the target path is already used by an existing file.
*/
private fun targetPathIsUsed(client: QSferaClient): Boolean {
val checkPathExistenceRemoteOperation = CheckPathExistenceRemoteOperation(newRemotePath, true)
val exists = checkPathExistenceRemoteOperation.execute(client)
return exists.isSuccess
}
private fun isSuccess(status: Int) = status.isOneOf(HttpConstants.HTTP_CREATED, HttpConstants.HTTP_NO_CONTENT)
companion object {
private const val RENAME_READ_TIMEOUT = 10_000L
private const val RENAME_CONNECTION_TIMEOUT = 5_000L
}
}
@@ -0,0 +1,67 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2022 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 eu.qsfera.android.lib.resources.files
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.webdav.PutMethod
import eu.qsfera.android.lib.common.network.ContentUriRequestBody
import eu.qsfera.android.lib.common.network.WebdavUtils
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.utils.isOneOf
import timber.log.Timber
import java.net.URL
class UploadFileFromContentUriOperation(
private val uploadPath: String,
private val lastModified: String,
private val requestBody: ContentUriRequestBody
) : RemoteOperation<Unit>() {
override fun run(client: QSferaClient): RemoteOperationResult<Unit> {
val putMethod = PutMethod(URL(client.userFilesWebDavUri.toString() + WebdavUtils.encodePath(uploadPath)), requestBody).apply {
retryOnConnectionFailure = false
addRequestHeader(HttpConstants.OC_TOTAL_LENGTH_HEADER, requestBody.contentLength().toString())
addRequestHeader(HttpConstants.OC_X_OC_MTIME_HEADER, lastModified)
}
return try {
val status = client.executeHttpMethod(putMethod)
if (isSuccess(status)) {
RemoteOperationResult<Unit>(RemoteOperationResult.ResultCode.OK).apply { data = Unit }
} else {
RemoteOperationResult<Unit>(putMethod)
}
} catch (e: Exception) {
val result = RemoteOperationResult<Unit>(e)
Timber.e(e, "Upload from content uri failed : ${result.logMessage}")
result
}
}
fun isSuccess(status: Int): Boolean =
status.isOneOf(HttpConstants.HTTP_OK, HttpConstants.HTTP_CREATED, HttpConstants.HTTP_NO_CONTENT)
}
@@ -0,0 +1,157 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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
* NONINFINGEMENT. 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 eu.qsfera.android.lib.resources.files
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.webdav.DavConstants
import eu.qsfera.android.lib.common.http.methods.webdav.DavUtils
import eu.qsfera.android.lib.common.http.methods.webdav.PropfindMethod
import eu.qsfera.android.lib.common.http.methods.webdav.PutMethod
import eu.qsfera.android.lib.common.network.FileRequestBody
import eu.qsfera.android.lib.common.network.OnDatatransferProgressListener
import eu.qsfera.android.lib.common.network.WebdavUtils
import eu.qsfera.android.lib.common.operations.OperationCancelledException
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.operations.RemoteOperationResult.ResultCode
import eu.qsfera.android.lib.common.utils.isOneOf
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import timber.log.Timber
import java.io.File
import java.net.URL
import java.util.concurrent.atomic.AtomicBoolean
/**
* Remote operation performing the upload of a remote file to the qsfera server.
*
* @author David A. Velasco
* @author masensio
* @author David González Verdugo
* @author Abel García de Prada
* @author Juan Carlos Garrote Gascón
*/
open class UploadFileFromFileSystemOperation(
val localPath: String,
val remotePath: String,
val mimeType: String,
val lastModifiedTimestamp: String,
val requiredEtag: String?,
val spaceWebDavUrl: String? = null,
) : RemoteOperation<Unit>() {
protected val cancellationRequested = AtomicBoolean(false)
protected var putMethod: PutMethod? = null
protected val dataTransferListener: MutableSet<OnDatatransferProgressListener> = HashSet()
protected var fileRequestBody: FileRequestBody? = null
var etag: String = ""
override fun run(client: QSferaClient): RemoteOperationResult<Unit> {
var result: RemoteOperationResult<Unit>
try {
val propfindMethod = PropfindMethod(
URL(client.userFilesWebDavUri.toString()),
DavConstants.DEPTH_1,
DavUtils.allPropSet
)
val status = client.executeHttpMethod(propfindMethod)
if (cancellationRequested.get()) {
// the operation was cancelled before getting it's turn to be executed in the queue of uploads
result = RemoteOperationResult<Unit>(OperationCancelledException())
Timber.i("Upload of $localPath to $remotePath has been cancelled")
} else {
// perform the upload
result = uploadFile(client)
Timber.i("Upload of $localPath to $remotePath - HTTP status code: $status")
}
} catch (e: Exception) {
if (putMethod?.isAborted == true) {
result = RemoteOperationResult<Unit>(OperationCancelledException())
Timber.e(result.exception, "Upload of $localPath to $remotePath has been aborted with this message: ${result.logMessage}")
} else {
result = RemoteOperationResult<Unit>(e)
Timber.e(result.exception, "Upload of $localPath to $remotePath has failed with this message: ${result.logMessage}")
}
}
return result
}
@Throws(Exception::class)
protected open fun uploadFile(client: QSferaClient): RemoteOperationResult<Unit> {
val fileToUpload = File(localPath)
val mediaType: MediaType? = mimeType.toMediaTypeOrNull()
fileRequestBody = FileRequestBody(fileToUpload, mediaType).also {
synchronized(dataTransferListener) { it.addDatatransferProgressListeners(dataTransferListener) }
}
val baseStringUrl = spaceWebDavUrl ?: client.userFilesWebDavUri.toString()
putMethod = PutMethod(URL(baseStringUrl + WebdavUtils.encodePath(remotePath)), fileRequestBody!!).apply {
retryOnConnectionFailure = false
if (!requiredEtag.isNullOrBlank()) {
addRequestHeader(HttpConstants.IF_MATCH_HEADER, requiredEtag)
}
addRequestHeader(HttpConstants.OC_TOTAL_LENGTH_HEADER, fileToUpload.length().toString())
addRequestHeader(HttpConstants.OC_X_OC_MTIME_HEADER, lastModifiedTimestamp)
}
val status = client.executeHttpMethod(putMethod)
return if (isSuccess(status)) {
etag = WebdavUtils.getEtagFromResponse(putMethod)
// Get rid of extra quotas
etag = etag.replace("\"", "")
if (etag.isEmpty()) {
Timber.e("Could not read eTag from response uploading %s", localPath)
} else {
Timber.d("File uploaded successfully. New etag for file ${fileToUpload.name} is $etag")
}
RemoteOperationResult<Unit>(ResultCode.OK).apply { data = Unit }
} else { // synchronization failed
RemoteOperationResult<Unit>(putMethod)
}
}
fun addDataTransferProgressListener(listener: OnDatatransferProgressListener) {
synchronized(dataTransferListener) { dataTransferListener.add(listener) }
fileRequestBody?.addDatatransferProgressListener(listener)
}
fun removeDataTransferProgressListener(listener: OnDatatransferProgressListener) {
synchronized(dataTransferListener) { dataTransferListener.remove(listener) }
fileRequestBody?.removeDatatransferProgressListener(listener)
}
fun cancel() {
synchronized(cancellationRequested) {
cancellationRequested.set(true)
putMethod?.abort()
}
}
fun isSuccess(status: Int): Boolean =
status.isOneOf(HttpConstants.HTTP_OK, HttpConstants.HTTP_CREATED, HttpConstants.HTTP_NO_CONTENT)
}
@@ -0,0 +1,122 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2022 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 eu.qsfera.android.lib.resources.files.chunks
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.methods.webdav.PutMethod
import eu.qsfera.android.lib.common.network.ChunkFromFileRequestBody
import eu.qsfera.android.lib.common.operations.OperationCancelledException
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.operations.RemoteOperationResult.ResultCode
import eu.qsfera.android.lib.resources.files.FileUtils.MODE_READ_ONLY
import eu.qsfera.android.lib.resources.files.UploadFileFromFileSystemOperation
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import timber.log.Timber
import java.io.File
import java.io.RandomAccessFile
import java.net.URL
import java.nio.channels.FileChannel
import java.util.concurrent.TimeUnit
import kotlin.math.ceil
/**
* Remote operation performing the chunked upload of a remote file to the qsfera server.
*
* @author David A. Velasco
* @author David González Verdugo
* @author Abel García de Prada
*/
class ChunkedUploadFromFileSystemOperation(
private val transferId: String,
localPath: String,
remotePath: String,
mimeType: String,
lastModifiedTimestamp: String,
requiredEtag: String?,
) : UploadFileFromFileSystemOperation(
localPath = localPath,
remotePath = remotePath,
mimeType = mimeType,
lastModifiedTimestamp = lastModifiedTimestamp,
requiredEtag = requiredEtag
) {
@Throws(Exception::class)
override fun uploadFile(client: QSferaClient): RemoteOperationResult<Unit> {
lateinit var result: RemoteOperationResult<Unit>
val fileToUpload = File(localPath)
val mediaType: MediaType? = mimeType.toMediaTypeOrNull()
val raf = RandomAccessFile(fileToUpload, MODE_READ_ONLY)
val channel: FileChannel = raf.channel
val fileRequestBody = ChunkFromFileRequestBody(fileToUpload, mediaType, channel).also {
synchronized(dataTransferListener) { it.addDatatransferProgressListeners(dataTransferListener) }
}
val uriPrefix = client.uploadsWebDavUri.toString() + File.separator + transferId
val totalLength = fileToUpload.length()
val chunkCount = ceil(totalLength.toDouble() / CHUNK_SIZE).toLong()
var offset: Long = 0
for (chunkIndex in 0..chunkCount) {
fileRequestBody.setOffset(offset)
if (cancellationRequested.get()) {
result = RemoteOperationResult<Unit>(OperationCancelledException())
break
} else {
putMethod = PutMethod(URL(uriPrefix + File.separator + chunkIndex), fileRequestBody).apply {
if (chunkIndex == chunkCount - 1) {
// Added a high timeout to the last chunk due to when the last chunk
// arrives to the server with the last PUT, all chunks get assembled
// within that PHP request, so last one takes longer.
setReadTimeout(LAST_CHUNK_TIMEOUT.toLong(), TimeUnit.MILLISECONDS)
}
}
val status = client.executeHttpMethod(putMethod)
Timber.d("Upload of $localPath to $remotePath, chunk index $chunkIndex, count $chunkCount, HTTP result status $status")
if (isSuccess(status)) {
result = RemoteOperationResult<Unit>(ResultCode.OK)
} else {
result = RemoteOperationResult<Unit>(putMethod)
break
}
}
offset += CHUNK_SIZE
}
channel.close()
raf.close()
return result
}
companion object {
const val CHUNK_SIZE = 10_240_000L // 10 MB
private const val LAST_CHUNK_TIMEOUT = 900_000 // 15 mins.
}
}
@@ -0,0 +1,58 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2021 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 eu.qsfera.android.lib.resources.files.chunks
import android.net.Uri
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.webdav.MoveMethod
import eu.qsfera.android.lib.resources.files.MoveRemoteFileOperation
/**
* Remote operation to move the file built from chunks after uploading it
*
* @author David González Verdugo
* @author Abel García de Prada
*/
class MoveRemoteChunksFileOperation(
sourceRemotePath: String,
targetRemotePath: String,
private val fileLastModificationTimestamp: String,
private val fileLength: Long
) : MoveRemoteFileOperation(
sourceRemotePath = sourceRemotePath,
targetRemotePath = targetRemotePath,
) {
override fun getSrcWebDavUriForClient(client: QSferaClient): Uri = client.uploadsWebDavUri
override fun addRequestHeaders(moveMethod: MoveMethod) {
super.addRequestHeaders(moveMethod)
moveMethod.apply {
addRequestHeader(HttpConstants.OC_X_OC_MTIME_HEADER, fileLastModificationTimestamp)
addRequestHeader(HttpConstants.OC_TOTAL_LENGTH_HEADER, fileLength.toString())
}
}
}
@@ -0,0 +1,32 @@
/* qsfera Android Library is available under MIT license
* @author David González Verdugo
* 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 eu.qsfera.android.lib.resources.files.chunks
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.resources.files.RemoveRemoteFileOperation
class RemoveRemoteChunksFolderOperation(remotePath: String) : RemoveRemoteFileOperation(remotePath) {
override fun getSrcWebDavUriForClient(client: QSferaClient): String = client.uploadsWebDavUri.toString()
}
@@ -0,0 +1,41 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2021 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 eu.qsfera.android.lib.resources.files.services
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.resources.Service
interface ChunkService : Service {
fun removeFile(
remotePath: String
): RemoteOperationResult<Unit>
fun moveFile(
sourceRemotePath: String,
targetRemotePath: String,
fileLastModificationTimestamp: String,
fileLength: Long
): RemoteOperationResult<Unit>
}
@@ -0,0 +1,92 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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 eu.qsfera.android.lib.resources.files.services
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.resources.Service
import eu.qsfera.android.lib.resources.files.RemoteFile
import eu.qsfera.android.lib.resources.files.RemoteMetaFile
interface FileService : Service {
fun checkPathExistence(
path: String,
isUserLogged: Boolean,
spaceWebDavUrl: String? = null,
): RemoteOperationResult<Boolean>
fun copyFile(
sourceRemotePath: String,
targetRemotePath: String,
sourceSpaceWebDavUrl: String?,
targetSpaceWebDavUrl: String?,
replace: Boolean,
): RemoteOperationResult<String?>
fun createFolder(
remotePath: String,
createFullPath: Boolean,
isChunkFolder: Boolean = false,
spaceWebDavUrl: String? = null,
): RemoteOperationResult<Unit>
fun downloadFile(
remotePath: String,
localTempPath: String
): RemoteOperationResult<Unit>
fun moveFile(
sourceRemotePath: String,
targetRemotePath: String,
spaceWebDavUrl: String?,
replace: Boolean,
): RemoteOperationResult<Unit>
fun readFile(
remotePath: String,
spaceWebDavUrl: String? = null,
): RemoteOperationResult<RemoteFile>
fun refreshFolder(
remotePath: String,
spaceWebDavUrl: String? = null,
): RemoteOperationResult<ArrayList<RemoteFile>>
fun removeFile(
remotePath: String,
spaceWebDavUrl: String? = null,
): RemoteOperationResult<Unit>
fun renameFile(
oldName: String,
oldRemotePath: String,
newName: String,
isFolder: Boolean,
spaceWebDavUrl: String? = null,
): RemoteOperationResult<Unit>
fun getMetaFileInfo(
fileId: String,
): RemoteOperationResult<RemoteMetaFile>
}
@@ -0,0 +1,50 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2021 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 eu.qsfera.android.lib.resources.files.services.implementation
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.resources.files.chunks.MoveRemoteChunksFileOperation
import eu.qsfera.android.lib.resources.files.chunks.RemoveRemoteChunksFolderOperation
import eu.qsfera.android.lib.resources.files.services.ChunkService
class OCChunkService(override val client: QSferaClient) : ChunkService {
override fun removeFile(remotePath: String): RemoteOperationResult<Unit> =
RemoveRemoteChunksFolderOperation(remotePath = remotePath).execute(client)
override fun moveFile(
sourceRemotePath: String,
targetRemotePath: String,
fileLastModificationTimestamp: String,
fileLength: Long
): RemoteOperationResult<Unit> =
MoveRemoteChunksFileOperation(
sourceRemotePath = sourceRemotePath,
targetRemotePath = targetRemotePath,
fileLastModificationTimestamp = fileLastModificationTimestamp,
fileLength = fileLength,
).execute(client)
}
@@ -0,0 +1,150 @@
/* qsfera Android Library is available under MIT license
* Copyright (C) 2023 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 eu.qsfera.android.lib.resources.files.services.implementation
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.resources.files.CheckPathExistenceRemoteOperation
import eu.qsfera.android.lib.resources.files.CopyRemoteFileOperation
import eu.qsfera.android.lib.resources.files.CreateRemoteFolderOperation
import eu.qsfera.android.lib.resources.files.DownloadRemoteFileOperation
import eu.qsfera.android.lib.resources.files.GetRemoteMetaFileOperation
import eu.qsfera.android.lib.resources.files.MoveRemoteFileOperation
import eu.qsfera.android.lib.resources.files.ReadRemoteFileOperation
import eu.qsfera.android.lib.resources.files.ReadRemoteFolderOperation
import eu.qsfera.android.lib.resources.files.RemoteFile
import eu.qsfera.android.lib.resources.files.RemoteMetaFile
import eu.qsfera.android.lib.resources.files.RemoveRemoteFileOperation
import eu.qsfera.android.lib.resources.files.RenameRemoteFileOperation
import eu.qsfera.android.lib.resources.files.services.FileService
class OCFileService(override val client: QSferaClient) : FileService {
override fun checkPathExistence(
path: String,
isUserLogged: Boolean,
spaceWebDavUrl: String?,
): RemoteOperationResult<Boolean> =
CheckPathExistenceRemoteOperation(
remotePath = path,
isUserLoggedIn = isUserLogged,
spaceWebDavUrl = spaceWebDavUrl,
).execute(client)
override fun copyFile(
sourceRemotePath: String,
targetRemotePath: String,
sourceSpaceWebDavUrl: String?,
targetSpaceWebDavUrl: String?,
replace: Boolean,
): RemoteOperationResult<String?> =
CopyRemoteFileOperation(
sourceRemotePath = sourceRemotePath,
targetRemotePath = targetRemotePath,
sourceSpaceWebDavUrl = sourceSpaceWebDavUrl,
targetSpaceWebDavUrl = targetSpaceWebDavUrl,
forceOverride = replace,
).execute(client)
override fun createFolder(
remotePath: String,
createFullPath: Boolean,
isChunkFolder: Boolean,
spaceWebDavUrl: String?,
): RemoteOperationResult<Unit> =
CreateRemoteFolderOperation(
remotePath = remotePath,
createFullPath = createFullPath,
isChunksFolder = isChunkFolder,
spaceWebDavUrl = spaceWebDavUrl,
).execute(client)
override fun downloadFile(
remotePath: String,
localTempPath: String
): RemoteOperationResult<Unit> =
DownloadRemoteFileOperation(
remotePath = remotePath,
localFolderPath = localTempPath
).execute(client)
override fun moveFile(
sourceRemotePath: String,
targetRemotePath: String,
spaceWebDavUrl: String?,
replace: Boolean,
): RemoteOperationResult<Unit> =
MoveRemoteFileOperation(
sourceRemotePath = sourceRemotePath,
targetRemotePath = targetRemotePath,
spaceWebDavUrl = spaceWebDavUrl,
forceOverride = replace,
).execute(client)
override fun readFile(
remotePath: String,
spaceWebDavUrl: String?,
): RemoteOperationResult<RemoteFile> =
ReadRemoteFileOperation(
remotePath = remotePath,
spaceWebDavUrl = spaceWebDavUrl,
).execute(client)
override fun refreshFolder(
remotePath: String,
spaceWebDavUrl: String?,
): RemoteOperationResult<ArrayList<RemoteFile>> =
ReadRemoteFolderOperation(
remotePath = remotePath,
spaceWebDavUrl = spaceWebDavUrl,
).execute(client)
override fun removeFile(
remotePath: String,
spaceWebDavUrl: String?,
): RemoteOperationResult<Unit> =
RemoveRemoteFileOperation(
remotePath = remotePath,
spaceWebDavUrl = spaceWebDavUrl,
).execute(client)
override fun renameFile(
oldName: String,
oldRemotePath: String,
newName: String,
isFolder: Boolean,
spaceWebDavUrl: String?,
): RemoteOperationResult<Unit> =
RenameRemoteFileOperation(
oldName = oldName,
oldRemotePath = oldRemotePath,
newName = newName,
isFolder = isFolder,
spaceWebDavUrl = spaceWebDavUrl,
).execute(client)
override fun getMetaFileInfo(
fileId: String,
): RemoteOperationResult<RemoteMetaFile> =
GetRemoteMetaFileOperation(fileId).execute(client)
}
@@ -0,0 +1,68 @@
package eu.qsfera.android.lib.resources.files.tus
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.nonwebdav.OptionsMethod
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.operations.RemoteOperationResult.ResultCode
import eu.qsfera.android.lib.common.utils.isOneOf
import timber.log.Timber
import java.net.URL
/**
* TUS capability detection (OPTIONS on uploads collection)
* Returns true when the server advertises Tus-Version 1.0.0 and the 'creation' extension.
*/
class CheckTusSupportRemoteOperation(
private val collectionUrlOverride: String? = null,
) : RemoteOperation<Boolean>() {
@Suppress("ExpressionBodySyntax")
override fun run(client: QSferaClient): RemoteOperationResult<Boolean> {
return try {
val base = (collectionUrlOverride ?: client.userFilesWebDavUri.toString()).trim()
val candidates = linkedSetOf(base, base.ensureTrailingSlash())
var lastResult: RemoteOperationResult<Boolean>? = null
for (endpoint in candidates) {
val options = OptionsMethod(URL(endpoint)).apply {
setRequestHeader(HttpConstants.TUS_RESUMABLE, HttpConstants.TUS_RESUMABLE_VERSION_1_0_0)
}
val status = client.executeHttpMethod(options)
Timber.d("TUS OPTIONS %s - %d", endpoint, status)
if (isSuccess(status)) {
val version = options.getResponseHeader(HttpConstants.TUS_VERSION) ?: ""
val extensions = options.getResponseHeader(HttpConstants.TUS_EXTENSION) ?: ""
val versionSupported = version.split(',').any { it.trim() == HttpConstants.TUS_RESUMABLE_VERSION_1_0_0 }
val creationSupported = extensions.split(',')
.map { it.trim().lowercase() }
.any { it == "creation" || it == "creation-with-upload" }
Timber.d("TUS supported (headers) at %s: version=%s extensions=%s", endpoint, version, extensions)
val supported = versionSupported && creationSupported
val result = RemoteOperationResult<Boolean>(ResultCode.OK).apply { data = supported }
if (supported) {
return result
}
lastResult = result
} else if (status != 0) {
lastResult = RemoteOperationResult<Boolean>(options).apply { data = false }
}
}
lastResult ?: RemoteOperationResult<Boolean>(ResultCode.OK).apply { data = false }
} catch (e: Exception) {
val result = RemoteOperationResult<Boolean>(e)
Timber.w(e, "TUS detection failed, assuming unsupported")
result.apply { data = false }
}
}
private fun isSuccess(status: Int) =
status.isOneOf(HttpConstants.HTTP_NO_CONTENT, HttpConstants.HTTP_OK)
private fun String.ensureTrailingSlash(): String =
if (this.endsWith("/")) this else "$this/"
}
@@ -0,0 +1,212 @@
package eu.qsfera.android.lib.resources.files.tus
import android.util.Base64
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.nonwebdav.PostMethod
import eu.qsfera.android.lib.common.network.ChunkFromFileRequestBody
import eu.qsfera.android.lib.common.network.WebdavUtils
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.operations.RemoteOperationResult.ResultCode
import eu.qsfera.android.lib.common.utils.isOneOf
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import timber.log.Timber
import java.io.File
import java.io.RandomAccessFile
import java.net.URL
import java.nio.channels.FileChannel
class CreateTusUploadRemoteOperation(
private val file: File,
private val remotePath: String,
@Suppress("UnusedPrivateProperty")
private val mimetype: String,
private val metadata: Map<String, String>,
private val useCreationWithUpload: Boolean,
private val firstChunkSize: Long?,
private val tusUrl: String?,
private val collectionUrlOverride: String? = null,
private val base64Encoder: Base64Encoder = DefaultBase64Encoder()
) : RemoteOperation<CreateTusUploadRemoteOperation.CreationResult>() {
data class CreationResult(
val uploadUrl: String,
val uploadOffset: Long
)
interface Base64Encoder {
fun encode(bytes: ByteArray): String
}
class DefaultBase64Encoder : Base64Encoder {
override fun encode(bytes: ByteArray): String =
Base64.encodeToString(bytes, Base64.NO_WRAP)
}
override fun run(client: QSferaClient): RemoteOperationResult<CreationResult> = try {
// Determine TUS endpoint URL based on provided parameters
val targetFileUrl = if (!tusUrl.isNullOrBlank()) {
tusUrl
} else {
val baseCollection = (collectionUrlOverride
?: client.userFilesWebDavUri.toString()).trim()
// Remove trailing slash - QSfera expects no slash on space endpoints
val resolvedCollection = buildCollectionUrl(baseCollection, remotePath).trimEnd('/')
Timber.d("TUS resolved collection: %s", resolvedCollection)
resolvedCollection
}
Timber.d("TUS Creation URL: %s", targetFileUrl)
// Prepare request body first
val postBody: RequestBody = if (useCreationWithUpload && (firstChunkSize ?: 0L) > 0L) {
// creation-with-upload: include first chunk
// Don't use .use{} here - the channel must stay open for OkHttp to read
val raf = RandomAccessFile(file, "r")
val channel: FileChannel = raf.channel
ChunkFromFileRequestBody(
file = file,
contentType = HttpConstants.CONTENT_TYPE_OFFSET_OCTET_STREAM.toMediaTypeOrNull(),
channel = channel,
chunkSize = firstChunkSize!!
)
} else {
// creation only: empty body
ByteArray(0).toRequestBody(null)
}
val postMethod = PostMethod(URL(targetFileUrl), postBody)
// Set TUS headers
postMethod.setRequestHeader(HttpConstants.TUS_RESUMABLE, "1.0.0")
postMethod.setRequestHeader(HttpConstants.UPLOAD_LENGTH, file.length().toString())
postMethod.setRequestHeader(HttpConstants.CONTENT_TYPE_HEADER, HttpConstants.CONTENT_TYPE_OFFSET_OCTET_STREAM)
// Set TUS-Extension header to indicate which extensions we want to use
val extensions = if (useCreationWithUpload && (firstChunkSize ?: 0L) > 0L) {
"creation,creation-with-upload"
} else {
"creation"
}
postMethod.setRequestHeader(HttpConstants.TUS_EXTENSION, extensions)
// Prepare Upload-Metadata like iOS SDK
val allMetadata = metadata.toMutableMap()
allMetadata.putIfAbsent("filename", remotePath.substringAfterLast('/'))
allMetadata.putIfAbsent("mtime", (file.lastModified() / 1000).toString())
if (allMetadata.isNotEmpty()) {
postMethod.setRequestHeader(HttpConstants.UPLOAD_METADATA, encodeTusMetadata(allMetadata))
}
// Set Upload-Offset for creation-with-upload
if (useCreationWithUpload && (firstChunkSize ?: 0L) > 0L) {
postMethod.setRequestHeader(HttpConstants.UPLOAD_OFFSET, "0")
}
val status = client.executeHttpMethod(postMethod)
Timber.d("TUS Creation [%s] - %d%s", targetFileUrl, status, if (!isSuccess(status)) " (FAIL)" else "")
if (!isSuccess(status)) {
Timber.w("TUS Creation failed - Status: %d", status)
Timber.w(" Target URL: %s", targetFileUrl)
Timber.w(" Collection Override: %s", collectionUrlOverride)
Timber.w(" User Files WebDAV: %s", client.userFilesWebDavUri)
Timber.w(" Remote Path: %s", remotePath)
Timber.w(" File Size: %d bytes", file.length())
Timber.w(" Tus-Resumable: %s", postMethod.getRequestHeader(HttpConstants.TUS_RESUMABLE))
Timber.w(" Upload-Length: %s", postMethod.getRequestHeader(HttpConstants.UPLOAD_LENGTH))
Timber.w(" Upload-Metadata: %s", postMethod.getRequestHeader(HttpConstants.UPLOAD_METADATA))
}
// Debug logging for troubleshooting
if (status == 412) {
Timber.w("HTTP 412 Precondition Failed - Request headers:")
Timber.w(" Tus-Resumable: %s", postMethod.getRequestHeader(HttpConstants.TUS_RESUMABLE))
Timber.w(" Tus-Extension: %s", postMethod.getRequestHeader(HttpConstants.TUS_EXTENSION))
Timber.w(" Upload-Length: %s", postMethod.getRequestHeader(HttpConstants.UPLOAD_LENGTH))
Timber.w(" Upload-Metadata: %s", postMethod.getRequestHeader(HttpConstants.UPLOAD_METADATA))
Timber.w(" Content-Type: %s", postMethod.getRequestHeader(HttpConstants.CONTENT_TYPE_HEADER))
Timber.w(" Content-Length: %d", postBody.contentLength())
if (useCreationWithUpload && (firstChunkSize ?: 0L) > 0L) {
Timber.w(" Upload-Offset: %s", postMethod.getRequestHeader(HttpConstants.UPLOAD_OFFSET))
}
}
if (isSuccess(status)) {
val locationHeader = postMethod.getResponseHeader(HttpConstants.LOCATION_HEADER)
?: postMethod.getResponseHeader(HttpConstants.LOCATION_HEADER_LOWER)
val base = URL(postMethod.getFinalUrl().toString())
val resolved = resolveLocationToAbsolute(locationHeader, base)
val offsetHeader = postMethod.getResponseHeader(HttpConstants.UPLOAD_OFFSET)
val offset = offsetHeader?.toLongOrNull() ?: 0L
if (resolved != null) {
Timber.d("TUS upload resource created: %s (offset=%d)", resolved, offset)
RemoteOperationResult<CreationResult>(ResultCode.OK).apply {
data = CreationResult(resolved, offset)
}
} else {
Timber.e("Location header is missing in TUS creation response")
RemoteOperationResult<CreationResult>(IllegalStateException("Location header missing")).apply {
data = null
}
}
} else {
Timber.w("TUS creation failed with status: %d", status)
RemoteOperationResult<CreationResult>(postMethod).apply { data = null }
}
} catch (e: Exception) {
val result = RemoteOperationResult<CreationResult>(e)
Timber.e(e, "TUS creation operation failed")
result
}
private fun isSuccess(status: Int) =
status.isOneOf(HttpConstants.HTTP_CREATED, HttpConstants.HTTP_OK)
private fun encodeTusMetadata(metadata: Map<String, String>): String =
metadata.entries.joinToString(",") { (key, value) ->
val encoded = base64Encoder.encode(value.toByteArray(Charsets.UTF_8))
"$key $encoded"
}
private fun resolveLocationToAbsolute(location: String?, base: URL): String? {
if (location.isNullOrBlank()) return null
return try {
URL(base, location).toString()
} catch (e: Exception) {
Timber.w(e, "Failed to resolve Location header: %s", location)
null
}
}
private fun buildCollectionUrl(base: String, remotePath: String): String {
val normalizedBase = base.trim().trimEnd('/')
val sanitizedRemotePath = remotePath.trim().trimEnd('/').ifEmpty { "/" }
if (sanitizedRemotePath == "/") {
return normalizedBase
}
val encodedPath = WebdavUtils.encodePath(sanitizedRemotePath)
val parentSegment = when (val idx = encodedPath.lastIndexOf('/')) {
-1, 0 -> ""
else -> encodedPath.substring(0, idx).removePrefix("/")
}
return if (parentSegment.isEmpty()) {
normalizedBase
} else {
"$normalizedBase/$parentSegment"
}
}
companion object {
// Use 10MB for first chunk like the browser does
const val DEFAULT_FIRST_CHUNK = 10 * 1024 * 1024L // 10MB
}
}
@@ -0,0 +1,40 @@
package eu.qsfera.android.lib.resources.files.tus
import eu.qsfera.android.lib.common.QSferaClient
import eu.qsfera.android.lib.common.http.HttpConstants
import eu.qsfera.android.lib.common.http.methods.nonwebdav.DeleteMethod
import eu.qsfera.android.lib.common.operations.RemoteOperation
import eu.qsfera.android.lib.common.operations.RemoteOperationResult
import eu.qsfera.android.lib.common.operations.RemoteOperationResult.ResultCode
import eu.qsfera.android.lib.common.utils.isOneOf
import timber.log.Timber
import java.net.URL
/**
* TUS Delete Upload operation (DELETE)
* Deletes an existing upload resource.
*/
class DeleteTusUploadRemoteOperation(
private val uploadUrl: String,
) : RemoteOperation<Unit>() {
override fun run(client: QSferaClient): RemoteOperationResult<Unit> =
try {
val deleteMethod = DeleteMethod(URL(uploadUrl)).apply {
setRequestHeader(HttpConstants.TUS_RESUMABLE, HttpConstants.TUS_RESUMABLE_VERSION_1_0_0)
}
val status = client.executeHttpMethod(deleteMethod)
Timber.d("Delete TUS upload - $status${if (!isSuccess(status)) "(FAIL)" else ""}")
if (isSuccess(status)) RemoteOperationResult<Unit>(ResultCode.OK).apply { data = Unit }
else RemoteOperationResult<Unit>(deleteMethod)
} catch (e: Exception) {
val result = RemoteOperationResult<Unit>(e)
Timber.e(e, "Delete TUS upload failed")
result
}
private fun isSuccess(status: Int): Boolean =
status.isOneOf(HttpConstants.HTTP_NO_CONTENT, HttpConstants.HTTP_OK)
}

Some files were not shown because too many files have changed in this diff Show More