diff --git a/build.gradle b/build.gradle index 0f79bf7f..6af7cb1f 100644 --- a/build.gradle +++ b/build.gradle @@ -1,10 +1,17 @@ buildscript { + ext { + // Libraries + kotlinVersion = '1.3.21' + } + repositories { google() jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:3.3.2' + classpath 'com.android.tools.build:gradle:3.4.1' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" + classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlinVersion" } } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 53f7eaf3..f350b755 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-all.zip \ No newline at end of file +distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip \ No newline at end of file diff --git a/owncloudComLibrary/build.gradle b/owncloudComLibrary/build.gradle index 3dce97b1..463d135a 100644 --- a/owncloudComLibrary/build.gradle +++ b/owncloudComLibrary/build.gradle @@ -1,11 +1,20 @@ apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-kapt' + +apply plugin: 'kotlin-allopen' dependencies { api 'com.squareup.okhttp3:okhttp:3.12.0' - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.11" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion" api 'com.gitlab.ownclouders:dav4android:oc_support_1.0.1' } +allOpen { + // allows mocking for classes w/o directly opening them for release builds + annotation 'com.owncloud.android.lib.testing.OpenClass' +} + android { compileSdkVersion 28 diff --git a/owncloudComLibrary/src/debug/java/com/owncloud/android/lib/testing/OpenForTesting.kt b/owncloudComLibrary/src/debug/java/com/owncloud/android/lib/testing/OpenForTesting.kt new file mode 100644 index 00000000..3c91e836 --- /dev/null +++ b/owncloudComLibrary/src/debug/java/com/owncloud/android/lib/testing/OpenForTesting.kt @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2018 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.owncloud.android.lib.testing + +/** + * This annotation allows us to open some classes for mocking purposes while they are final in + * release builds. + */ +@Target(AnnotationTarget.ANNOTATION_CLASS) +annotation class OpenClass + +/** + * Annotate a class with [OpenForTesting] if you want it to be extendable in debug builds. + */ +@OpenClass +@Target(AnnotationTarget.CLASS) +annotation class OpenForTesting diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/interceptors/HttpInterceptor.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/interceptors/HttpInterceptor.java index 3c9b61e7..b9720924 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/interceptors/HttpInterceptor.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/interceptors/HttpInterceptor.java @@ -30,7 +30,7 @@ import okhttp3.Response; import java.io.IOException; import java.util.ArrayList; -import java.util.Iterator; +import java.util.ListIterator; /** * Http interceptor to use multiple interceptors in the same {@link okhttp3.OkHttpClient} instance @@ -86,7 +86,7 @@ public class HttpInterceptor implements Interceptor { } public void deleteRequestHeaderInterceptor(String headerName) { - Iterator requestInterceptorIterator = mRequestInterceptors.iterator(); + ListIterator requestInterceptorIterator = mRequestInterceptors.listIterator(); while (requestInterceptorIterator.hasNext()) { RequestInterceptor currentRequestInterceptor = requestInterceptorIterator.next(); if (currentRequestInterceptor instanceof RequestHeaderInterceptor && diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/operations/RemoteOperationResult.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/operations/RemoteOperationResult.java index 18d417fc..e87ed5ec 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/operations/RemoteOperationResult.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/operations/RemoteOperationResult.java @@ -526,6 +526,10 @@ public class RemoteOperationResult mData = data; } + public void setHttpPhrase(String httpPhrase) { + mHttpPhrase = httpPhrase; + } + public enum ResultCode { OK, OK_SSL, diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/CreateRemoteShareOperation.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/CreateRemoteShareOperation.java deleted file mode 100644 index 631af0ee..00000000 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/CreateRemoteShareOperation.java +++ /dev/null @@ -1,269 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * @author masensio - * @author David A. Velasco - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.lib.resources.shares; - -import android.net.Uri; - -import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.http.HttpConstants; -import com.owncloud.android.lib.common.http.methods.nonwebdav.PostMethod; -import com.owncloud.android.lib.common.operations.RemoteOperation; -import com.owncloud.android.lib.common.operations.RemoteOperationResult; -import com.owncloud.android.lib.common.utils.Log_OC; -import okhttp3.FormBody; - -import java.net.URL; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Locale; - -/** - * Creates a new share. This allows sharing with a user or group or as a link. - * - * @author masensio - * @author David A. Velasco - * @author David González Verdugo - */ -public class CreateRemoteShareOperation extends RemoteOperation { - - private static final String TAG = CreateRemoteShareOperation.class.getSimpleName(); - - private static final String PARAM_NAME = "name"; - private static final String PARAM_PASSWORD = "password"; - private static final String PARAM_EXPIRATION_DATE = "expireDate"; - private static final String PARAM_PUBLIC_UPLOAD = "publicUpload"; - private static final String PARAM_PATH = "path"; - private static final String PARAM_SHARE_TYPE = "shareType"; - private static final String PARAM_SHARE_WITH = "shareWith"; - private static final String PARAM_PERMISSIONS = "permissions"; - private static final String FORMAT_EXPIRATION_DATE = "yyyy-MM-dd"; - - private String mRemoteFilePath; - private ShareType mShareType; - private String mShareWith; - private boolean mGetShareDetails; - - /** - * Name to set for the public link - */ - private String mName = ""; - - /** - * Password to set for the public link - */ - private String mPassword; - - /** - * Expiration date to set for the public link - */ - private long mExpirationDateInMillis = 0; - - /** - * Access permissions for the file bound to the share - */ - private int mPermissions; - - /** - * Upload permissions for the public link (only folders) - */ - private Boolean mPublicUpload; - - /** - * Constructor - * - * @param remoteFilePath Full path of the file/folder being shared. Mandatory argument - * @param shareType 0 = user, 1 = group, 3 = Public link. Mandatory argument - * @param shareWith User/group ID with who the file should be shared. This is mandatory for shareType - * of 0 or 1 - * @param publicUpload If false (default) public cannot upload to a public shared folder. - * If true public can upload to a shared folder. Only available for public link shares - * @param password Password to protect a public link share. Only available for public link shares - * @param permissions 1 - Read only Default for public shares - * 2 - Update - * 4 - Create - * 8 - Delete - * 16- Re-share - * 31- All above Default for private shares - * For user or group shares. - * To obtain combinations, add the desired values together. - * For instance, for Re-Share, delete, read, update, add 16+8+2+1 = 27. - */ - public CreateRemoteShareOperation( - String remoteFilePath, - ShareType shareType, - String shareWith, - boolean publicUpload, - String password, - int permissions - ) { - - mRemoteFilePath = remoteFilePath; - mShareType = shareType; - mShareWith = shareWith; - mPublicUpload = publicUpload; - mPassword = password; - mPermissions = permissions; - mGetShareDetails = false; // defaults to false for backwards compatibility - } - - /** - * Set name to create in Share resource. Ignored by servers previous to version 10.0.0 - * - * @param name Name to set to the target share. - * Null or empty string result in no value set for the name. - */ - public void setName(String name) { - this.mName = (name == null) ? "" : name; - } - - /** - * Set password to create in Share resource. - * - * @param password Password to set to the target share. - * Null or empty string result in no value set for the password. - */ - public void setPassword(String password) { - mPassword = password; - } - - /** - * Set expiration date to create in Share resource. - * - * @param expirationDateInMillis Expiration date to set to the target share. - * Zero or negative value results in no value sent for expiration date. - */ - public void setExpirationDate(long expirationDateInMillis) { - mExpirationDateInMillis = expirationDateInMillis; - } - - /** - * Set permissions to create in Share resource. - * - * @param permissions Permissions to set to the target share. - * Values <= 0 result in value set to the permissions. - */ - public void setPermissions(int permissions) { - mPermissions = permissions; - } - - /** - * * Enable upload permissions to create in Share resource. - * * - * * @param publicUpload Upload permission to set to the target share. - * * Null results in no update applied to the upload permission. - */ - public void setPublicUpload(Boolean publicUpload) { - mPublicUpload = publicUpload; - } - - public void setGetShareDetails(boolean set) { - mGetShareDetails = set; - } - - @Override - protected RemoteOperationResult run(OwnCloudClient client) { - RemoteOperationResult result; - - try { - FormBody.Builder formBodyBuilder = new FormBody.Builder() - .add(PARAM_PATH, mRemoteFilePath) - .add(PARAM_SHARE_TYPE, Integer.toString(mShareType.getValue())) - .add(PARAM_SHARE_WITH, mShareWith); - - if (mName.length() > 0) { - formBodyBuilder.add(PARAM_NAME, mName); - } - - if (mExpirationDateInMillis > 0) { - DateFormat dateFormat = new SimpleDateFormat(FORMAT_EXPIRATION_DATE, Locale.getDefault()); - Calendar expirationDate = Calendar.getInstance(); - expirationDate.setTimeInMillis(mExpirationDateInMillis); - String formattedExpirationDate = dateFormat.format(expirationDate.getTime()); - formBodyBuilder.add(PARAM_EXPIRATION_DATE, formattedExpirationDate); - } - - if (mPublicUpload) { - formBodyBuilder.add(PARAM_PUBLIC_UPLOAD, Boolean.toString(true)); - } - if (mPassword != null && mPassword.length() > 0) { - formBodyBuilder.add(PARAM_PASSWORD, mPassword); - } - if (OCShare.DEFAULT_PERMISSION != mPermissions) { - formBodyBuilder.add(PARAM_PERMISSIONS, Integer.toString(mPermissions)); - } - - Uri requestUri = client.getBaseUri(); - Uri.Builder uriBuilder = requestUri.buildUpon(); - uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH); - - PostMethod postMethod = new PostMethod(new URL(uriBuilder.build().toString())); - - postMethod.setRequestBody(formBodyBuilder.build()); - - postMethod.setRequestHeader(HttpConstants.CONTENT_TYPE_HEADER, HttpConstants.CONTENT_TYPE_URLENCODED_UTF8); - postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); - - int status = client.executeHttpMethod(postMethod); - - ShareToRemoteOperationResultParser parser = new ShareToRemoteOperationResultParser( - new ShareXMLParser() - ); - - if (isSuccess(status)) { - parser.setOneOrMoreSharesRequired(true); - parser.setOwnCloudVersion(client.getOwnCloudVersion()); - parser.setServerBaseUri(client.getBaseUri()); - result = parser.parse(postMethod.getResponseBodyAsString()); - - if (result.isSuccess() && mGetShareDetails) { - - // TODO Use executeHttpMethod - // retrieve more info - POST only returns the index of the new share - OCShare emptyShare = result.getData().getShares().get(0); - GetRemoteShareOperation getInfo = new GetRemoteShareOperation( - emptyShare.getRemoteId() - ); - result = getInfo.execute(client); - } - - } else { - result = parser.parse(postMethod.getResponseBodyAsString()); - } - - } catch (Exception e) { - result = new RemoteOperationResult<>(e); - Log_OC.e(TAG, "Exception while Creating New Share", e); - } - return result; - } - - private boolean isSuccess(int status) { - return (status == HttpConstants.HTTP_OK); - } -} \ No newline at end of file diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/CreateRemoteShareOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/CreateRemoteShareOperation.kt new file mode 100644 index 00000000..b7080c4d --- /dev/null +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/CreateRemoteShareOperation.kt @@ -0,0 +1,174 @@ +/* ownCloud Android Library is available under MIT license + * @author masensio + * @author David A. Velasco + * @author David González Verdugo + * Copyright (C) 2019 ownCloud GmbH + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.resources.shares + +import com.owncloud.android.lib.common.OwnCloudClient +import com.owncloud.android.lib.common.http.HttpConstants +import com.owncloud.android.lib.common.http.methods.nonwebdav.PostMethod +import com.owncloud.android.lib.common.operations.RemoteOperation +import com.owncloud.android.lib.common.operations.RemoteOperationResult +import com.owncloud.android.lib.common.utils.Log_OC +import com.owncloud.android.lib.resources.shares.RemoteShare.Companion.INIT_EXPIRATION_DATE_IN_MILLIS +import okhttp3.FormBody +import java.net.URL +import java.text.SimpleDateFormat +import java.util.Calendar +import java.util.Locale + +/** + * Creates a new share. This allows sharing with a user or group or as a link. + * + * @author masensio + * @author David A. Velasco + * @author David González Verdugo + */ + +/** + * Constructor + * + * @param remoteFilePath Full path of the file/folder being shared. Mandatory argument + * @param shareType 0 = user, 1 = group, 3 = Public link. Mandatory argument + * @param shareWith User/group ID with who the file should be shared. This is mandatory for shareType + * of 0 or 1 + * @param permissions 1 - Read only Default for public shares + * 2 - Update + * 4 - Create + * 8 - Delete + * 16- Re-share + * 31- All above Default for private shares + * For user or group shares. + * To obtain combinations, add the desired values together. + * For instance, for Re-Share, delete, read, update, add 16+8+2+1 = 27. + */ +class CreateRemoteShareOperation( + private val remoteFilePath: String, + private val shareType: ShareType, + private val shareWith: String, + private val permissions: Int +) : RemoteOperation() { + var name = "" // Name to set for the public link + + var password: String = "" // Password to set for the public link + + var expirationDateInMillis: Long = INIT_EXPIRATION_DATE_IN_MILLIS // Expiration date to set for the public link + + var publicUpload: Boolean = false // Upload permissions for the public link (only folders) + + var retrieveShareDetails = false // To retrieve more info about the just created share + + override fun run(client: OwnCloudClient): RemoteOperationResult { + var result: RemoteOperationResult + + try { + val formBodyBuilder = FormBody.Builder() + .add(PARAM_PATH, remoteFilePath) + .add(PARAM_SHARE_TYPE, shareType.value.toString()) + .add(PARAM_SHARE_WITH, shareWith) + + if (name.isNotEmpty()) { + formBodyBuilder.add(PARAM_NAME, name) + } + + if (expirationDateInMillis > INIT_EXPIRATION_DATE_IN_MILLIS) { + val dateFormat = SimpleDateFormat(FORMAT_EXPIRATION_DATE, Locale.getDefault()) + val expirationDate = Calendar.getInstance() + expirationDate.timeInMillis = expirationDateInMillis + val formattedExpirationDate = dateFormat.format(expirationDate.time) + formBodyBuilder.add(PARAM_EXPIRATION_DATE, formattedExpirationDate) + } + + if (publicUpload) { + formBodyBuilder.add(PARAM_PUBLIC_UPLOAD, publicUpload.toString()) + } + if (password.isNotEmpty()) { + formBodyBuilder.add(PARAM_PASSWORD, password) + } + if (RemoteShare.DEFAULT_PERMISSION != permissions) { + formBodyBuilder.add(PARAM_PERMISSIONS, permissions.toString()) + } + + val requestUri = client.baseUri + val uriBuilder = requestUri.buildUpon() + uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH) + + val postMethod = PostMethod(URL(uriBuilder.build().toString())) + + postMethod.setRequestBody(formBodyBuilder.build()) + + postMethod.setRequestHeader(HttpConstants.CONTENT_TYPE_HEADER, HttpConstants.CONTENT_TYPE_URLENCODED_UTF8) + postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE) + + val status = client.executeHttpMethod(postMethod) + + val parser = ShareToRemoteOperationResultParser( + ShareXMLParser() + ) + + if (isSuccess(status)) { + parser.oneOrMoreSharesRequired = true + parser.ownCloudVersion = client.ownCloudVersion + parser.serverBaseUri = client.baseUri + result = parser.parse(postMethod.responseBodyAsString) + + if (result.isSuccess && retrieveShareDetails) { + // retrieve more info - POST only returns the index of the new share + val emptyShare = result.data.shares[0] + val getInfo = GetRemoteShareOperation( + emptyShare.id + ) + result = getInfo.execute(client) + } + + } else { + result = parser.parse(postMethod.responseBodyAsString) + } + + } catch (e: Exception) { + result = RemoteOperationResult(e) + Log_OC.e(TAG, "Exception while Creating New Share", e) + } + + return result + } + + private fun isSuccess(status: Int): Boolean = status == HttpConstants.HTTP_OK + + companion object { + private val TAG = CreateRemoteShareOperation::class.java.simpleName + + private const val PARAM_NAME = "name" + private const val PARAM_PASSWORD = "password" + private const val PARAM_EXPIRATION_DATE = "expireDate" + private const val PARAM_PUBLIC_UPLOAD = "publicUpload" + private const val PARAM_PATH = "path" + private const val PARAM_SHARE_TYPE = "shareType" + private const val PARAM_SHARE_WITH = "shareWith" + private const val PARAM_PERMISSIONS = "permissions" + private const val FORMAT_EXPIRATION_DATE = "yyyy-MM-dd" + } +} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteShareesOperation.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteShareesOperation.java deleted file mode 100644 index 2a90128e..00000000 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteShareesOperation.java +++ /dev/null @@ -1,199 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * - * @author masensio - * @author David A. Velasco - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.lib.resources.shares; - -import android.net.Uri; - -import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.http.HttpConstants; -import com.owncloud.android.lib.common.http.methods.nonwebdav.GetMethod; -import com.owncloud.android.lib.common.operations.RemoteOperation; -import com.owncloud.android.lib.common.operations.RemoteOperationResult; -import com.owncloud.android.lib.common.utils.Log_OC; - -import org.json.JSONArray; -import org.json.JSONObject; - -import java.net.URL; -import java.util.ArrayList; - -import static com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode.OK; - -/** - * Created by masensio on 08/10/2015. - *

- * Retrieves a list of sharees (possible targets of a share) from the ownCloud server. - *

- * Currently only handles users and groups. Users in other OC servers (federation) should be added later. - *

- * Depends on SHAREE API. {@See https://github.com/owncloud/documentation/issues/1626} - *

- * Syntax: - * Entry point: ocs/v2.php/apps/files_sharing/api/v1/sharees - * HTTP method: GET - * url argument: itemType - string, required - * url argument: format - string, optional - * url argument: search - string, optional - * url arguments: perPage - int, optional - * url arguments: page - int, optional - *

- * Status codes: - * 100 - successful - * - * @author masensio - * @author David A. Velasco - * @author David González Verdugo - */ -public class GetRemoteShareesOperation extends RemoteOperation> { - - private static final String TAG = GetRemoteShareesOperation.class.getSimpleName(); - - // OCS Routes - private static final String OCS_ROUTE = "ocs/v2.php/apps/files_sharing/api/v1/sharees"; // from OC 8.2 - - // Arguments - names - private static final String PARAM_FORMAT = "format"; - private static final String PARAM_ITEM_TYPE = "itemType"; - private static final String PARAM_SEARCH = "search"; - private static final String PARAM_PAGE = "page"; // default = 1 - private static final String PARAM_PER_PAGE = "perPage"; // default = 200 - - // Arguments - constant values - private static final String VALUE_FORMAT = "json"; - private static final String VALUE_ITEM_TYPE = "file"; // to get the server search for users / groups - - // JSON Node names - private static final String NODE_OCS = "ocs"; - private static final String NODE_DATA = "data"; - private static final String NODE_EXACT = "exact"; - private static final String NODE_USERS = "users"; - private static final String NODE_GROUPS = "groups"; - private static final String NODE_REMOTES = "remotes"; - public static final String NODE_VALUE = "value"; - public static final String PROPERTY_LABEL = "label"; - public static final String PROPERTY_SHARE_TYPE = "shareType"; - public static final String PROPERTY_SHARE_WITH = "shareWith"; - public static final String PROPERTY_SHARE_WITH_ADDITIONAL_INFO = "shareWithAdditionalInfo"; - - private String mSearchString; - private int mPage; - private int mPerPage; - - /** - * Constructor - * - * @param searchString string for searching users, optional - * @param page page index in the list of results; beginning in 1 - * @param perPage maximum number of results in a single page - */ - public GetRemoteShareesOperation(String searchString, int page, int perPage) { - mSearchString = searchString; - mPage = page; - mPerPage = perPage; - } - - @Override - protected RemoteOperationResult> run(OwnCloudClient client) { - RemoteOperationResult> result; - - try { - Uri requestUri = client.getBaseUri(); - Uri.Builder uriBuilder = requestUri.buildUpon() - .appendEncodedPath(OCS_ROUTE) - .appendQueryParameter(PARAM_FORMAT, VALUE_FORMAT) - .appendQueryParameter(PARAM_ITEM_TYPE, VALUE_ITEM_TYPE) - .appendQueryParameter(PARAM_SEARCH, mSearchString) - .appendQueryParameter(PARAM_PAGE, String.valueOf(mPage)) - .appendQueryParameter(PARAM_PER_PAGE, String.valueOf(mPerPage)); - - GetMethod getMethod = new GetMethod(new URL(uriBuilder.build().toString())); - - getMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); - - int status = client.executeHttpMethod(getMethod); - String response = getMethod.getResponseBodyAsString(); - - if (isSuccess(status)) { - Log_OC.d(TAG, "Successful response: " + response); - - // Parse the response - JSONObject respJSON = new JSONObject(response); - JSONObject respOCS = respJSON.getJSONObject(NODE_OCS); - JSONObject respData = respOCS.getJSONObject(NODE_DATA); - JSONObject respExact = respData.getJSONObject(NODE_EXACT); - JSONArray respExactUsers = respExact.getJSONArray(NODE_USERS); - JSONArray respExactGroups = respExact.getJSONArray(NODE_GROUPS); - JSONArray respExactRemotes = respExact.getJSONArray(NODE_REMOTES); - JSONArray respPartialUsers = respData.getJSONArray(NODE_USERS); - JSONArray respPartialGroups = respData.getJSONArray(NODE_GROUPS); - JSONArray respPartialRemotes = respData.getJSONArray(NODE_REMOTES); - JSONArray[] jsonResults = { - respExactUsers, - respExactGroups, - respExactRemotes, - respPartialUsers, - respPartialGroups, - respPartialRemotes - }; - - ArrayList data = new ArrayList<>(); // For result data - for (int i = 0; i < 6; i++) { - for (int j = 0; j < jsonResults[i].length(); j++) { - JSONObject jsonResult = jsonResults[i].getJSONObject(j); - data.add(jsonResult); - Log_OC.d(TAG, "*** Added item: " + jsonResult.getString(PROPERTY_LABEL)); - } - } - - result = new RemoteOperationResult<>(OK); - result.setData(data); - - Log_OC.d(TAG, "*** Get Users or groups completed "); - - } else { - result = new RemoteOperationResult<>(getMethod); - Log_OC.e(TAG, "Failed response while getting users/groups from the server "); - if (response != null) { - Log_OC.e(TAG, "*** status code: " + status + "; response message: " + response); - } else { - Log_OC.e(TAG, "*** status code: " + status); - } - } - } catch (Exception e) { - result = new RemoteOperationResult<>(e); - Log_OC.e(TAG, "Exception while getting users/groups", e); - } - - return result; - } - - private boolean isSuccess(int status) { - return (status == HttpConstants.HTTP_OK); - } -} \ No newline at end of file diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteShareesOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteShareesOperation.kt new file mode 100644 index 00000000..d439ff26 --- /dev/null +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteShareesOperation.kt @@ -0,0 +1,197 @@ +/* ownCloud Android Library is available under MIT license + * + * @author masensio + * @author David A. Velasco + * @author David González Verdugo + * Copyright (C) 2019 ownCloud GmbH. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.resources.shares + +import com.owncloud.android.lib.common.OwnCloudClient +import com.owncloud.android.lib.common.http.HttpConstants +import com.owncloud.android.lib.common.http.methods.nonwebdav.GetMethod +import com.owncloud.android.lib.common.operations.RemoteOperation +import com.owncloud.android.lib.common.operations.RemoteOperationResult +import com.owncloud.android.lib.common.utils.Log_OC + +import org.json.JSONObject + +import java.net.URL +import java.util.ArrayList + +import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode.OK +import com.owncloud.android.lib.testing.OpenForTesting + +/** + * Created by masensio on 08/10/2015. + * + * + * Retrieves a list of sharees (possible targets of a share) from the ownCloud server. + * + * + * Currently only handles users and groups. Users in other OC servers (federation) should be added later. + * + * + * Depends on SHAREE API. {@See https://github.com/owncloud/documentation/issues/1626} + * + * + * Syntax: + * Entry point: ocs/v2.php/apps/files_sharing/api/v1/sharees + * HTTP method: GET + * url argument: itemType - string, required + * url argument: format - string, optional + * url argument: search - string, optional + * url arguments: perPage - int, optional + * url arguments: page - int, optional + * + * + * Status codes: + * 100 - successful + * + * @author masensio + * @author David A. Velasco + * @author David González Verdugo + */ +@OpenForTesting +class GetRemoteShareesOperation +/** + * Constructor + * + * @param searchString string for searching users, optional + * @param page page index in the list of results; beginning in 1 + * @param perPage maximum number of results in a single page + */ + (private val searchString: String, private val page: Int, private val perPage: Int) : + RemoteOperation>() { + + override fun run(client: OwnCloudClient): RemoteOperationResult> { + var result: RemoteOperationResult> + + try { + val requestUri = client.baseUri + val uriBuilder = requestUri.buildUpon() + .appendEncodedPath(OCS_ROUTE) + .appendQueryParameter(PARAM_FORMAT, VALUE_FORMAT) + .appendQueryParameter(PARAM_ITEM_TYPE, VALUE_ITEM_TYPE) + .appendQueryParameter(PARAM_SEARCH, searchString) + .appendQueryParameter(PARAM_PAGE, page.toString()) + .appendQueryParameter(PARAM_PER_PAGE, perPage.toString()) + + val getMethod = GetMethod(URL(uriBuilder.build().toString())) + + getMethod.addRequestHeader(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE) + + val status = client.executeHttpMethod(getMethod) + val response = getMethod.responseBodyAsString + + if (isSuccess(status)) { + Log_OC.d(TAG, "Successful response: " + response!!) + + // Parse the response + val respJSON = JSONObject(response) + val respOCS = respJSON.getJSONObject(NODE_OCS) + val respData = respOCS.getJSONObject(NODE_DATA) + val respExact = respData.getJSONObject(NODE_EXACT) + val respExactUsers = respExact.getJSONArray(NODE_USERS) + val respExactGroups = respExact.getJSONArray(NODE_GROUPS) + val respExactRemotes = respExact.getJSONArray(NODE_REMOTES) + val respPartialUsers = respData.getJSONArray(NODE_USERS) + val respPartialGroups = respData.getJSONArray(NODE_GROUPS) + val respPartialRemotes = respData.getJSONArray(NODE_REMOTES) + val jsonResults = arrayOf( + respExactUsers, + respExactGroups, + respExactRemotes, + respPartialUsers, + respPartialGroups, + respPartialRemotes + ) + + val data = ArrayList() // For result data + for (i in 0..5) { + for (j in 0 until jsonResults[i].length()) { + val jsonResult = jsonResults[i].getJSONObject(j) + data.add(jsonResult) + Log_OC.d(TAG, "*** Added item: " + jsonResult.getString(PROPERTY_LABEL)) + } + } + + result = RemoteOperationResult(OK) + result.data = data + + Log_OC.d(TAG, "*** Get Users or groups completed ") + + } else { + result = RemoteOperationResult(getMethod) + Log_OC.e(TAG, "Failed response while getting users/groups from the server ") + if (response != null) { + Log_OC.e(TAG, "*** status code: $status; response message: $response") + } else { + Log_OC.e(TAG, "*** status code: $status") + } + } + } catch (e: Exception) { + result = RemoteOperationResult(e) + Log_OC.e(TAG, "Exception while getting users/groups", e) + } + + return result + } + + private fun isSuccess(status: Int): Boolean { + return status == HttpConstants.HTTP_OK + } + + companion object { + + private val TAG = GetRemoteShareesOperation::class.java.simpleName + + // OCS Routes + private val OCS_ROUTE = "ocs/v2.php/apps/files_sharing/api/v1/sharees" // from OC 8.2 + + // Arguments - names + private val PARAM_FORMAT = "format" + private val PARAM_ITEM_TYPE = "itemType" + private val PARAM_SEARCH = "search" + private val PARAM_PAGE = "page" // default = 1 + private val PARAM_PER_PAGE = "perPage" // default = 200 + + // Arguments - constant values + private val VALUE_FORMAT = "json" + private val VALUE_ITEM_TYPE = "file" // to get the server search for users / groups + + // JSON Node names + private val NODE_OCS = "ocs" + private val NODE_DATA = "data" + private val NODE_EXACT = "exact" + private val NODE_USERS = "users" + private val NODE_GROUPS = "groups" + private val NODE_REMOTES = "remotes" + val NODE_VALUE = "value" + val PROPERTY_LABEL = "label" + val PROPERTY_SHARE_TYPE = "shareType" + val PROPERTY_SHARE_WITH = "shareWith" + val PROPERTY_SHARE_WITH_ADDITIONAL_INFO = "shareWithAdditionalInfo" + } +} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteSharesForFileOperation.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteSharesForFileOperation.java deleted file mode 100644 index e788cb25..00000000 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteSharesForFileOperation.java +++ /dev/null @@ -1,124 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * @author masensio - * @author David A. Velasco - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.lib.resources.shares; - -import android.net.Uri; - -import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.http.HttpConstants; -import com.owncloud.android.lib.common.http.methods.nonwebdav.GetMethod; -import com.owncloud.android.lib.common.operations.RemoteOperation; -import com.owncloud.android.lib.common.operations.RemoteOperationResult; -import com.owncloud.android.lib.common.utils.Log_OC; - -import java.net.URL; - -/** - * Provide a list shares for a specific file. - * The input is the full path of the desired file. - * The output is a list of everyone who has the file shared with them. - * - * @author masensio - * @author David A. Velasco - * @author David González Verdugo - */ -public class GetRemoteSharesForFileOperation extends RemoteOperation { - - private static final String TAG = GetRemoteSharesForFileOperation.class.getSimpleName(); - - private static final String PARAM_PATH = "path"; - private static final String PARAM_RESHARES = "reshares"; - private static final String PARAM_SUBFILES = "subfiles"; - - private String mRemoteFilePath; - private boolean mReshares; - private boolean mSubfiles; - - /** - * Constructor - * - * @param remoteFilePath Path to file or folder - * @param reshares If set to false (default), only shares owned by the current user are - * returned. - * If set to true, shares owned by any user from the given file are returned. - * @param subfiles If set to false (default), lists only the folder being shared - * If set to true, all shared files within the folder are returned. - */ - public GetRemoteSharesForFileOperation(String remoteFilePath, boolean reshares, - boolean subfiles) { - mRemoteFilePath = remoteFilePath; - mReshares = reshares; - mSubfiles = subfiles; - } - - @Override - protected RemoteOperationResult run(OwnCloudClient client) { - RemoteOperationResult result; - - try { - - Uri requestUri = client.getBaseUri(); - Uri.Builder uriBuilder = requestUri.buildUpon(); - uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH); - uriBuilder.appendQueryParameter(PARAM_PATH, mRemoteFilePath); - uriBuilder.appendQueryParameter(PARAM_RESHARES, String.valueOf(mReshares)); - uriBuilder.appendQueryParameter(PARAM_SUBFILES, String.valueOf(mSubfiles)); - - GetMethod getMethod = new GetMethod(new URL(uriBuilder.build().toString())); - - getMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); - - int status = client.executeHttpMethod(getMethod); - - if (isSuccess(status)) { - // Parse xml response and obtain the list of shares - ShareToRemoteOperationResultParser parser = new ShareToRemoteOperationResultParser( - new ShareXMLParser() - ); - parser.setOwnCloudVersion(client.getOwnCloudVersion()); - parser.setServerBaseUri(client.getBaseUri()); - result = parser.parse(getMethod.getResponseBodyAsString()); - - if (result.isSuccess()) { - Log_OC.d(TAG, "Got " + result.getData().getShares().size() + " shares"); - } - } else { - result = new RemoteOperationResult<>(getMethod); - } - } catch (Exception e) { - result = new RemoteOperationResult<>(e); - Log_OC.e(TAG, "Exception while getting shares", e); - } - - return result; - } - - private boolean isSuccess(int status) { - return (status == HttpConstants.HTTP_OK); - } -} \ No newline at end of file diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteSharesForFileOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteSharesForFileOperation.kt new file mode 100644 index 00000000..321f170b --- /dev/null +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteSharesForFileOperation.kt @@ -0,0 +1,115 @@ +/* ownCloud Android Library is available under MIT license + * @author masensio + * @author David A. Velasco + * @author David González Verdugo + * Copyright (C) 2019 ownCloud GmbH. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.resources.shares + +import com.owncloud.android.lib.common.OwnCloudClient +import com.owncloud.android.lib.common.http.HttpConstants +import com.owncloud.android.lib.common.http.methods.nonwebdav.GetMethod +import com.owncloud.android.lib.common.operations.RemoteOperation +import com.owncloud.android.lib.common.operations.RemoteOperationResult +import com.owncloud.android.lib.common.utils.Log_OC +import java.net.URL + +/** + * Provide a list shares for a specific file. + * The input is the full path of the desired file. + * The output is a list of everyone who has the file shared with them. + * + * @author masensio + * @author David A. Velasco + * @author David González Verdugo + */ + +/** + * Constructor + * + * @param remoteFilePath Path to file or folder + * @param reshares If set to false (default), only shares owned by the current user are + * returned. + * If set to true, shares owned by any user from the given file are returned. + * @param subfiles If set to false (default), lists only the folder being shared + * If set to true, all shared files within the folder are returned. + */ +class GetRemoteSharesForFileOperation( + private val remoteFilePath: String, + private val reshares: Boolean, + private val subfiles: Boolean +) : RemoteOperation() { + + override fun run(client: OwnCloudClient): RemoteOperationResult { + var result: RemoteOperationResult + + try { + + val requestUri = client.baseUri + val uriBuilder = requestUri.buildUpon() + uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH) + uriBuilder.appendQueryParameter(PARAM_PATH, remoteFilePath) + uriBuilder.appendQueryParameter(PARAM_RESHARES, reshares.toString()) + uriBuilder.appendQueryParameter(PARAM_SUBFILES, subfiles.toString()) + + val getMethod = GetMethod(URL(uriBuilder.build().toString())) + + getMethod.addRequestHeader(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE) + + val status = client.executeHttpMethod(getMethod) + + if (isSuccess(status)) { + // Parse xml response and obtain the list of shares + val parser = ShareToRemoteOperationResultParser( + ShareXMLParser() + ) + parser.ownCloudVersion = client.ownCloudVersion + parser.serverBaseUri = client.baseUri + result = parser.parse(getMethod.responseBodyAsString) + + if (result.isSuccess) { + Log_OC.d(TAG, "Got " + result.data.shares.size + " shares") + } + } else { + result = RemoteOperationResult(getMethod) + } + } catch (e: Exception) { + result = RemoteOperationResult(e) + Log_OC.e(TAG, "Exception while getting shares", e) + } + + return result + } + + private fun isSuccess(status: Int): Boolean = status == HttpConstants.HTTP_OK + + companion object { + + private val TAG = GetRemoteSharesForFileOperation::class.java.simpleName + + private const val PARAM_PATH = "path" + private const val PARAM_RESHARES = "reshares" + private const val PARAM_SUBFILES = "subfiles" + } +} \ No newline at end of file diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/OCShare.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/OCShare.java deleted file mode 100644 index 72bccd50..00000000 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/OCShare.java +++ /dev/null @@ -1,356 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2019 ownCloud GmbH. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.lib.resources.shares; - -import java.io.File; -import java.io.Serializable; - -import android.os.Parcel; -import android.os.Parcelable; - -import com.owncloud.android.lib.common.utils.Log_OC; -import com.owncloud.android.lib.resources.files.FileUtils; - - -/** - * Contains the data of a Share from the Share API - * - * @author masensio - * @author David A. Velasco - * @author David González Verdugo - */ -public class OCShare implements Parcelable, Serializable { - - /** - * Generated - should be refreshed every time the class changes!! - */ - private static final long serialVersionUID = 4124975224281327921L; - - private static final String TAG = OCShare.class.getSimpleName(); - - public static final int DEFAULT_PERMISSION = -1; - public static final int READ_PERMISSION_FLAG = 1; - public static final int UPDATE_PERMISSION_FLAG = 2; - public static final int CREATE_PERMISSION_FLAG = 4; - public static final int DELETE_PERMISSION_FLAG = 8; - public static final int SHARE_PERMISSION_FLAG = 16; - public static final int MAXIMUM_PERMISSIONS_FOR_FILE = - READ_PERMISSION_FLAG + - UPDATE_PERMISSION_FLAG + - SHARE_PERMISSION_FLAG; - public static final int MAXIMUM_PERMISSIONS_FOR_FOLDER = - MAXIMUM_PERMISSIONS_FOR_FILE + - CREATE_PERMISSION_FLAG + - DELETE_PERMISSION_FLAG; - public static final int FEDERATED_PERMISSIONS_FOR_FILE_UP_TO_OC9 = - READ_PERMISSION_FLAG + - UPDATE_PERMISSION_FLAG; - public static final int FEDERATED_PERMISSIONS_FOR_FILE_AFTER_OC9 = - READ_PERMISSION_FLAG + - UPDATE_PERMISSION_FLAG + - SHARE_PERMISSION_FLAG; - public static final int FEDERATED_PERMISSIONS_FOR_FOLDER_UP_TO_OC9 = - READ_PERMISSION_FLAG + - UPDATE_PERMISSION_FLAG + - CREATE_PERMISSION_FLAG + - DELETE_PERMISSION_FLAG; - public static final int FEDERATED_PERMISSIONS_FOR_FOLDER_AFTER_OC9 = - FEDERATED_PERMISSIONS_FOR_FOLDER_UP_TO_OC9 + - SHARE_PERMISSION_FLAG; - - private long mId; - private long mFileSource; - private long mItemSource; - private ShareType mShareType; - private String mShareWith; - private String mPath; - private int mPermissions; - private long mSharedDate; - private long mExpirationDate; - private String mToken; - private String mSharedWithDisplayName; - private String mSharedWithAdditionalInfo; - private String mName; - private boolean mIsFolder; - private long mUserId; - private long mRemoteId; - private String mShareLink; - - public OCShare() { - super(); - resetData(); - } - - public OCShare(String path) { - resetData(); - if (path == null || path.length() <= 0 || !path.startsWith(FileUtils.PATH_SEPARATOR)) { - Log_OC.e(TAG, "Trying to create a OCShare with a non valid path"); - throw new IllegalArgumentException("Trying to create a OCShare with a non valid path: " + path); - } - mPath = path; - } - - /** - * Used internally. Reset all file properties - */ - private void resetData() { - mId = -1; - mFileSource = 0; - mItemSource = 0; - mShareType = ShareType.NO_SHARED; - mShareWith = ""; - mPath = ""; - mPermissions = -1; - mSharedDate = 0; - mExpirationDate = 0; - mToken = ""; - mSharedWithDisplayName = ""; - mSharedWithAdditionalInfo = ""; - mIsFolder = false; - mUserId = -1; - mRemoteId = -1; - mShareLink = ""; - mName = ""; - } - - /// Getters and Setters - - public long getId() { - return mId; - } - - public void setId(long id) { - mId = id; - } - - public long getFileSource() { - return mFileSource; - } - - public void setFileSource(long fileSource) { - this.mFileSource = fileSource; - } - - public long getItemSource() { - return mItemSource; - } - - public void setItemSource(long itemSource) { - this.mItemSource = itemSource; - } - - public ShareType getShareType() { - return mShareType; - } - - public void setShareType(ShareType shareType) { - this.mShareType = shareType; - } - - public String getShareWith() { - return mShareWith; - } - - public void setShareWith(String shareWith) { - this.mShareWith = (shareWith != null) ? shareWith : ""; - } - - public String getPath() { - return mPath; - } - - public void setPath(String path) { - this.mPath = (path != null) ? path : ""; - } - - public int getPermissions() { - return mPermissions; - } - - public void setPermissions(int permissions) { - this.mPermissions = permissions; - } - - public long getSharedDate() { - return mSharedDate; - } - - public void setSharedDate(long sharedDate) { - this.mSharedDate = sharedDate; - } - - public long getExpirationDate() { - return mExpirationDate; - } - - public void setExpirationDate(long expirationDate) { - this.mExpirationDate = expirationDate; - } - - public String getToken() { - return mToken; - } - - public void setToken(String token) { - this.mToken = (token != null) ? token : ""; - } - - public String getSharedWithDisplayName() { - return mSharedWithDisplayName; - } - - public void setSharedWithDisplayName(String sharedWithDisplayName) { - this.mSharedWithDisplayName = (sharedWithDisplayName != null) ? sharedWithDisplayName : ""; - } - - public String getSharedWithAdditionalInfo() { - return mSharedWithAdditionalInfo; - } - - public void setSharedWithAdditionalInfo(String sharedWithAdditionalInfo) { - this.mSharedWithAdditionalInfo = sharedWithAdditionalInfo; - } - - public String getName() { - return mName; - } - - public void setName(String name) { - mName = (name != null) ? name : ""; - } - - public boolean isFolder() { - return mIsFolder; - } - - public void setIsFolder(boolean isFolder) { - this.mIsFolder = isFolder; - } - - public long getUserId() { - return mUserId; - } - - public void setUserId(long userId) { - this.mUserId = userId; - } - - public long getRemoteId() { - return mRemoteId; - } - - public void setIdRemoteShared(long remoteId) { - this.mRemoteId = remoteId; - } - - public String getShareLink() { - return this.mShareLink; - } - - public void setShareLink(String shareLink) { - this.mShareLink = (shareLink != null) ? shareLink : ""; - } - - public boolean isPasswordProtected() { - return ShareType.PUBLIC_LINK.equals(mShareType) && mShareWith.length() > 0; - } - - /** - * Parcelable Methods - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public OCShare createFromParcel(Parcel source) { - return new OCShare(source); - } - - @Override - public OCShare[] newArray(int size) { - return new OCShare[size]; - } - }; - - /** - * Reconstruct from parcel - * - * @param source The source parcel - */ - protected OCShare(Parcel source) { - readFromParcel(source); - } - - public void readFromParcel(Parcel source) { - mId = source.readLong(); - - mFileSource = source.readLong(); - mItemSource = source.readLong(); - try { - mShareType = ShareType.valueOf(source.readString()); - } catch (IllegalArgumentException x) { - mShareType = ShareType.NO_SHARED; - } - mShareWith = source.readString(); - mPath = source.readString(); - mPermissions = source.readInt(); - mSharedDate = source.readLong(); - mExpirationDate = source.readLong(); - mToken = source.readString(); - mSharedWithDisplayName = source.readString(); - mSharedWithAdditionalInfo = source.readString(); - mIsFolder = source.readInt() == 0; - mUserId = source.readLong(); - mRemoteId = source.readLong(); - mShareLink = source.readString(); - mName = source.readString(); - } - - - @Override - public int describeContents() { - return this.hashCode(); - } - - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeLong(mId); - dest.writeLong(mFileSource); - dest.writeLong(mItemSource); - dest.writeString((mShareType == null) ? "" : mShareType.name()); - dest.writeString(mShareWith); - dest.writeString(mPath); - dest.writeInt(mPermissions); - dest.writeLong(mSharedDate); - dest.writeLong(mExpirationDate); - dest.writeString(mToken); - dest.writeString(mSharedWithDisplayName); - dest.writeString(mSharedWithAdditionalInfo); - dest.writeInt(mIsFolder ? 1 : 0); - dest.writeLong(mUserId); - dest.writeLong(mRemoteId); - dest.writeString(mShareLink); - dest.writeString(mName); - } -} \ No newline at end of file diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/RemoteShare.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/RemoteShare.kt new file mode 100644 index 00000000..de669db6 --- /dev/null +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/RemoteShare.kt @@ -0,0 +1,198 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2019 ownCloud GmbH. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.resources.shares + +import android.os.Parcel +import android.os.Parcelable +import com.owncloud.android.lib.common.utils.Log_OC +import com.owncloud.android.lib.resources.files.FileUtils +import java.io.Serializable + +/** + * Contains the data of a Share from the Share API + * + * @author masensio + * @author David A. Velasco + * @author David González Verdugo + */ +class RemoteShare : Parcelable, Serializable { + var id: Long = 0 + var shareWith: String = "" + var path: String = "" + var token: String = "" + var sharedWithDisplayName: String = "" + var sharedWithAdditionalInfo: String = "" + var name: String = "" + var shareLink: String = "" + var fileSource: Long = 0 + var itemSource: Long = 0 + var shareType: ShareType? = null + var permissions: Int = DEFAULT_PERMISSION + var sharedDate: Long = INIT_SHARED_DATE + var expirationDate: Long = INIT_EXPIRATION_DATE_IN_MILLIS + var isFolder: Boolean = path.endsWith(FileUtils.PATH_SEPARATOR) + var userId: Long = 0 + + val isValid: Boolean = id > -1 + + constructor() : super() { + resetData() + } + + constructor(path: String?) { + resetData() + if (path.isNullOrEmpty() || !path.startsWith(FileUtils.PATH_SEPARATOR)) { + Log_OC.e(TAG, "Trying to create a RemoteShare with a non valid path") + throw IllegalArgumentException("Trying to create a RemoteShare with a non valid path: " + path!!) + } + this.path = path + } + + /** + * Used internally. Reset all file properties + */ + private fun resetData() { + id = -1 + shareWith = "" + path = "" + token = "" + sharedWithDisplayName = "" + sharedWithAdditionalInfo = "" + name = "" + shareLink = "" + fileSource = 0 + itemSource = 0 + shareType = ShareType.NO_SHARED + permissions = DEFAULT_PERMISSION + sharedDate = INIT_SHARED_DATE + expirationDate = INIT_EXPIRATION_DATE_IN_MILLIS + sharedWithAdditionalInfo = "" + isFolder = false + userId = -1 + } + + /** + * Reconstruct from parcel + * + * @param source The source parcel + */ + protected constructor(source: Parcel) { + readFromParcel(source) + } + + fun readFromParcel(source: Parcel) { + id = source.readLong() + shareWith = source.readString() + path = source.readString() + token = source.readString() + sharedWithDisplayName = source.readString() + sharedWithAdditionalInfo = source.readString() + name = source.readString() + shareLink = source.readString() + fileSource = source.readLong() + itemSource = source.readLong() + try { + shareType = ShareType.valueOf(source.readString()) + } catch (x: IllegalArgumentException) { + shareType = ShareType.NO_SHARED + } + permissions = source.readInt() + sharedDate = source.readLong() + expirationDate = source.readLong() + isFolder = source.readInt() == 0 + userId = source.readLong() + } + + override fun describeContents(): Int = this.hashCode() + + override fun writeToParcel(dest: Parcel, flags: Int) { + dest.writeLong(id) + dest.writeString(shareWith) + dest.writeString(path) + dest.writeString(token) + dest.writeString(sharedWithDisplayName) + dest.writeString(sharedWithAdditionalInfo) + dest.writeString(name) + dest.writeString(shareLink) + dest.writeLong(fileSource) + dest.writeLong(itemSource) + dest.writeString(shareType?.name ?: "") + dest.writeInt(permissions) + dest.writeLong(sharedDate) + dest.writeLong(expirationDate) + dest.writeInt(if (isFolder) 1 else 0) + dest.writeLong(userId) + } + + companion object { + + /** + * Generated - should be refreshed every time the class changes!! + */ + private const val serialVersionUID = 4124975224281327921L + + private val TAG = RemoteShare::class.java.simpleName + + const val DEFAULT_PERMISSION = -1 + const val READ_PERMISSION_FLAG = 1 + const val UPDATE_PERMISSION_FLAG = 2 + const val CREATE_PERMISSION_FLAG = 4 + const val DELETE_PERMISSION_FLAG = 8 + const val SHARE_PERMISSION_FLAG = 16 + const val MAXIMUM_PERMISSIONS_FOR_FILE = READ_PERMISSION_FLAG + + UPDATE_PERMISSION_FLAG + + SHARE_PERMISSION_FLAG + const val MAXIMUM_PERMISSIONS_FOR_FOLDER = MAXIMUM_PERMISSIONS_FOR_FILE + + CREATE_PERMISSION_FLAG + + DELETE_PERMISSION_FLAG + const val FEDERATED_PERMISSIONS_FOR_FILE_UP_TO_OC9 = READ_PERMISSION_FLAG + UPDATE_PERMISSION_FLAG + const val FEDERATED_PERMISSIONS_FOR_FILE_AFTER_OC9 = READ_PERMISSION_FLAG + + UPDATE_PERMISSION_FLAG + + SHARE_PERMISSION_FLAG + const val FEDERATED_PERMISSIONS_FOR_FOLDER_UP_TO_OC9 = READ_PERMISSION_FLAG + + UPDATE_PERMISSION_FLAG + + CREATE_PERMISSION_FLAG + + DELETE_PERMISSION_FLAG + const val FEDERATED_PERMISSIONS_FOR_FOLDER_AFTER_OC9 = + FEDERATED_PERMISSIONS_FOR_FOLDER_UP_TO_OC9 + SHARE_PERMISSION_FLAG + + const val INIT_EXPIRATION_DATE_IN_MILLIS: Long = 0 + const val INIT_SHARED_DATE: Long = 0 + + /** + * Parcelable Methods + */ + @JvmField + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(source: Parcel): RemoteShare { + return RemoteShare(source) + } + + override fun newArray(size: Int): Array { + return arrayOfNulls(size) + } + } + } +} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/RemoveRemoteShareOperation.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/RemoveRemoteShareOperation.kt similarity index 50% rename from owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/RemoveRemoteShareOperation.java rename to owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/RemoveRemoteShareOperation.kt index c3edaa2d..d4deda06 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/RemoveRemoteShareOperation.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/RemoveRemoteShareOperation.kt @@ -25,18 +25,15 @@ * */ -package com.owncloud.android.lib.resources.shares; +package com.owncloud.android.lib.resources.shares -import android.net.Uri; - -import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.http.HttpConstants; -import com.owncloud.android.lib.common.http.methods.nonwebdav.DeleteMethod; -import com.owncloud.android.lib.common.operations.RemoteOperation; -import com.owncloud.android.lib.common.operations.RemoteOperationResult; -import com.owncloud.android.lib.common.utils.Log_OC; - -import java.net.URL; +import com.owncloud.android.lib.common.OwnCloudClient +import com.owncloud.android.lib.common.http.HttpConstants +import com.owncloud.android.lib.common.http.methods.nonwebdav.DeleteMethod +import com.owncloud.android.lib.common.operations.RemoteOperation +import com.owncloud.android.lib.common.operations.RemoteOperationResult +import com.owncloud.android.lib.common.utils.Log_OC +import java.net.URL /** * Remove a share @@ -46,63 +43,56 @@ import java.net.URL; * @author David González Verdugo */ -public class RemoveRemoteShareOperation extends RemoteOperation { +/** + * Constructor + * + * @param remoteShareId Share ID + */ +class RemoveRemoteShareOperation(private val remoteShareId: Long) : RemoteOperation() { - private static final String TAG = RemoveRemoteShareOperation.class.getSimpleName(); - - private int mRemoteShareId; - - /** - * Constructor - * - * @param remoteShareId Share ID - */ - - public RemoveRemoteShareOperation(int remoteShareId) { - mRemoteShareId = remoteShareId; - } - - @Override - protected RemoteOperationResult run(OwnCloudClient client) { - RemoteOperationResult result; + override fun run(client: OwnCloudClient): RemoteOperationResult { + var result: RemoteOperationResult try { - Uri requestUri = client.getBaseUri(); - Uri.Builder uriBuilder = requestUri.buildUpon(); - uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH); - uriBuilder.appendEncodedPath(String.valueOf(mRemoteShareId)); + val requestUri = client.baseUri + val uriBuilder = requestUri.buildUpon() + uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH) + uriBuilder.appendEncodedPath(remoteShareId.toString()) - DeleteMethod deleteMethod = new DeleteMethod( - new URL(uriBuilder.build().toString()) - ); + val deleteMethod = DeleteMethod( + URL(uriBuilder.build().toString()) + ) - deleteMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); + deleteMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE) - int status = client.executeHttpMethod(deleteMethod); + val status = client.executeHttpMethod(deleteMethod) if (isSuccess(status)) { // Parse xml response and obtain the list of shares - ShareToRemoteOperationResultParser parser = new ShareToRemoteOperationResultParser( - new ShareXMLParser() - ); - result = parser.parse(deleteMethod.getResponseBodyAsString()); + val parser = ShareToRemoteOperationResultParser( + ShareXMLParser() + ) + result = parser.parse(deleteMethod.responseBodyAsString) - Log_OC.d(TAG, "Unshare " + mRemoteShareId + ": " + result.getLogMessage()); + Log_OC.d(TAG, "Unshare " + remoteShareId + ": " + result.logMessage) } else { - result = new RemoteOperationResult<>(deleteMethod); + result = RemoteOperationResult(deleteMethod) } - } catch (Exception e) { - result = new RemoteOperationResult<>(e); - Log_OC.e(TAG, "Unshare Link Exception " + result.getLogMessage(), e); + } catch (e: Exception) { + result = RemoteOperationResult(e) + Log_OC.e(TAG, "Unshare Link Exception " + result.logMessage, e) } - return result; + return result } - private boolean isSuccess(int status) { - return (status == HttpConstants.HTTP_OK); + private fun isSuccess(status: Int): Boolean = status == HttpConstants.HTTP_OK + + companion object { + + private val TAG = RemoveRemoteShareOperation::class.java.simpleName } } \ No newline at end of file diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareParserResult.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareParserResult.kt similarity index 71% rename from owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareParserResult.java rename to owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareParserResult.kt index c98fd6e3..bd0920a6 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareParserResult.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareParserResult.kt @@ -23,24 +23,6 @@ * */ -package com.owncloud.android.lib.resources.shares; +package com.owncloud.android.lib.resources.shares -import java.util.ArrayList; - -public class ShareParserResult { - private ArrayList shares; - private String parserMessage; - - public ShareParserResult(ArrayList shares, String parserMessage) { - this.shares = shares; - this.parserMessage = parserMessage; - } - - public ArrayList getShares() { - return shares; - } - - public String getParserMessage() { - return parserMessage; - } -} \ No newline at end of file +class ShareParserResult(val shares: List) diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/SharePermissionsBuilder.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/SharePermissionsBuilder.kt similarity index 70% rename from owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/SharePermissionsBuilder.java rename to owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/SharePermissionsBuilder.kt index 2b0682dd..2f503ac1 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/SharePermissionsBuilder.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/SharePermissionsBuilder.kt @@ -1,6 +1,6 @@ /* ownCloud Android Library is available under MIT license * @author David A. Velasco - * Copyright (C) 2016 ownCloud GmbH. + * Copyright (C) 2019 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 @@ -23,18 +23,16 @@ * */ -package com.owncloud.android.lib.resources.shares; +package com.owncloud.android.lib.resources.shares /** * Provides method to define a set of share permissions and calculate the appropiate * int value representing it. */ -public class SharePermissionsBuilder { +class SharePermissionsBuilder { - /** - * Set of permissions - */ - private int mPermissions = OCShare.READ_PERMISSION_FLAG; // READ is minimum permission + /** Set of permissions */ + private var permissions = RemoteShare.READ_PERMISSION_FLAG // READ is minimum permission /** * Sets or clears permission to reshare a file or folder. @@ -42,9 +40,9 @@ public class SharePermissionsBuilder { * @param enabled 'True' to set, 'false' to clear. * @return Instance to builder itself, to allow consecutive calls to setters */ - public SharePermissionsBuilder setSharePermission(boolean enabled) { - updatePermission(OCShare.SHARE_PERMISSION_FLAG, enabled); - return this; + fun setSharePermission(enabled: Boolean): SharePermissionsBuilder { + updatePermission(RemoteShare.SHARE_PERMISSION_FLAG, enabled) + return this } /** @@ -53,9 +51,9 @@ public class SharePermissionsBuilder { * @param enabled 'True' to set, 'false' to clear. * @return Instance to builder itself, to allow consecutive calls to setters */ - public SharePermissionsBuilder setUpdatePermission(boolean enabled) { - updatePermission(OCShare.UPDATE_PERMISSION_FLAG, enabled); - return this; + fun setUpdatePermission(enabled: Boolean): SharePermissionsBuilder { + updatePermission(RemoteShare.UPDATE_PERMISSION_FLAG, enabled) + return this } /** @@ -64,9 +62,9 @@ public class SharePermissionsBuilder { * @param enabled 'True' to set, 'false' to clear. * @return Instance to builder itself, to allow consecutive calls to setters */ - public SharePermissionsBuilder setCreatePermission(boolean enabled) { - updatePermission(OCShare.CREATE_PERMISSION_FLAG, enabled); - return this; + fun setCreatePermission(enabled: Boolean): SharePermissionsBuilder { + updatePermission(RemoteShare.CREATE_PERMISSION_FLAG, enabled) + return this } /** @@ -75,9 +73,9 @@ public class SharePermissionsBuilder { * @param enabled 'True' to set, 'false' to clear. * @return Instance to builder itself, to allow consecutive calls to setters */ - public SharePermissionsBuilder setDeletePermission(boolean enabled) { - updatePermission(OCShare.DELETE_PERMISSION_FLAG, enabled); - return this; + fun setDeletePermission(enabled: Boolean): SharePermissionsBuilder { + updatePermission(RemoteShare.DELETE_PERMISSION_FLAG, enabled) + return this } /** @@ -86,13 +84,13 @@ public class SharePermissionsBuilder { * @param permissionsFlag Flag for the permission to update. * @param enable 'True' to set, 'false' to clear. */ - private void updatePermission(int permissionsFlag, boolean enable) { + private fun updatePermission(permissionsFlag: Int, enable: Boolean) { if (enable) { // add permission - mPermissions |= permissionsFlag; + permissions = permissions or permissionsFlag } else { // delete permission - mPermissions &= ~permissionsFlag; + permissions = permissions and permissionsFlag.inv() } } @@ -101,7 +99,5 @@ public class SharePermissionsBuilder { * * @return An int value representing the accumulated set of permissions. */ - public int build() { - return mPermissions; - } + fun build(): Int = permissions } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareToRemoteOperationResultParser.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareToRemoteOperationResultParser.java deleted file mode 100644 index 5b6aa671..00000000 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareToRemoteOperationResultParser.java +++ /dev/null @@ -1,140 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * @author David A. Velasco - * @author David González Verdugo - * @author Christian Schabesberger - * Copyright (C) 2019 ownCloud GmbH. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.lib.resources.shares; - -import android.net.Uri; - -import com.owncloud.android.lib.common.operations.RemoteOperationResult; -import com.owncloud.android.lib.common.utils.Log_OC; -import com.owncloud.android.lib.resources.status.OwnCloudVersion; -import org.xmlpull.v1.XmlPullParserException; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -public class ShareToRemoteOperationResultParser { - - private static final String TAG = ShareToRemoteOperationResultParser.class.getSimpleName(); - - private ShareXMLParser mShareXmlParser = null; - private boolean mOneOrMoreSharesRequired = false; - private OwnCloudVersion mOwnCloudVersion = null; - private Uri mServerBaseUri = null; - - public ShareToRemoteOperationResultParser(ShareXMLParser shareXmlParser) { - mShareXmlParser = shareXmlParser; - } - - public void setOneOrMoreSharesRequired(boolean oneOrMoreSharesRequired) { - mOneOrMoreSharesRequired = oneOrMoreSharesRequired; - } - - public void setOwnCloudVersion(OwnCloudVersion ownCloudVersion) { - mOwnCloudVersion = ownCloudVersion; - } - - public void setServerBaseUri(Uri serverBaseURi) { - mServerBaseUri = serverBaseURi; - } - - public RemoteOperationResult parse(String serverResponse) { - if (serverResponse == null || serverResponse.length() == 0) { - return new RemoteOperationResult<>(RemoteOperationResult.ResultCode.WRONG_SERVER_RESPONSE); - } - - RemoteOperationResult result; - final ArrayList resultData = new ArrayList<>(); - - try { - // Parse xml response and obtain the list of shares - InputStream is = new ByteArrayInputStream(serverResponse.getBytes()); - if (mShareXmlParser == null) { - Log_OC.w(TAG, "No ShareXmlParser provided, creating new instance "); - mShareXmlParser = new ShareXMLParser(); - } - List shares = mShareXmlParser.parseXMLResponse(is); - - if (mShareXmlParser.isSuccess()) { - if ((shares != null && shares.size() > 0) || !mOneOrMoreSharesRequired) { - result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.OK); - if (shares != null) { - for (OCShare share : shares) { - resultData.add(share); - // build the share link if not in the response - // (needed for OC servers < 9.0.0, see ShareXMLParser.java#line256) - if (share.getShareType() == ShareType.PUBLIC_LINK - && (share.getShareLink() == null - || share.getShareLink().length() <= 0) - && share.getToken().length() > 0) { - if (mServerBaseUri != null) { - String sharingLinkPath = ShareUtils.getSharingLinkPath(mOwnCloudVersion); - share.setShareLink(mServerBaseUri + sharingLinkPath + share.getToken()); - } else { - Log_OC.e(TAG, "Couldn't build link for public share :("); - } - } - } - } - result.setData(new ShareParserResult(resultData, "")); - - } else { - result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.WRONG_SERVER_RESPONSE); - Log_OC.e(TAG, "Successful status with no share in the response"); - } - - } else if (mShareXmlParser.isWrongParameter()) { - result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.SHARE_WRONG_PARAMETER); - result.setData(new ShareParserResult(null, mShareXmlParser.getMessage())); - - } else if (mShareXmlParser.isNotFound()) { - result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND); - result.setData(new ShareParserResult(null, mShareXmlParser.getMessage())); - - } else if (mShareXmlParser.isForbidden()) { - result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.SHARE_FORBIDDEN); - result.setData(new ShareParserResult(null, mShareXmlParser.getMessage())); - - } else { - result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.WRONG_SERVER_RESPONSE); - } - - } catch (XmlPullParserException e) { - Log_OC.e(TAG, "Error parsing response from server ", e); - result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.WRONG_SERVER_RESPONSE); - - } catch (IOException e) { - Log_OC.e(TAG, "Error reading response from server ", e); - result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.WRONG_SERVER_RESPONSE); - } - - return result; - } -} \ No newline at end of file diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareToRemoteOperationResultParser.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareToRemoteOperationResultParser.kt new file mode 100644 index 00000000..c3e23f3f --- /dev/null +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareToRemoteOperationResultParser.kt @@ -0,0 +1,122 @@ +/* ownCloud Android Library is available under MIT license + * @author David A. Velasco + * @author David González Verdugo + * @author Christian Schabesberger + * Copyright (C) 2019 ownCloud GmbH. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.resources.shares + +import android.net.Uri +import com.owncloud.android.lib.common.operations.RemoteOperationResult +import com.owncloud.android.lib.common.utils.Log_OC +import com.owncloud.android.lib.resources.status.OwnCloudVersion +import org.xmlpull.v1.XmlPullParserException +import java.io.ByteArrayInputStream +import java.io.IOException +import java.util.ArrayList + +class ShareToRemoteOperationResultParser(private var shareXmlParser: ShareXMLParser?) { + var oneOrMoreSharesRequired = false + var ownCloudVersion: OwnCloudVersion? = null + var serverBaseUri: Uri? = null + + fun parse(serverResponse: String?): RemoteOperationResult { + if (serverResponse.isNullOrEmpty()) { + return RemoteOperationResult(RemoteOperationResult.ResultCode.WRONG_SERVER_RESPONSE) + } + + var result: RemoteOperationResult + var resultData: List? + + try { + // Parse xml response and obtain the list of shares + val byteArrayServerResponse = ByteArrayInputStream(serverResponse.toByteArray()) + if (shareXmlParser == null) { + Log_OC.w(TAG, "No ShareXmlParser provided, creating new instance ") + shareXmlParser = ShareXMLParser() + } + val shares = shareXmlParser?.parseXMLResponse(byteArrayServerResponse) + + when { + shareXmlParser?.isSuccess!! -> { + if (!shares.isNullOrEmpty() || !oneOrMoreSharesRequired) { + result = RemoteOperationResult(RemoteOperationResult.ResultCode.OK) + + resultData = shares?.map { share -> + if (share.shareType != ShareType.PUBLIC_LINK || + share.shareLink.isNotEmpty() || + share.token.isEmpty() + ) { + return@map share + } + + if (serverBaseUri != null) { + val sharingLinkPath = ShareUtils.getSharingLinkPath(ownCloudVersion) + share.shareLink = serverBaseUri.toString() + sharingLinkPath + share.token + } else { + Log_OC.e(TAG, "Couldn't build link for public share :(") + } + + share + } + + result.setData(ShareParserResult(ArrayList(resultData))) + + } else { + result = RemoteOperationResult(RemoteOperationResult.ResultCode.WRONG_SERVER_RESPONSE) + Log_OC.e(TAG, "Successful status with no share in the response") + } + } + shareXmlParser?.isWrongParameter!! -> { + result = RemoteOperationResult(RemoteOperationResult.ResultCode.SHARE_WRONG_PARAMETER) + result.httpPhrase = shareXmlParser?.message + } + shareXmlParser?.isNotFound!! -> { + result = RemoteOperationResult(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND) + result.httpPhrase = shareXmlParser?.message + } + shareXmlParser?.isForbidden!! -> { + result = RemoteOperationResult(RemoteOperationResult.ResultCode.SHARE_FORBIDDEN) + result.httpPhrase = shareXmlParser?.message + } + else -> { + result = RemoteOperationResult(RemoteOperationResult.ResultCode.WRONG_SERVER_RESPONSE) + } + } + } catch (e: XmlPullParserException) { + Log_OC.e(TAG, "Error parsing response from server ", e) + result = RemoteOperationResult(RemoteOperationResult.ResultCode.WRONG_SERVER_RESPONSE) + + } catch (e: IOException) { + Log_OC.e(TAG, "Error reading response from server ", e) + result = RemoteOperationResult(RemoteOperationResult.ResultCode.WRONG_SERVER_RESPONSE) + } + + return result + } + + companion object { + private val TAG = ShareToRemoteOperationResultParser::class.java.simpleName + } +} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareType.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareType.kt similarity index 67% rename from owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareType.java rename to owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareType.kt index e272abbd..234b4276 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareType.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareType.kt @@ -1,5 +1,5 @@ /* ownCloud Android Library is available under MIT license - * Copyright (C) 2016 ownCloud GmbH. + * Copyright (C) 2019 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 @@ -22,7 +22,7 @@ * */ -package com.owncloud.android.lib.resources.shares; +package com.owncloud.android.lib.resources.shares /** * Enum for Share Type, with values: @@ -32,11 +32,12 @@ package com.owncloud.android.lib.resources.shares; * 3 - Shared by public link * 4 - Shared by e-mail * 5 - Shared by contact + * 6 - Federated * * @author masensio */ -public enum ShareType { +enum class ShareType constructor(val value: Int) { NO_SHARED(-1), USER(0), GROUP(1), @@ -45,33 +46,19 @@ public enum ShareType { CONTACT(5), FEDERATED(6); - private int value; + companion object { - private ShareType(int value) { - this.value = value; - } - - public static ShareType fromValue(int value) { - switch (value) { - case -1: - return NO_SHARED; - case 0: - return USER; - case 1: - return GROUP; - case 3: - return PUBLIC_LINK; - case 4: - return EMAIL; - case 5: - return CONTACT; - case 6: - return FEDERATED; + fun fromValue(value: Int): ShareType? { + return when (value) { + -1 -> NO_SHARED + 0 -> USER + 1 -> GROUP + 3 -> PUBLIC_LINK + 4 -> EMAIL + 5 -> CONTACT + 6 -> FEDERATED + else -> null + } } - return null; } - - public int getValue() { - return value; - } -}; \ No newline at end of file +} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareXMLParser.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareXMLParser.java deleted file mode 100644 index a6265e1a..00000000 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareXMLParser.java +++ /dev/null @@ -1,452 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2019 ownCloud GmbH. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.lib.resources.shares; - -import android.util.Xml; - -import com.owncloud.android.lib.common.network.WebdavUtils; -import com.owncloud.android.lib.resources.files.FileUtils; - -import org.xmlpull.v1.XmlPullParser; -import org.xmlpull.v1.XmlPullParserException; -import org.xmlpull.v1.XmlPullParserFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; - -/** - * Parser for Share API Response - * - * @author masensio - * @author David González Verdugo - */ - -public class ShareXMLParser { - - //private static final String TAG = ShareXMLParser.class.getSimpleName(); - - // No namespaces - private static final String ns = null; - - // NODES for XML Parser - private static final String NODE_OCS = "ocs"; - - private static final String NODE_META = "meta"; - private static final String NODE_STATUS = "status"; - private static final String NODE_STATUS_CODE = "statuscode"; - private static final String NODE_MESSAGE = "message"; - - private static final String NODE_DATA = "data"; - private static final String NODE_ELEMENT = "element"; - private static final String NODE_ID = "id"; - private static final String NODE_ITEM_TYPE = "item_type"; - private static final String NODE_ITEM_SOURCE = "item_source"; - private static final String NODE_PARENT = "parent"; - private static final String NODE_SHARE_TYPE = "share_type"; - private static final String NODE_SHARE_WITH = "share_with"; - private static final String NODE_FILE_SOURCE = "file_source"; - private static final String NODE_PATH = "path"; - private static final String NODE_PERMISSIONS = "permissions"; - private static final String NODE_STIME = "stime"; - private static final String NODE_EXPIRATION = "expiration"; - private static final String NODE_TOKEN = "token"; - private static final String NODE_STORAGE = "storage"; - private static final String NODE_MAIL_SEND = "mail_send"; - private static final String NODE_SHARE_WITH_DISPLAY_NAME = "share_with_displayname"; - private static final String NODE_SHARE_WITH_ADDITIONAL_INFO = "share_with_additional_info"; - private static final String NODE_NAME = "name"; - - private static final String NODE_URL = "url"; - - private static final String TYPE_FOLDER = "folder"; - - private static final int SUCCESS = 200; - private static final int ERROR_WRONG_PARAMETER = 400; - private static final int ERROR_FORBIDDEN = 403; - private static final int ERROR_NOT_FOUND = 404; - - private String mStatus; - private int mStatusCode; - private String mMessage; - - // Getters and Setters - public String getStatus() { - return mStatus; - } - - public void setStatus(String status) { - this.mStatus = status; - } - - public int getStatusCode() { - return mStatusCode; - } - - public void setStatusCode(int statusCode) { - this.mStatusCode = statusCode; - } - - public String getMessage() { - return mMessage; - } - - public void setMessage(String message) { - this.mMessage = message; - } - - // Constructor - public ShareXMLParser() { - mStatusCode = -1; - } - - public boolean isSuccess() { - return mStatusCode == SUCCESS; - } - - public boolean isForbidden() { - return mStatusCode == ERROR_FORBIDDEN; - } - - public boolean isNotFound() { - return mStatusCode == ERROR_NOT_FOUND; - } - - public boolean isWrongParameter() { - return mStatusCode == ERROR_WRONG_PARAMETER; - } - - /** - * Parse is as response of Share API - * - * @param is - * @return List of ShareRemoteFiles - * @throws XmlPullParserException - * @throws IOException - */ - public ArrayList parseXMLResponse(InputStream is) throws XmlPullParserException, - IOException { - - 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(); - return readOCS(parser); - - } finally { - is.close(); - } - } - - /** - * Parse OCS node - * - * @param parser - * @return List of ShareRemoteFiles - * @throws XmlPullParserException - * @throws IOException - */ - private ArrayList readOCS(XmlPullParser parser) throws XmlPullParserException, - IOException { - ArrayList shares = new ArrayList<>(); - parser.require(XmlPullParser.START_TAG, ns, NODE_OCS); - while (parser.next() != XmlPullParser.END_TAG) { - if (parser.getEventType() != XmlPullParser.START_TAG) { - continue; - } - String name = parser.getName(); - // read NODE_META and NODE_DATA - if (name.equalsIgnoreCase(NODE_META)) { - readMeta(parser); - } else if (name.equalsIgnoreCase(NODE_DATA)) { - shares = readData(parser); - } else { - skip(parser); - } - - } - return shares; - } - - /** - * Parse Meta node - * - * @param parser - * @throws XmlPullParserException - * @throws IOException - */ - private void readMeta(XmlPullParser parser) throws XmlPullParserException, IOException { - parser.require(XmlPullParser.START_TAG, ns, NODE_META); - //Log_OC.d(TAG, "---- NODE META ---"); - while (parser.next() != XmlPullParser.END_TAG) { - if (parser.getEventType() != XmlPullParser.START_TAG) { - continue; - } - String name = parser.getName(); - - if (name.equalsIgnoreCase(NODE_STATUS)) { - setStatus(readNode(parser, NODE_STATUS)); - - } else if (name.equalsIgnoreCase(NODE_STATUS_CODE)) { - setStatusCode(Integer.parseInt(readNode(parser, NODE_STATUS_CODE))); - - } else if (name.equalsIgnoreCase(NODE_MESSAGE)) { - setMessage(readNode(parser, NODE_MESSAGE)); - - } else { - skip(parser); - } - - } - } - - /** - * Parse Data node - * - * @param parser - * @return - * @throws XmlPullParserException - * @throws IOException - */ - private ArrayList readData(XmlPullParser parser) throws XmlPullParserException, - IOException { - ArrayList shares = new ArrayList(); - OCShare share = null; - - parser.require(XmlPullParser.START_TAG, ns, NODE_DATA); - //Log_OC.d(TAG, "---- NODE DATA ---"); - while (parser.next() != XmlPullParser.END_TAG) { - if (parser.getEventType() != XmlPullParser.START_TAG) { - continue; - } - String name = parser.getName(); - if (name.equalsIgnoreCase(NODE_ELEMENT)) { - readElement(parser, shares); - - } else if (name.equalsIgnoreCase(NODE_ID)) {// Parse Create XML Response - share = new OCShare(); - String value = readNode(parser, NODE_ID); - share.setIdRemoteShared(Integer.parseInt(value)); - - } else if (name.equalsIgnoreCase(NODE_URL)) { - // NOTE: this field is received in all the public shares from OC 9.0.0 - // in previous versions, it's received in the result of POST requests, but not - // in GET requests - share.setShareType(ShareType.PUBLIC_LINK); - String value = readNode(parser, NODE_URL); - share.setShareLink(value); - - } else if (name.equalsIgnoreCase(NODE_TOKEN)) { - share.setToken(readNode(parser, NODE_TOKEN)); - - } else { - skip(parser); - - } - } - - if (share != null) { - // this is the response of a request for creation; don't pass to isValidShare() - shares.add(share); - } - - return shares; - - } - - - /** - * Parse Element node - * - * @param parser - * @return - * @throws XmlPullParserException - * @throws IOException - */ - private void readElement(XmlPullParser parser, ArrayList shares) - throws XmlPullParserException, IOException { - parser.require(XmlPullParser.START_TAG, ns, NODE_ELEMENT); - - OCShare share = new OCShare(); - - //Log_OC.d(TAG, "---- NODE ELEMENT ---"); - while (parser.next() != XmlPullParser.END_TAG) { - if (parser.getEventType() != XmlPullParser.START_TAG) { - continue; - } - - String name = parser.getName(); - - if (name.equalsIgnoreCase(NODE_ELEMENT)) { - // patch to work around servers responding with extra surrounding all - // the shares on the same file before - // https://github.com/owncloud/core/issues/6992 was fixed - readElement(parser, shares); - - } else if (name.equalsIgnoreCase(NODE_ID)) { - share.setIdRemoteShared(Integer.parseInt(readNode(parser, NODE_ID))); - - } else if (name.equalsIgnoreCase(NODE_ITEM_TYPE)) { - share.setIsFolder(readNode(parser, NODE_ITEM_TYPE).equalsIgnoreCase(TYPE_FOLDER)); - fixPathForFolder(share); - - } else if (name.equalsIgnoreCase(NODE_ITEM_SOURCE)) { - share.setItemSource(Long.parseLong(readNode(parser, NODE_ITEM_SOURCE))); - - } else if (name.equalsIgnoreCase(NODE_PARENT)) { - readNode(parser, NODE_PARENT); - - } else if (name.equalsIgnoreCase(NODE_SHARE_TYPE)) { - int value = Integer.parseInt(readNode(parser, NODE_SHARE_TYPE)); - share.setShareType(ShareType.fromValue(value)); - - } else if (name.equalsIgnoreCase(NODE_SHARE_WITH)) { - share.setShareWith(readNode(parser, NODE_SHARE_WITH)); - - } else if (name.equalsIgnoreCase(NODE_FILE_SOURCE)) { - share.setFileSource(Long.parseLong(readNode(parser, NODE_FILE_SOURCE))); - - } else if (name.equalsIgnoreCase(NODE_PATH)) { - share.setPath(readNode(parser, NODE_PATH)); - fixPathForFolder(share); - - } else if (name.equalsIgnoreCase(NODE_PERMISSIONS)) { - share.setPermissions(Integer.parseInt(readNode(parser, NODE_PERMISSIONS))); - - } else if (name.equalsIgnoreCase(NODE_STIME)) { - share.setSharedDate(Long.parseLong(readNode(parser, NODE_STIME))); - - } else if (name.equalsIgnoreCase(NODE_EXPIRATION)) { - String value = readNode(parser, NODE_EXPIRATION); - if (!(value.length() == 0)) { - share.setExpirationDate(WebdavUtils.parseResponseDate(value).getTime()); - } - - } else if (name.equalsIgnoreCase(NODE_TOKEN)) { - share.setToken(readNode(parser, NODE_TOKEN)); - - } else if (name.equalsIgnoreCase(NODE_STORAGE)) { - readNode(parser, NODE_STORAGE); - } else if (name.equalsIgnoreCase(NODE_MAIL_SEND)) { - readNode(parser, NODE_MAIL_SEND); - - } else if (name.equalsIgnoreCase(NODE_SHARE_WITH_DISPLAY_NAME)) { - share.setSharedWithDisplayName(readNode(parser, NODE_SHARE_WITH_DISPLAY_NAME)); - - } else if (name.equalsIgnoreCase(NODE_SHARE_WITH_ADDITIONAL_INFO)) { - share.setSharedWithAdditionalInfo(readNode(parser, NODE_SHARE_WITH_ADDITIONAL_INFO)); - - } else if (name.equalsIgnoreCase(NODE_URL)) { - String value = readNode(parser, NODE_URL); - share.setShareLink(value); - - } else if (name.equalsIgnoreCase(NODE_NAME)) { - share.setName(readNode(parser, NODE_NAME)); - - } else { - skip(parser); - } - } - - if (isValidShare(share)) { - shares.add(share); - } - } - - private boolean isValidShare(OCShare share) { - return (share.getRemoteId() > -1); - } - - private void fixPathForFolder(OCShare share) { - if (share.isFolder() && share.getPath() != null && share.getPath().length() > 0 && - !share.getPath().endsWith(FileUtils.PATH_SEPARATOR)) { - share.setPath(share.getPath() + FileUtils.PATH_SEPARATOR); - } - } - - /** - * Parse a node, to obtain its text. Needs readText method - * - * @param parser - * @param node - * @return Text of the node - * @throws XmlPullParserException - * @throws IOException - */ - private String readNode(XmlPullParser parser, String node) throws XmlPullParserException, - IOException { - parser.require(XmlPullParser.START_TAG, ns, node); - String value = readText(parser); - //Log_OC.d(TAG, "node= " + node + ", value= " + value); - parser.require(XmlPullParser.END_TAG, ns, node); - return value; - } - - /** - * 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; - } - - /** - * 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; - } - } - } -} \ No newline at end of file diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareXMLParser.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareXMLParser.kt new file mode 100644 index 00000000..df634321 --- /dev/null +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/ShareXMLParser.kt @@ -0,0 +1,433 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2019 ownCloud GmbH. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.resources.shares + +import android.util.Xml + +import com.owncloud.android.lib.common.network.WebdavUtils +import com.owncloud.android.lib.resources.files.FileUtils + +import org.xmlpull.v1.XmlPullParser +import org.xmlpull.v1.XmlPullParserException +import org.xmlpull.v1.XmlPullParserFactory + +import java.io.IOException +import java.io.InputStream +import java.util.ArrayList + +/** + * Parser for Share API Response + * + * @author masensio + * @author David González Verdugo + */ + +class ShareXMLParser { + // Getters and Setters + var status: String? = null + var statusCode: Int = 0 + var message: String? = null + + val isSuccess: Boolean + get() = statusCode == SUCCESS + + val isForbidden: Boolean + get() = statusCode == ERROR_FORBIDDEN + + val isNotFound: Boolean + get() = statusCode == ERROR_NOT_FOUND + + val isWrongParameter: Boolean + get() = statusCode == ERROR_WRONG_PARAMETER + + // Constructor + init { + statusCode = INIT + } + + /** + * Parse is as response of Share API + * @param inputStream + * @return List of ShareRemoteFiles + * @throws XmlPullParserException + * @throws IOException + */ + @Throws(XmlPullParserException::class, IOException::class) + fun parseXMLResponse(inputStream: InputStream): ArrayList { + + try { + // XMLPullParser + val factory = XmlPullParserFactory.newInstance() + factory.isNamespaceAware = true + + val parser = Xml.newPullParser() + parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false) + parser.setInput(inputStream, null) + parser.nextTag() + return readOCS(parser) + + } finally { + inputStream.close() + } + } + + /** + * Parse OCS node + * @param parser + * @return List of ShareRemoteFiles + * @throws XmlPullParserException + * @throws IOException + */ + @Throws(XmlPullParserException::class, IOException::class) + private fun readOCS(parser: XmlPullParser): ArrayList { + var shares = ArrayList() + parser.require(XmlPullParser.START_TAG, ns, NODE_OCS) + while (parser.next() != XmlPullParser.END_TAG) { + if (parser.eventType != XmlPullParser.START_TAG) { + continue + } + val name = parser.name + // read NODE_META and NODE_DATA + if (name.equals(NODE_META, ignoreCase = true)) { + readMeta(parser) + } else if (name.equals(NODE_DATA, ignoreCase = true)) { + shares = readData(parser) + } else { + skip(parser) + } + } + return shares + } + + /** + * Parse Meta node + * @param parser + * @throws XmlPullParserException + * @throws IOException + */ + @Throws(XmlPullParserException::class, IOException::class) + private fun readMeta(parser: XmlPullParser) { + parser.require(XmlPullParser.START_TAG, ns, NODE_META) + //Log_OC.d(TAG, "---- NODE META ---"); + while (parser.next() != XmlPullParser.END_TAG) { + if (parser.eventType != XmlPullParser.START_TAG) { + continue + } + val name = parser.name + + if (name.equals(NODE_STATUS, ignoreCase = true)) { + status = readNode(parser, NODE_STATUS) + + } else if (name.equals(NODE_STATUS_CODE, ignoreCase = true)) { + statusCode = Integer.parseInt(readNode(parser, NODE_STATUS_CODE)) + + } else if (name.equals(NODE_MESSAGE, ignoreCase = true)) { + message = readNode(parser, NODE_MESSAGE) + + } else { + skip(parser) + } + } + } + + /** + * Parse Data node + * @param parser + * @return + * @throws XmlPullParserException + * @throws IOException + */ + @Throws(XmlPullParserException::class, IOException::class) + private fun readData(parser: XmlPullParser): ArrayList { + val shares = ArrayList() + var share: RemoteShare? = null + + parser.require(XmlPullParser.START_TAG, ns, NODE_DATA) + //Log_OC.d(TAG, "---- NODE DATA ---"); + while (parser.next() != XmlPullParser.END_TAG) { + if (parser.eventType != XmlPullParser.START_TAG) { + continue + } + val name = parser.name + if (name.equals(NODE_ELEMENT, ignoreCase = true)) { + readElement(parser, shares) + + } else if (name.equals(NODE_ID, ignoreCase = true)) {// Parse Create XML Response + share = RemoteShare() + val value = readNode(parser, NODE_ID) + share.id = Integer.parseInt(value).toLong() + + } else if (name.equals(NODE_URL, ignoreCase = true)) { + // NOTE: this field is received in all the public shares from OC 9.0.0 + // in previous versions, it's received in the result of POST requests, but not + // in GET requests + share!!.shareType = ShareType.PUBLIC_LINK + val value = readNode(parser, NODE_URL) + share.shareLink = value + + } else if (name.equals(NODE_TOKEN, ignoreCase = true)) { + share!!.token = readNode(parser, NODE_TOKEN) + + } else { + skip(parser) + } + } + + if (share != null) { + // this is the response of a request for creation; don't pass to isValidShare() + shares.add(share) + } + + return shares + + } + + /** + * Parse Element node + * @param parser + * @return + * @throws XmlPullParserException + * @throws IOException + */ + @Throws(XmlPullParserException::class, IOException::class) + private fun readElement(parser: XmlPullParser, shares: ArrayList) { + parser.require(XmlPullParser.START_TAG, ns, NODE_ELEMENT) + + val remoteShare = RemoteShare() + + //Log_OC.d(TAG, "---- NODE ELEMENT ---"); + while (parser.next() != XmlPullParser.END_TAG) { + if (parser.eventType != XmlPullParser.START_TAG) { + continue + } + + val name = parser.name + + when { + name.equals(NODE_ELEMENT, ignoreCase = true) -> { + // patch to work around servers responding with extra surrounding all + // the shares on the same file before + // https://github.com/owncloud/core/issues/6992 was fixed + readElement(parser, shares) + } + + name.equals(NODE_ID, ignoreCase = true) -> { + remoteShare.id = Integer.parseInt(readNode(parser, NODE_ID)).toLong() + } + + name.equals(NODE_ITEM_TYPE, ignoreCase = true) -> { + remoteShare.isFolder = readNode(parser, NODE_ITEM_TYPE).equals(TYPE_FOLDER, ignoreCase = true) + fixPathForFolder(remoteShare) + } + + name.equals(NODE_ITEM_SOURCE, ignoreCase = true) -> { + remoteShare.itemSource = java.lang.Long.parseLong(readNode(parser, NODE_ITEM_SOURCE)) + } + + name.equals(NODE_PARENT, ignoreCase = true) -> { + readNode(parser, NODE_PARENT) + } + + name.equals(NODE_SHARE_TYPE, ignoreCase = true) -> { + val value = Integer.parseInt(readNode(parser, NODE_SHARE_TYPE)) + remoteShare.shareType = ShareType.fromValue(value) + } + + name.equals(NODE_SHARE_WITH, ignoreCase = true) -> { + remoteShare.shareWith = readNode(parser, NODE_SHARE_WITH) + } + + name.equals(NODE_FILE_SOURCE, ignoreCase = true) -> { + remoteShare.fileSource = java.lang.Long.parseLong(readNode(parser, NODE_FILE_SOURCE)) + } + + name.equals(NODE_PATH, ignoreCase = true) -> { + remoteShare.path = readNode(parser, NODE_PATH) + fixPathForFolder(remoteShare) + } + + name.equals(NODE_PERMISSIONS, ignoreCase = true) -> { + remoteShare.permissions = Integer.parseInt(readNode(parser, NODE_PERMISSIONS)) + } + + name.equals(NODE_STIME, ignoreCase = true) -> { + remoteShare.sharedDate = java.lang.Long.parseLong(readNode(parser, NODE_STIME)) + } + + name.equals(NODE_EXPIRATION, ignoreCase = true) -> { + val value = readNode(parser, NODE_EXPIRATION) + if (value.isNotEmpty()) { + remoteShare.expirationDate = WebdavUtils.parseResponseDate(value)!!.time + } + } + + name.equals(NODE_TOKEN, ignoreCase = true) -> { + remoteShare.token = readNode(parser, NODE_TOKEN) + } + + name.equals(NODE_STORAGE, ignoreCase = true) -> { + readNode(parser, NODE_STORAGE) + } + + name.equals(NODE_MAIL_SEND, ignoreCase = true) -> { + readNode(parser, NODE_MAIL_SEND) + } + + name.equals(NODE_SHARE_WITH_DISPLAY_NAME, ignoreCase = true) -> { + remoteShare.sharedWithDisplayName = readNode(parser, NODE_SHARE_WITH_DISPLAY_NAME) + } + + name.equals(NODE_SHARE_WITH_ADDITIONAL_INFO, ignoreCase = true) -> { + remoteShare.sharedWithAdditionalInfo = readNode(parser, NODE_SHARE_WITH_ADDITIONAL_INFO) + } + + name.equals(NODE_URL, ignoreCase = true) -> { + val value = readNode(parser, NODE_URL) + remoteShare.shareLink = value + } + + name.equals(NODE_NAME, ignoreCase = true) -> { + remoteShare.name = readNode(parser, NODE_NAME) + } + + else -> { + skip(parser) + } + } + } + + if (remoteShare.isValid) { + shares.add(remoteShare) + } + } + + private fun fixPathForFolder(share: RemoteShare) { + if (share.isFolder && share.path.isNotEmpty() && + !share.path.endsWith(FileUtils.PATH_SEPARATOR) + ) { + share.path = share.path + FileUtils.PATH_SEPARATOR + } + } + + /** + * Parse a node, to obtain its text. Needs readText method + * @param parser + * @param node + * @return Text of the node + * @throws XmlPullParserException + * @throws IOException + */ + @Throws(XmlPullParserException::class, IOException::class) + private fun readNode(parser: XmlPullParser, node: String): String { + parser.require(XmlPullParser.START_TAG, ns, node) + val value = readText(parser) + //Log_OC.d(TAG, "node= " + node + ", value= " + value); + parser.require(XmlPullParser.END_TAG, ns, node) + return value + } + + /** + * Read the text from a node + * @param parser + * @return Text of the node + * @throws IOException + * @throws XmlPullParserException + */ + @Throws(IOException::class, XmlPullParserException::class) + private fun readText(parser: XmlPullParser): String { + var result = "" + if (parser.next() == XmlPullParser.TEXT) { + result = parser.text + parser.nextTag() + } + return result + } + + /** + * Skip tags in parser procedure + * @param parser + * @throws XmlPullParserException + * @throws IOException + */ + @Throws(XmlPullParserException::class, IOException::class) + private fun skip(parser: XmlPullParser) { + if (parser.eventType != XmlPullParser.START_TAG) { + throw IllegalStateException() + } + var depth = 1 + while (depth != 0) { + when (parser.next()) { + XmlPullParser.END_TAG -> depth-- + XmlPullParser.START_TAG -> depth++ + } + } + } + + companion object { + + //private static final String TAG = ShareXMLParser.class.getSimpleName(); + + // No namespaces + private val ns: String? = null + + // NODES for XML Parser + private const val NODE_OCS = "ocs" + + private const val NODE_META = "meta" + private const val NODE_STATUS = "status" + private const val NODE_STATUS_CODE = "statuscode" + private const val NODE_MESSAGE = "message" + + private const val NODE_DATA = "data" + private const val NODE_ELEMENT = "element" + private const val NODE_ID = "id" + private const val NODE_ITEM_TYPE = "item_type" + private const val NODE_ITEM_SOURCE = "item_source" + private const val NODE_PARENT = "parent" + private const val NODE_SHARE_TYPE = "share_type" + private const val NODE_SHARE_WITH = "share_with" + private const val NODE_FILE_SOURCE = "file_source" + private const val NODE_PATH = "path" + private const val NODE_PERMISSIONS = "permissions" + private const val NODE_STIME = "stime" + private const val NODE_EXPIRATION = "expiration" + private const val NODE_TOKEN = "token" + private const val NODE_STORAGE = "storage" + private const val NODE_MAIL_SEND = "mail_send" + private const val NODE_SHARE_WITH_DISPLAY_NAME = "share_with_displayname" + private const val NODE_SHARE_WITH_ADDITIONAL_INFO = "share_with_additional_info" + private const val NODE_NAME = "name" + + private const val NODE_URL = "url" + + private const val TYPE_FOLDER = "folder" + + private const val SUCCESS = 200 + private const val ERROR_WRONG_PARAMETER = 400 + private const val ERROR_FORBIDDEN = 403 + private const val ERROR_NOT_FOUND = 404 + private const val INIT = -1 + } +} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/UpdateRemoteShareOperation.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/UpdateRemoteShareOperation.java deleted file mode 100644 index 0122d86e..00000000 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/UpdateRemoteShareOperation.java +++ /dev/null @@ -1,233 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * - * Copyright (C) 2019 ownCloud GmbH. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.lib.resources.shares; - -import android.net.Uri; - -import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.http.HttpConstants; -import com.owncloud.android.lib.common.http.methods.nonwebdav.PutMethod; -import com.owncloud.android.lib.common.operations.RemoteOperation; -import com.owncloud.android.lib.common.operations.RemoteOperationResult; -import com.owncloud.android.lib.common.utils.Log_OC; -import okhttp3.FormBody; - -import java.net.URL; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Locale; - -/** - * Updates parameters of an existing Share resource, known its remote ID. - *

- * Allow updating several parameters, triggering a request to the server per parameter. - * - * @author David A. Velasco - * @author David González Verdugo - */ - -public class UpdateRemoteShareOperation extends RemoteOperation { - - private static final String TAG = GetRemoteShareOperation.class.getSimpleName(); - - private static final String PARAM_NAME = "name"; - private static final String PARAM_PASSWORD = "password"; - private static final String PARAM_EXPIRATION_DATE = "expireDate"; - private static final String PARAM_PERMISSIONS = "permissions"; - private static final String PARAM_PUBLIC_UPLOAD = "publicUpload"; - private static final String FORMAT_EXPIRATION_DATE = "yyyy-MM-dd"; - private static final String ENTITY_CONTENT_TYPE = "application/x-www-form-urlencoded"; - private static final String ENTITY_CHARSET = "UTF-8"; - - /** - * Identifier of the share to update - */ - private long mRemoteId; - - /** - * Password to set for the public link - */ - private String mPassword; - - /** - * Expiration date to set for the public link - */ - private long mExpirationDateInMillis; - - /** - * Access permissions for the file bound to the share - */ - private int mPermissions; - - /** - * Upload permissions for the public link (only folders) - */ - private Boolean mPublicUpload; - private String mName; - - /** - * Constructor. No update is initialized by default, need to be applied with setters below. - * - * @param remoteId Identifier of the share to update. - */ - public UpdateRemoteShareOperation(long remoteId) { - mRemoteId = remoteId; - mPassword = null; // no update - mExpirationDateInMillis = 0; // no update - mPublicUpload = null; - mPermissions = OCShare.DEFAULT_PERMISSION; - } - - /** - * Set name to update in Share resource. Ignored by servers previous to version 10.0.0 - * - * @param name Name to set to the target share. - * Empty string clears the current name. - * Null results in no update applied to the name. - */ - public void setName(String name) { - this.mName = name; - } - - /** - * Set password to update in Share resource. - * - * @param password Password to set to the target share. - * Empty string clears the current password. - * Null results in no update applied to the password. - */ - public void setPassword(String password) { - mPassword = password; - } - - /** - * Set expiration date to update in Share resource. - * - * @param expirationDateInMillis Expiration date to set to the target share. - * A negative value clears the current expiration date. - * Zero value (start-of-epoch) results in no update done on - * the expiration date. - */ - public void setExpirationDate(long expirationDateInMillis) { - mExpirationDateInMillis = expirationDateInMillis; - } - - /** - * Set permissions to update in Share resource. - * - * @param permissions Permissions to set to the target share. - * Values <= 0 result in no update applied to the permissions. - */ - public void setPermissions(int permissions) { - mPermissions = permissions; - } - - /** - * Enable upload permissions to update in Share resource. - * - * @param publicUpload Upload permission to set to the target share. - * Null results in no update applied to the upload permission. - */ - public void setPublicUpload(Boolean publicUpload) { - mPublicUpload = publicUpload; - } - - @Override - protected RemoteOperationResult run(OwnCloudClient client) { - RemoteOperationResult result; - - try { - FormBody.Builder formBodyBuilder = new FormBody.Builder(); - - // Parameters to update - if (mName != null) { - formBodyBuilder.add(PARAM_NAME, mName); - } - - if (mExpirationDateInMillis < 0) { - // clear expiration date - formBodyBuilder.add(PARAM_EXPIRATION_DATE, ""); - - } else if (mExpirationDateInMillis > 0) { - // set expiration date - DateFormat dateFormat = new SimpleDateFormat(FORMAT_EXPIRATION_DATE, Locale.GERMAN); - Calendar expirationDate = Calendar.getInstance(); - expirationDate.setTimeInMillis(mExpirationDateInMillis); - String formattedExpirationDate = dateFormat.format(expirationDate.getTime()); - formBodyBuilder.add(PARAM_EXPIRATION_DATE, formattedExpirationDate); - } // else, ignore - no update - - if (mPublicUpload != null) { - formBodyBuilder.add(PARAM_PUBLIC_UPLOAD, Boolean.toString(mPublicUpload)); - } - - // IMPORTANT: permissions parameter needs to be updated after mPublicUpload parameter, - // otherwise they would be set always as 1 (READ) in the server when mPublicUpload was updated - if (mPermissions > 0) { - // set permissions - formBodyBuilder.add(PARAM_PERMISSIONS, Integer.toString(mPermissions)); - } - - Uri requestUri = client.getBaseUri(); - Uri.Builder uriBuilder = requestUri.buildUpon(); - uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH); - uriBuilder.appendEncodedPath(Long.toString(mRemoteId)); - - PutMethod putMethod = new PutMethod(new URL(uriBuilder.build().toString())); - - putMethod.setRequestBody(formBodyBuilder.build()); - - putMethod.setRequestHeader(HttpConstants.CONTENT_TYPE_HEADER, HttpConstants.CONTENT_TYPE_URLENCODED_UTF8); - putMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); - - int status = client.executeHttpMethod(putMethod); - - if (isSuccess(status)) { - // Parse xml response - ShareToRemoteOperationResultParser parser = new ShareToRemoteOperationResultParser( - new ShareXMLParser() - ); - parser.setOwnCloudVersion(client.getOwnCloudVersion()); - parser.setServerBaseUri(client.getBaseUri()); - result = parser.parse(putMethod.getResponseBodyAsString()); - - } else { - result = new RemoteOperationResult<>(putMethod); - } - - } catch (Exception e) { - result = new RemoteOperationResult<>(e); - Log_OC.e(TAG, "Exception while Creating New Share", e); - } - - return result; - } - - private boolean isSuccess(int status) { - return (status == HttpConstants.HTTP_OK); - } -} \ No newline at end of file diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/UpdateRemoteShareOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/UpdateRemoteShareOperation.kt new file mode 100644 index 00000000..49f38e65 --- /dev/null +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/UpdateRemoteShareOperation.kt @@ -0,0 +1,207 @@ +/* ownCloud Android Library is available under MIT license + * + * Copyright (C) 2019 ownCloud GmbH. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.resources.shares + +import com.owncloud.android.lib.common.OwnCloudClient +import com.owncloud.android.lib.common.http.HttpConstants +import com.owncloud.android.lib.common.http.methods.nonwebdav.PutMethod +import com.owncloud.android.lib.common.operations.RemoteOperation +import com.owncloud.android.lib.common.operations.RemoteOperationResult +import com.owncloud.android.lib.common.utils.Log_OC +import com.owncloud.android.lib.resources.shares.RemoteShare.Companion.DEFAULT_PERMISSION +import okhttp3.FormBody +import java.net.URL +import java.text.SimpleDateFormat +import java.util.Calendar +import java.util.Locale + +/** + * Updates parameters of an existing Share resource, known its remote ID. + * + * + * Allow updating several parameters, triggering a request to the server per parameter. + * + * @author David A. Velasco + * @author David González Verdugo + */ + +class UpdateRemoteShareOperation +/** + * Constructor. No update is initialized by default, need to be applied with setters below. + */ + ( + /** + * @param remoteId Identifier of the share to update. + */ + private val remoteId: Long + +) : RemoteOperation() { + /** + * Name to update in Share resource. Ignored by servers previous to version 10.0.0 + * + * @param name Name to set to the target share. + * Empty string clears the current name. + * Null results in no update applied to the name. + */ + var name: String? = null + + /** + * Password to update in Share resource. + * + * @param password Password to set to the target share. + * Empty string clears the current password. + * Null results in no update applied to the password. + */ + var password: String? = null + + /** + * Expiration date to update in Share resource. + * + * @param expirationDateInMillis Expiration date to set to the target share. + * A negative value clears the current expiration date. + * Zero value (start-of-epoch) results in no update done on + * the expiration date. + */ + var expirationDateInMillis: Long = INITIAL_EXPIRATION_DATE_IN_MILLIS + + /** + * Permissions to update in Share resource. + * + * @param permissions Permissions to set to the target share. + * Values <= 0 result in no update applied to the permissions. + */ + var permissions: Int = DEFAULT_PERMISSION + + /** + * Enable upload permissions to update in Share resource. + * + * @param publicUpload Upload permission to set to the target share. + * Null results in no update applied to the upload permission. + */ + var publicUpload: Boolean? = null + + var retrieveShareDetails = false // To retrieve more info about the just updated share + + override fun run(client: OwnCloudClient): RemoteOperationResult { + var result: RemoteOperationResult + + try { + val formBodyBuilder = FormBody.Builder() + + // Parameters to update + if (name != null) { + formBodyBuilder.add(PARAM_NAME, name!!) + } + + if (password != null) { + formBodyBuilder.add(PARAM_PASSWORD, password!!) + } + + if (expirationDateInMillis < INITIAL_EXPIRATION_DATE_IN_MILLIS) { + // clear expiration date + formBodyBuilder.add(PARAM_EXPIRATION_DATE, "") + + } else if (expirationDateInMillis > INITIAL_EXPIRATION_DATE_IN_MILLIS) { + // set expiration date + val dateFormat = SimpleDateFormat(FORMAT_EXPIRATION_DATE, Locale.getDefault()) + val expirationDate = Calendar.getInstance() + expirationDate.timeInMillis = expirationDateInMillis + val formattedExpirationDate = dateFormat.format(expirationDate.time) + formBodyBuilder.add(PARAM_EXPIRATION_DATE, formattedExpirationDate) + } // else, ignore - no update + + if (publicUpload != null) { + formBodyBuilder.add(PARAM_PUBLIC_UPLOAD, publicUpload.toString()) + } + + // IMPORTANT: permissions parameter needs to be updated after mPublicUpload parameter, + // otherwise they would be set always as 1 (READ) in the server when mPublicUpload was updated + if (permissions > DEFAULT_PERMISSION) { + // set permissions + formBodyBuilder.add(PARAM_PERMISSIONS, permissions.toString()) + } + + val requestUri = client.baseUri + val uriBuilder = requestUri.buildUpon() + uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH) + uriBuilder.appendEncodedPath(remoteId.toString()) + + val putMethod = PutMethod(URL(uriBuilder.build().toString())) + + putMethod.setRequestBody(formBodyBuilder.build()) + + putMethod.setRequestHeader(HttpConstants.CONTENT_TYPE_HEADER, HttpConstants.CONTENT_TYPE_URLENCODED_UTF8) + putMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE) + + val status = client.executeHttpMethod(putMethod) + + // Parse xml response + val parser = ShareToRemoteOperationResultParser( + ShareXMLParser() + ) + + if (!isSuccess(status)) { + return parser.parse(putMethod.responseBodyAsString) + } + + parser.ownCloudVersion = client.ownCloudVersion + parser.serverBaseUri = client.baseUri + result = parser.parse(putMethod.responseBodyAsString) + + if (result.isSuccess && retrieveShareDetails) { + // retrieve more info - PUT only returns the index of the new share + val emptyShare = result.data.shares.first() + val getInfo = GetRemoteShareOperation( + emptyShare.id + ) + result = getInfo.execute(client) + } + + } catch (e: Exception) { + result = RemoteOperationResult(e) + Log_OC.e(TAG, "Exception while Creating New Share", e) + } + + return result + } + + private fun isSuccess(status: Int): Boolean = status == HttpConstants.HTTP_OK + + companion object { + private val TAG = GetRemoteShareOperation::class.java.simpleName + + private const val PARAM_NAME = "name" + private const val PARAM_PASSWORD = "password" + private const val PARAM_EXPIRATION_DATE = "expireDate" + private const val PARAM_PERMISSIONS = "permissions" + private const val PARAM_PUBLIC_UPLOAD = "publicUpload" + private const val FORMAT_EXPIRATION_DATE = "yyyy-MM-dd" + private const val ENTITY_CONTENT_TYPE = "application/x-www-form-urlencoded" + private const val ENTITY_CHARSET = "UTF-8" + + private const val INITIAL_EXPIRATION_DATE_IN_MILLIS: Long = 0 + } +} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/CapabilityBooleanType.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/CapabilityBooleanType.kt similarity index 57% rename from owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/CapabilityBooleanType.java rename to owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/CapabilityBooleanType.kt index 706ab357..7d3d51e7 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/CapabilityBooleanType.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/CapabilityBooleanType.kt @@ -1,5 +1,5 @@ /* ownCloud Android Library is available under MIT license - * Copyright (C) 2016 ownCloud GmbH. + * Copyright (C) 2019 ownCloud GmbH. * @author masensio * * Permission is hereby granted, free of charge, to any person obtaining a copy @@ -22,59 +22,44 @@ * THE SOFTWARE. * */ -package com.owncloud.android.lib.resources.status; +package com.owncloud.android.lib.resources.status /** - * Enum for Boolean Type in OCCapability parameters, with values: + * Enum for Boolean Type in RemoteCapability parameters, with values: * -1 - Unknown * 0 - False * 1 - True */ -public enum CapabilityBooleanType { +enum class CapabilityBooleanType private constructor(val value: Int) { UNKNOWN(-1), FALSE(0), TRUE(1); - private int value; + val isUnknown: Boolean + get() = value == -1 - CapabilityBooleanType(int value) { - this.value = value; - } + val isFalse: Boolean + get() = value == 0 - public static CapabilityBooleanType fromValue(int value) { - switch (value) { - case -1: - return UNKNOWN; - case 0: - return FALSE; - case 1: - return TRUE; + val isTrue: Boolean + get() = value == 1 + + companion object { + fun fromValue(value: Int): CapabilityBooleanType? { + return when (value) { + -1 -> UNKNOWN + 0 -> FALSE + 1 -> TRUE + else -> null + } } - return null; - } - public static CapabilityBooleanType fromBooleanValue(boolean boolValue) { - if (boolValue) { - return TRUE; - } else { - return FALSE; + fun fromBooleanValue(boolValue: Boolean): CapabilityBooleanType { + return if (boolValue) { + TRUE + } else { + FALSE + } } } - - public int getValue() { - return value; - } - - public boolean isUnknown() { - return getValue() == -1; - } - - public boolean isFalse() { - return getValue() == 0; - } - - public boolean isTrue() { - return getValue() == 1; - } - -}; \ No newline at end of file +} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteCapabilitiesOperation.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteCapabilitiesOperation.java deleted file mode 100644 index ec319df4..00000000 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteCapabilitiesOperation.java +++ /dev/null @@ -1,316 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * @author masensio - * @author Semih Serhat Karakaya - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.lib.resources.status; - -import android.net.Uri; - -import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.http.HttpConstants; -import com.owncloud.android.lib.common.http.methods.nonwebdav.GetMethod; -import com.owncloud.android.lib.common.operations.RemoteOperation; -import com.owncloud.android.lib.common.operations.RemoteOperationResult; -import com.owncloud.android.lib.common.utils.Log_OC; -import org.json.JSONObject; - -import java.net.URL; - -import static com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode.OK; - -/** - * Get the Capabilities from the server - * Save in Result.getData in a OCCapability object - * - * @author masensio - * @author David González Verdugo - */ -public class GetRemoteCapabilitiesOperation extends RemoteOperation { - - private static final String TAG = GetRemoteCapabilitiesOperation.class.getSimpleName(); - - // OCS Routes - private static final String OCS_ROUTE = "ocs/v2.php/cloud/capabilities"; - - // Arguments - names - private static final String PARAM_FORMAT = "format"; - - // Arguments - constant values - private static final String VALUE_FORMAT = "json"; - - // JSON Node names - private static final String NODE_OCS = "ocs"; - - private static final String NODE_META = "meta"; - - private static final String NODE_DATA = "data"; - private static final String NODE_VERSION = "version"; - - private static final String NODE_CAPABILITIES = "capabilities"; - private static final String NODE_CORE = "core"; - - private static final String NODE_FILES_SHARING = "files_sharing"; - private static final String NODE_PUBLIC = "public"; - private static final String NODE_PASSWORD = "password"; - private static final String NODE_ENFORCED_FOR = "enforced_for"; - private static final String NODE_EXPIRE_DATE = "expire_date"; - private static final String NODE_USER = "user"; - private static final String NODE_FEDERATION = "federation"; - private static final String NODE_FILES = "files"; - - private static final String PROPERTY_STATUS = "status"; - private static final String PROPERTY_STATUSCODE = "statuscode"; - private static final String PROPERTY_MESSAGE = "message"; - - private static final String PROPERTY_POLLINTERVAL = "pollinterval"; - - private static final String PROPERTY_MAJOR = "major"; - private static final String PROPERTY_MINOR = "minor"; - private static final String PROPERTY_MICRO = "micro"; - private static final String PROPERTY_STRING = "string"; - private static final String PROPERTY_EDITION = "edition"; - - private static final String PROPERTY_API_ENABLED = "api_enabled"; - private static final String PROPERTY_ENABLED = "enabled"; - private static final String PROPERTY_ENFORCED = "enforced"; - private static final String PROPERTY_ENFORCED_READ_ONLY = "read_only"; - private static final String PROPERTY_ENFORCED_READ_WRITE = "read_write"; - private static final String PROPERTY_ENFORCED_UPLOAD_ONLY = "upload_only"; - private static final String PROPERTY_DAYS = "days"; - private static final String PROPERTY_SEND_MAIL = "send_mail"; - private static final String PROPERTY_UPLOAD = "upload"; - private static final String PROPERTY_UPLOAD_ONLY = "supports_upload_only"; - private static final String PROPERTY_MULTIPLE = "multiple"; - private static final String PROPERTY_RESHARING = "resharing"; - private static final String PROPERTY_OUTGOING = "outgoing"; - private static final String PROPERTY_INCOMING = "incoming"; - - private static final String PROPERTY_BIGFILECHUNKING = "bigfilechunking"; - private static final String PROPERTY_UNDELETE = "undelete"; - private static final String PROPERTY_VERSIONING = "versioning"; - - /** - * Constructor - */ - public GetRemoteCapabilitiesOperation() { - - } - - @Override - protected RemoteOperationResult run(OwnCloudClient client) { - RemoteOperationResult result; - - try { - Uri requestUri = client.getBaseUri(); - Uri.Builder uriBuilder = requestUri.buildUpon(); - uriBuilder.appendEncodedPath(OCS_ROUTE); // avoid starting "/" in this method - uriBuilder.appendQueryParameter(PARAM_FORMAT, VALUE_FORMAT); - - GetMethod getMethod = new GetMethod(new URL(uriBuilder.build().toString())); - - getMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); - - int status = client.executeHttpMethod(getMethod); - - String response = getMethod.getResponseBodyAsString(); - if (isSuccess(status)) { - Log_OC.d(TAG, "Successful response: " + response); - - // Parse the response - JSONObject respJSON = new JSONObject(response); - JSONObject respOCS = respJSON.getJSONObject(NODE_OCS); - JSONObject respMeta = respOCS.getJSONObject(NODE_META); - JSONObject respData = respOCS.getJSONObject(NODE_DATA); - - // Read meta - boolean statusProp = respMeta.getString(PROPERTY_STATUS).equalsIgnoreCase("ok"); - int statuscode = respMeta.getInt(PROPERTY_STATUSCODE); - String message = respMeta.getString(PROPERTY_MESSAGE); - - if (statusProp) { - OCCapability capability = new OCCapability(); - // Add Version - if (respData.has(NODE_VERSION)) { - JSONObject respVersion = respData.getJSONObject(NODE_VERSION); - capability.setVersionMayor(respVersion.getInt(PROPERTY_MAJOR)); - capability.setVersionMinor(respVersion.getInt(PROPERTY_MINOR)); - capability.setVersionMicro(respVersion.getInt(PROPERTY_MICRO)); - capability.setVersionString(respVersion.getString(PROPERTY_STRING)); - capability.setVersionEdition(respVersion.getString(PROPERTY_EDITION)); - Log_OC.d(TAG, "*** Added " + NODE_VERSION); - } - - // Capabilities Object - if (respData.has(NODE_CAPABILITIES)) { - JSONObject respCapabilities = respData.getJSONObject(NODE_CAPABILITIES); - - // Add Core: pollinterval - if (respCapabilities.has(NODE_CORE)) { - JSONObject respCore = respCapabilities.getJSONObject(NODE_CORE); - capability.setCorePollinterval(respCore.getInt(PROPERTY_POLLINTERVAL)); - Log_OC.d(TAG, "*** Added " + NODE_CORE); - } - - // Add files_sharing: public, user, resharing - if (respCapabilities.has(NODE_FILES_SHARING)) { - JSONObject respFilesSharing = respCapabilities.getJSONObject(NODE_FILES_SHARING); - if (respFilesSharing.has(PROPERTY_API_ENABLED)) { - capability.setFilesSharingApiEnabled(CapabilityBooleanType.fromBooleanValue( - respFilesSharing.getBoolean(PROPERTY_API_ENABLED))); - } - - if (respFilesSharing.has(NODE_PUBLIC)) { - JSONObject respPublic = respFilesSharing.getJSONObject(NODE_PUBLIC); - capability.setFilesSharingPublicEnabled(CapabilityBooleanType.fromBooleanValue( - respPublic.getBoolean(PROPERTY_ENABLED))); - - if (respPublic.has(NODE_PASSWORD)) { - JSONObject respPassword = respPublic.getJSONObject(NODE_PASSWORD); - capability.setFilesSharingPublicPasswordEnforced( - CapabilityBooleanType.fromBooleanValue( - respPublic.getJSONObject(NODE_PASSWORD). - getBoolean(PROPERTY_ENFORCED) - ) - ); - - if(respPassword.has(NODE_ENFORCED_FOR)) { - capability.setFilesSharingPublicPasswordEnforcedReadOnly( - CapabilityBooleanType.fromBooleanValue( - respPassword.getJSONObject(NODE_ENFORCED_FOR). - getBoolean(PROPERTY_ENFORCED_READ_ONLY) - ) - ); - - capability.setFilesSharingPublicPasswordEnforcedReadWrite( - CapabilityBooleanType.fromBooleanValue( - respPassword.getJSONObject(NODE_ENFORCED_FOR). - getBoolean(PROPERTY_ENFORCED_READ_WRITE) - ) - ); - - capability.setFilesSharingPublicPasswordEnforcedUploadOnly( - CapabilityBooleanType.fromBooleanValue( - respPassword.getJSONObject(NODE_ENFORCED_FOR). - getBoolean(PROPERTY_ENFORCED_UPLOAD_ONLY) - ) - ); - } - } - if (respPublic.has(NODE_EXPIRE_DATE)) { - JSONObject respExpireDate = respPublic.getJSONObject(NODE_EXPIRE_DATE); - capability.setFilesSharingPublicExpireDateEnabled( - CapabilityBooleanType.fromBooleanValue( - respExpireDate.getBoolean(PROPERTY_ENABLED))); - if (respExpireDate.has(PROPERTY_DAYS)) { - capability.setFilesSharingPublicExpireDateDays( - respExpireDate.getInt(PROPERTY_DAYS)); - } - if (respExpireDate.has(PROPERTY_ENFORCED)) { - capability.setFilesSharingPublicExpireDateEnforced( - CapabilityBooleanType.fromBooleanValue( - respExpireDate.getBoolean(PROPERTY_ENFORCED))); - } - } - if (respPublic.has(PROPERTY_UPLOAD)) { - capability.setFilesSharingPublicUpload(CapabilityBooleanType.fromBooleanValue( - respPublic.getBoolean(PROPERTY_UPLOAD))); - } - if (respPublic.has(PROPERTY_UPLOAD_ONLY)) { - capability.setFilesSharingPublicSupportsUploadOnly(CapabilityBooleanType.fromBooleanValue( - respPublic.getBoolean(PROPERTY_UPLOAD_ONLY))); - } - if (respPublic.has(PROPERTY_MULTIPLE)) { - capability.setFilesSharingPublicMultiple(CapabilityBooleanType.fromBooleanValue( - respPublic.getBoolean(PROPERTY_MULTIPLE))); - } - } - - if (respFilesSharing.has(NODE_USER)) { - JSONObject respUser = respFilesSharing.getJSONObject(NODE_USER); - capability.setFilesSharingUserSendMail(CapabilityBooleanType.fromBooleanValue( - respUser.getBoolean(PROPERTY_SEND_MAIL))); - } - - capability.setFilesSharingResharing(CapabilityBooleanType.fromBooleanValue( - respFilesSharing.getBoolean(PROPERTY_RESHARING))); - if (respFilesSharing.has(NODE_FEDERATION)) { - JSONObject respFederation = respFilesSharing.getJSONObject(NODE_FEDERATION); - capability.setFilesSharingFederationOutgoing( - CapabilityBooleanType.fromBooleanValue(respFederation.getBoolean(PROPERTY_OUTGOING))); - capability.setFilesSharingFederationIncoming(CapabilityBooleanType.fromBooleanValue( - respFederation.getBoolean(PROPERTY_INCOMING))); - } - Log_OC.d(TAG, "*** Added " + NODE_FILES_SHARING); - } - - if (respCapabilities.has(NODE_FILES)) { - JSONObject respFiles = respCapabilities.getJSONObject(NODE_FILES); - // Add files - capability.setFilesBigFileChuncking(CapabilityBooleanType.fromBooleanValue( - respFiles.getBoolean(PROPERTY_BIGFILECHUNKING))); - if (respFiles.has(PROPERTY_UNDELETE)) { - capability.setFilesUndelete(CapabilityBooleanType.fromBooleanValue( - respFiles.getBoolean(PROPERTY_UNDELETE))); - } - if (respFiles.has(PROPERTY_VERSIONING)) { - capability.setFilesVersioning(CapabilityBooleanType.fromBooleanValue( - respFiles.getBoolean(PROPERTY_VERSIONING))); - } - Log_OC.d(TAG, "*** Added " + NODE_FILES); - } - } - // Result - result = new RemoteOperationResult<>(OK); - result.setData(capability); - - Log_OC.d(TAG, "*** Get Capabilities completed "); - } else { - result = new RemoteOperationResult<>(statuscode, message, null); - Log_OC.e(TAG, "Failed response while getting capabilities from the server "); - Log_OC.e(TAG, "*** status: " + statusProp + "; message: " + message); - } - - } else { - result = new RemoteOperationResult<>(getMethod); - Log_OC.e(TAG, "Failed response while getting capabilities from the server "); - if (response != null) { - Log_OC.e(TAG, "*** status code: " + status + "; response message: " + response); - } else { - Log_OC.e(TAG, "*** status code: " + status); - } - } - - } catch (Exception e) { - result = new RemoteOperationResult<>(e); - Log_OC.e(TAG, "Exception while getting capabilities", e); - } - return result; - } - - private boolean isSuccess(int status) { - return (status == HttpConstants.HTTP_OK); - } -} \ No newline at end of file diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteCapabilitiesOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteCapabilitiesOperation.kt new file mode 100644 index 00000000..8bce27ef --- /dev/null +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteCapabilitiesOperation.kt @@ -0,0 +1,326 @@ +/* ownCloud Android Library is available under MIT license + * @author masensio + * @author Semih Serhat Karakaya + * @author David González Verdugo + * Copyright (C) 2019 ownCloud GmbH. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.resources.status + +import com.owncloud.android.lib.common.OwnCloudClient +import com.owncloud.android.lib.common.http.HttpConstants +import com.owncloud.android.lib.common.http.methods.nonwebdav.GetMethod +import com.owncloud.android.lib.common.operations.RemoteOperation +import com.owncloud.android.lib.common.operations.RemoteOperationResult +import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode.OK +import com.owncloud.android.lib.common.utils.Log_OC +import org.json.JSONObject +import java.net.URL + +/** + * Get the Capabilities from the server + * Save in Result.getData in a RemoteCapability object + * + * @author masensio + * @author David González Verdugo + */ +/** + * Constructor + */ +class GetRemoteCapabilitiesOperation : RemoteOperation() { + + override fun run(client: OwnCloudClient): RemoteOperationResult { + var result: RemoteOperationResult + + try { + val requestUri = client.baseUri + val uriBuilder = requestUri.buildUpon() + uriBuilder.appendEncodedPath(OCS_ROUTE) // avoid starting "/" in this method + uriBuilder.appendQueryParameter(PARAM_FORMAT, VALUE_FORMAT) + + val getMethod = GetMethod(URL(uriBuilder.build().toString())) + + getMethod.addRequestHeader(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE) + + val status = client.executeHttpMethod(getMethod) + + val response = getMethod.responseBodyAsString + + if (!isSuccess(status)) { + result = RemoteOperationResult(getMethod) + Log_OC.e(TAG, "Failed response while getting capabilities from the server ") + if (response != null) { + Log_OC.e(TAG, "*** status code: $status; response message: $response") + } else { + Log_OC.e(TAG, "*** status code: $status") + } + + return result + } + + Log_OC.d(TAG, "Successful response: " + response!!) + + // Parse the response + val respJSON = JSONObject(response) + val respOCS = respJSON.getJSONObject(NODE_OCS) + val respMeta = respOCS.getJSONObject(NODE_META) + val respData = respOCS.getJSONObject(NODE_DATA) + + // Read meta + val statusProp = respMeta.getString(PROPERTY_STATUS).equals(PROPERTY_STATUS_OK, ignoreCase = true) + val statuscode = respMeta.getInt(PROPERTY_STATUSCODE) + val message = respMeta.getString(PROPERTY_MESSAGE) + + if (statusProp) { + val capability = RemoteCapability() + // Add Version + if (respData.has(NODE_VERSION)) { + val respVersion = respData.getJSONObject(NODE_VERSION) + capability.versionMayor = respVersion.getInt(PROPERTY_MAJOR) + capability.versionMinor = respVersion.getInt(PROPERTY_MINOR) + capability.versionMicro = respVersion.getInt(PROPERTY_MICRO) + capability.versionString = respVersion.getString(PROPERTY_STRING) + capability.versionEdition = respVersion.getString(PROPERTY_EDITION) + Log_OC.d(TAG, "*** Added $NODE_VERSION") + } + + // Capabilities Object + if (respData.has(NODE_CAPABILITIES)) { + val respCapabilities = respData.getJSONObject(NODE_CAPABILITIES) + + // Add Core: pollinterval + if (respCapabilities.has(NODE_CORE)) { + val respCore = respCapabilities.getJSONObject(NODE_CORE) + capability.corePollinterval = respCore.getInt(PROPERTY_POLLINTERVAL) + Log_OC.d(TAG, "*** Added $NODE_CORE") + } + + // Add files_sharing: public, user, resharing + if (respCapabilities.has(NODE_FILES_SHARING)) { + val respFilesSharing = respCapabilities.getJSONObject(NODE_FILES_SHARING) + if (respFilesSharing.has(PROPERTY_API_ENABLED)) { + capability.filesSharingApiEnabled = CapabilityBooleanType.fromBooleanValue( + respFilesSharing.getBoolean(PROPERTY_API_ENABLED) + ) + } + + if (respFilesSharing.has(NODE_PUBLIC)) { + val respPublic = respFilesSharing.getJSONObject(NODE_PUBLIC) + capability.filesSharingPublicEnabled = CapabilityBooleanType.fromBooleanValue( + respPublic.getBoolean(PROPERTY_ENABLED) + ) + + if (respPublic.has(NODE_PASSWORD)) { + val respPassword = respPublic.getJSONObject(NODE_PASSWORD) + capability.filesSharingPublicPasswordEnforced = + CapabilityBooleanType.fromBooleanValue( + respPublic.getJSONObject(NODE_PASSWORD).getBoolean(PROPERTY_ENFORCED) + ) + + if (respPassword.has(NODE_ENFORCED_FOR)) { + capability.filesSharingPublicPasswordEnforcedReadOnly = + CapabilityBooleanType.fromBooleanValue( + respPassword.getJSONObject(NODE_ENFORCED_FOR).getBoolean( + PROPERTY_ENFORCED_READ_ONLY + ) + ) + + capability.filesSharingPublicPasswordEnforcedReadWrite = + CapabilityBooleanType.fromBooleanValue( + respPassword.getJSONObject(NODE_ENFORCED_FOR).getBoolean( + PROPERTY_ENFORCED_READ_WRITE + ) + ) + + capability.filesSharingPublicPasswordEnforcedUploadOnly = + CapabilityBooleanType.fromBooleanValue( + respPassword.getJSONObject(NODE_ENFORCED_FOR).getBoolean( + PROPERTY_ENFORCED_UPLOAD_ONLY + ) + ) + } + } + if (respPublic.has(NODE_EXPIRE_DATE)) { + val respExpireDate = respPublic.getJSONObject(NODE_EXPIRE_DATE) + capability.filesSharingPublicExpireDateEnabled = + CapabilityBooleanType.fromBooleanValue( + respExpireDate.getBoolean(PROPERTY_ENABLED) + ) + if (respExpireDate.has(PROPERTY_DAYS)) { + capability.filesSharingPublicExpireDateDays = + respExpireDate.getInt(PROPERTY_DAYS) + } + if (respExpireDate.has(PROPERTY_ENFORCED)) { + capability.filesSharingPublicExpireDateEnforced = + CapabilityBooleanType.fromBooleanValue( + respExpireDate.getBoolean(PROPERTY_ENFORCED) + ) + } + } + if (respPublic.has(PROPERTY_UPLOAD)) { + capability.filesSharingPublicUpload = CapabilityBooleanType.fromBooleanValue( + respPublic.getBoolean(PROPERTY_UPLOAD) + ) + } + if (respPublic.has(PROPERTY_UPLOAD_ONLY)) { + capability.filesSharingPublicSupportsUploadOnly = + CapabilityBooleanType.fromBooleanValue( + respPublic.getBoolean(PROPERTY_UPLOAD_ONLY) + ) + } + if (respPublic.has(PROPERTY_MULTIPLE)) { + capability.filesSharingPublicMultiple = CapabilityBooleanType.fromBooleanValue( + respPublic.getBoolean(PROPERTY_MULTIPLE) + ) + } + } + + if (respFilesSharing.has(NODE_USER)) { + val respUser = respFilesSharing.getJSONObject(NODE_USER) + capability.filesSharingUserSendMail = CapabilityBooleanType.fromBooleanValue( + respUser.getBoolean(PROPERTY_SEND_MAIL) + ) + } + + capability.filesSharingResharing = CapabilityBooleanType.fromBooleanValue( + respFilesSharing.getBoolean(PROPERTY_RESHARING) + ) + if (respFilesSharing.has(NODE_FEDERATION)) { + val respFederation = respFilesSharing.getJSONObject(NODE_FEDERATION) + capability.filesSharingFederationOutgoing = + CapabilityBooleanType.fromBooleanValue(respFederation.getBoolean(PROPERTY_OUTGOING)) + capability.filesSharingFederationIncoming = CapabilityBooleanType.fromBooleanValue( + respFederation.getBoolean(PROPERTY_INCOMING) + ) + } + Log_OC.d(TAG, "*** Added $NODE_FILES_SHARING") + } + + if (respCapabilities.has(NODE_FILES)) { + val respFiles = respCapabilities.getJSONObject(NODE_FILES) + // Add files + capability.filesBigFileChunking = CapabilityBooleanType.fromBooleanValue( + respFiles.getBoolean(PROPERTY_BIGFILECHUNKING) + ) + if (respFiles.has(PROPERTY_UNDELETE)) { + capability.filesUndelete = CapabilityBooleanType.fromBooleanValue( + respFiles.getBoolean(PROPERTY_UNDELETE) + ) + } + if (respFiles.has(PROPERTY_VERSIONING)) { + capability.filesVersioning = CapabilityBooleanType.fromBooleanValue( + respFiles.getBoolean(PROPERTY_VERSIONING) + ) + } + Log_OC.d(TAG, "*** Added $NODE_FILES") + } + } + // Result + result = RemoteOperationResult(OK) + result.data = capability + + Log_OC.d(TAG, "*** Get Capabilities completed ") + } else { + result = RemoteOperationResult(statuscode, message, null) + Log_OC.e(TAG, "Failed response while getting capabilities from the server ") + Log_OC.e(TAG, "*** status: $statusProp; message: $message") + } + + } catch (e: Exception) { + result = RemoteOperationResult(e) + Log_OC.e(TAG, "Exception while getting capabilities", e) + } + + return result + } + + private fun isSuccess(status: Int): Boolean { + return status == HttpConstants.HTTP_OK + } + + companion object { + + private val TAG = GetRemoteCapabilitiesOperation::class.java.simpleName + + // OCS Routes + private val OCS_ROUTE = "ocs/v2.php/cloud/capabilities" + + // Arguments - names + private val PARAM_FORMAT = "format" + + // Arguments - constant values + private val VALUE_FORMAT = "json" + + // JSON Node names + private val NODE_OCS = "ocs" + + private val NODE_META = "meta" + + private val NODE_DATA = "data" + private val NODE_VERSION = "version" + + private val NODE_CAPABILITIES = "capabilities" + private val NODE_CORE = "core" + + private val NODE_FILES_SHARING = "files_sharing" + private val NODE_PUBLIC = "public" + private val NODE_PASSWORD = "password" + private val NODE_ENFORCED_FOR = "enforced_for" + private val NODE_EXPIRE_DATE = "expire_date" + private val NODE_USER = "user" + private val NODE_FEDERATION = "federation" + private val NODE_FILES = "files" + + private val PROPERTY_STATUS = "status" + private val PROPERTY_STATUS_OK = "ok" + private val PROPERTY_STATUSCODE = "statuscode" + private val PROPERTY_MESSAGE = "message" + + private val PROPERTY_POLLINTERVAL = "pollinterval" + + private val PROPERTY_MAJOR = "major" + private val PROPERTY_MINOR = "minor" + private val PROPERTY_MICRO = "micro" + private val PROPERTY_STRING = "string" + private val PROPERTY_EDITION = "edition" + + private val PROPERTY_API_ENABLED = "api_enabled" + private val PROPERTY_ENABLED = "enabled" + private val PROPERTY_ENFORCED = "enforced" + private val PROPERTY_ENFORCED_READ_ONLY = "read_only" + private val PROPERTY_ENFORCED_READ_WRITE = "read_write" + private val PROPERTY_ENFORCED_UPLOAD_ONLY = "upload_only" + private val PROPERTY_DAYS = "days" + private val PROPERTY_SEND_MAIL = "send_mail" + private val PROPERTY_UPLOAD = "upload" + private val PROPERTY_UPLOAD_ONLY = "supports_upload_only" + private val PROPERTY_MULTIPLE = "multiple" + private val PROPERTY_RESHARING = "resharing" + private val PROPERTY_OUTGOING = "outgoing" + private val PROPERTY_INCOMING = "incoming" + + private val PROPERTY_BIGFILECHUNKING = "bigfilechunking" + private val PROPERTY_UNDELETE = "undelete" + private val PROPERTY_VERSIONING = "versioning" + } +} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OCCapability.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OCCapability.java deleted file mode 100644 index 99479b54..00000000 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OCCapability.java +++ /dev/null @@ -1,339 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * @author masensio - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -package com.owncloud.android.lib.resources.status; - -/** - * Contains data of the Capabilities for an account, from the Capabilities API - */ -public class OCCapability { - - private static final String TAG = OCCapability.class.getSimpleName(); - - private long mId; - private String mAccountName; - - // Server version - private int mVersionMayor; - private int mVersionMinor; - private int mVersionMicro; - private String mVersionString; - private String mVersionEdition; - - // Core PollInterval - private int mCorePollinterval; - - // Files Sharing - private CapabilityBooleanType mFilesSharingApiEnabled; - - private CapabilityBooleanType mFilesSharingPublicEnabled; - private CapabilityBooleanType mFilesSharingPublicPasswordEnforced; - private CapabilityBooleanType mFilesSharingPublicPasswordEnforcedReadOnly; - private CapabilityBooleanType mFilesSharingPublicPasswordEnforcedReadWrite; - private CapabilityBooleanType mFilesSharingPublicPasswordEnforcedUploadOnly; - private CapabilityBooleanType mFilesSharingPublicExpireDateEnabled; - private int mFilesSharingPublicExpireDateDays; - private CapabilityBooleanType mFilesSharingPublicExpireDateEnforced; - private CapabilityBooleanType mFilesSharingPublicSendMail; - private CapabilityBooleanType mFilesSharingPublicUpload; - private CapabilityBooleanType mFilesSharingPublicMultiple; - private CapabilityBooleanType mFilesSharingPublicSupportsUploadOnly; - - private CapabilityBooleanType mFilesSharingUserSendMail; - - private CapabilityBooleanType mFilesSharingResharing; - - private CapabilityBooleanType mFilesSharingFederationOutgoing; - private CapabilityBooleanType mFilesSharingFederationIncoming; - - // Files - private CapabilityBooleanType mFilesBigFileChuncking; - private CapabilityBooleanType mFilesUndelete; - private CapabilityBooleanType mFilesVersioning; - - public OCCapability() { - mId = 0; - mAccountName = ""; - - mVersionMayor = 0; - mVersionMinor = 0; - mVersionMicro = 0; - mVersionString = ""; - mVersionString = ""; - - mCorePollinterval = 0; - - mFilesSharingApiEnabled = CapabilityBooleanType.UNKNOWN; - mFilesSharingPublicEnabled = CapabilityBooleanType.UNKNOWN; - mFilesSharingPublicPasswordEnforced = CapabilityBooleanType.UNKNOWN; - mFilesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.UNKNOWN; - mFilesSharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.UNKNOWN; - mFilesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.UNKNOWN; - mFilesSharingPublicExpireDateEnabled = CapabilityBooleanType.UNKNOWN; - mFilesSharingPublicExpireDateDays = 0; - mFilesSharingPublicExpireDateEnforced = CapabilityBooleanType.UNKNOWN; - mFilesSharingPublicSendMail = CapabilityBooleanType.UNKNOWN; - mFilesSharingPublicUpload = CapabilityBooleanType.UNKNOWN; - mFilesSharingPublicMultiple = CapabilityBooleanType.UNKNOWN; - mFilesSharingPublicSupportsUploadOnly = CapabilityBooleanType.UNKNOWN; - mFilesSharingUserSendMail = CapabilityBooleanType.UNKNOWN; - mFilesSharingResharing = CapabilityBooleanType.UNKNOWN; - mFilesSharingFederationOutgoing = CapabilityBooleanType.UNKNOWN; - mFilesSharingFederationIncoming = CapabilityBooleanType.UNKNOWN; - - mFilesBigFileChuncking = CapabilityBooleanType.UNKNOWN; - mFilesUndelete = CapabilityBooleanType.UNKNOWN; - mFilesVersioning = CapabilityBooleanType.UNKNOWN; - } - - // Getters and Setters - public String getAccountName() { - return mAccountName; - } - - public void setAccountName(String accountName) { - this.mAccountName = accountName; - } - - public long getId() { - return mId; - } - - public void setId(long id) { - this.mId = id; - } - - public int getVersionMayor() { - return mVersionMayor; - } - - public void setVersionMayor(int versionMayor) { - this.mVersionMayor = versionMayor; - } - - public int getVersionMinor() { - return mVersionMinor; - } - - public void setVersionMinor(int versionMinor) { - this.mVersionMinor = versionMinor; - } - - public int getVersionMicro() { - return mVersionMicro; - } - - public void setVersionMicro(int versionMicro) { - this.mVersionMicro = versionMicro; - } - - public String getVersionString() { - return mVersionString; - } - - public void setVersionString(String versionString) { - this.mVersionString = versionString; - } - - public String getVersionEdition() { - return mVersionEdition; - } - - public void setVersionEdition(String versionEdition) { - this.mVersionEdition = versionEdition; - } - - public int getCorePollinterval() { - return mCorePollinterval; - } - - public void setCorePollinterval(int corePollinterval) { - this.mCorePollinterval = corePollinterval; - } - - public CapabilityBooleanType getFilesSharingApiEnabled() { - return mFilesSharingApiEnabled; - } - - public void setFilesSharingApiEnabled(CapabilityBooleanType filesSharingApiEnabled) { - this.mFilesSharingApiEnabled = filesSharingApiEnabled; - } - - public CapabilityBooleanType getFilesSharingPublicEnabled() { - return mFilesSharingPublicEnabled; - } - - public void setFilesSharingPublicEnabled(CapabilityBooleanType filesSharingPublicEnabled) { - this.mFilesSharingPublicEnabled = filesSharingPublicEnabled; - } - - public CapabilityBooleanType getFilesSharingPublicPasswordEnforced() { - return mFilesSharingPublicPasswordEnforced; - } - - public void setFilesSharingPublicPasswordEnforced(CapabilityBooleanType filesSharingPublicPasswordEnforced) { - this.mFilesSharingPublicPasswordEnforced = filesSharingPublicPasswordEnforced; - } - - public CapabilityBooleanType getFilesSharingPublicPasswordEnforcedReadOnly() { - return mFilesSharingPublicPasswordEnforcedReadOnly; - } - - public void setFilesSharingPublicPasswordEnforcedReadOnly( - CapabilityBooleanType filesSharingPublicPasswordEnforcedReadOnly) { - this.mFilesSharingPublicPasswordEnforcedReadOnly = filesSharingPublicPasswordEnforcedReadOnly; - } - - public CapabilityBooleanType getFilesSharingPublicPasswordEnforcedReadWrite() { - return mFilesSharingPublicPasswordEnforcedReadWrite; - } - - public void setFilesSharingPublicPasswordEnforcedReadWrite( - CapabilityBooleanType filesSharingPublicPasswordEnforcedReadWrite) { - this.mFilesSharingPublicPasswordEnforcedReadWrite = filesSharingPublicPasswordEnforcedReadWrite; - } - - public CapabilityBooleanType getFilesSharingPublicPasswordEnforcedUploadOnly() { - return mFilesSharingPublicPasswordEnforcedUploadOnly; - } - - public void setFilesSharingPublicPasswordEnforcedUploadOnly( - CapabilityBooleanType filesSharingPublicPasswordEnforcedUploadOnly) { - this.mFilesSharingPublicPasswordEnforcedUploadOnly = filesSharingPublicPasswordEnforcedUploadOnly; - } - - public CapabilityBooleanType getFilesSharingPublicExpireDateEnabled() { - return mFilesSharingPublicExpireDateEnabled; - } - - public void setFilesSharingPublicExpireDateEnabled(CapabilityBooleanType filesSharingPublicExpireDateEnabled) { - this.mFilesSharingPublicExpireDateEnabled = filesSharingPublicExpireDateEnabled; - } - - public int getFilesSharingPublicExpireDateDays() { - return mFilesSharingPublicExpireDateDays; - } - - public void setFilesSharingPublicExpireDateDays(int filesSharingPublicExpireDateDays) { - this.mFilesSharingPublicExpireDateDays = filesSharingPublicExpireDateDays; - } - - public CapabilityBooleanType getFilesSharingPublicExpireDateEnforced() { - return mFilesSharingPublicExpireDateEnforced; - } - - public void setFilesSharingPublicExpireDateEnforced(CapabilityBooleanType filesSharingPublicExpireDateEnforced) { - this.mFilesSharingPublicExpireDateEnforced = filesSharingPublicExpireDateEnforced; - } - - public CapabilityBooleanType getFilesSharingPublicSendMail() { - return mFilesSharingPublicSendMail; - } - - public void setFilesSharingPublicSendMail(CapabilityBooleanType filesSharingPublicSendMail) { - this.mFilesSharingPublicSendMail = filesSharingPublicSendMail; - } - - public CapabilityBooleanType getFilesSharingPublicUpload() { - return mFilesSharingPublicUpload; - } - - public void setFilesSharingPublicUpload(CapabilityBooleanType filesSharingPublicUpload) { - this.mFilesSharingPublicUpload = filesSharingPublicUpload; - } - - public CapabilityBooleanType getFilesSharingPublicMultiple() { - return mFilesSharingPublicMultiple; - } - - public void setFilesSharingPublicMultiple(CapabilityBooleanType filesSharingPublicMultiple) { - this.mFilesSharingPublicMultiple = filesSharingPublicMultiple; - } - - public CapabilityBooleanType getFilesSharingPublicSupportsUploadOnly() { - return mFilesSharingPublicSupportsUploadOnly; - } - - public void setFilesSharingPublicSupportsUploadOnly(CapabilityBooleanType - filesSharingPublicMultiple) { - this.mFilesSharingPublicSupportsUploadOnly = filesSharingPublicMultiple; - } - - public CapabilityBooleanType getFilesSharingUserSendMail() { - return mFilesSharingUserSendMail; - } - - public void setFilesSharingUserSendMail(CapabilityBooleanType filesSharingUserSendMail) { - this.mFilesSharingUserSendMail = filesSharingUserSendMail; - } - - public CapabilityBooleanType getFilesSharingResharing() { - return mFilesSharingResharing; - } - - public void setFilesSharingResharing(CapabilityBooleanType filesSharingResharing) { - this.mFilesSharingResharing = filesSharingResharing; - } - - public CapabilityBooleanType getFilesSharingFederationOutgoing() { - return mFilesSharingFederationOutgoing; - } - - public void setFilesSharingFederationOutgoing(CapabilityBooleanType filesSharingFederationOutgoing) { - this.mFilesSharingFederationOutgoing = filesSharingFederationOutgoing; - } - - public CapabilityBooleanType getFilesSharingFederationIncoming() { - return mFilesSharingFederationIncoming; - } - - public void setFilesSharingFederationIncoming(CapabilityBooleanType filesSharingFederationIncoming) { - this.mFilesSharingFederationIncoming = filesSharingFederationIncoming; - } - - public CapabilityBooleanType getFilesBigFileChuncking() { - return mFilesBigFileChuncking; - } - - public void setFilesBigFileChuncking(CapabilityBooleanType filesBigFileChuncking) { - this.mFilesBigFileChuncking = filesBigFileChuncking; - } - - public CapabilityBooleanType getFilesUndelete() { - return mFilesUndelete; - } - - public void setFilesUndelete(CapabilityBooleanType filesUndelete) { - this.mFilesUndelete = filesUndelete; - } - - public CapabilityBooleanType getFilesVersioning() { - return mFilesVersioning; - } - - public void setFilesVersioning(CapabilityBooleanType filesVersioning) { - this.mFilesVersioning = filesVersioning; - } -} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OwnCloudVersion.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OwnCloudVersion.java deleted file mode 100644 index 04b8800c..00000000 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OwnCloudVersion.java +++ /dev/null @@ -1,199 +0,0 @@ -/* ownCloud 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 com.owncloud.android.lib.resources.status; - -public class OwnCloudVersion implements Comparable { - - public static final int MINIMUN_VERSION_FOR_CHUNKED_UPLOADS = 0x04050000; // 4.5 - - public static final int MINIMUM_VERSION_FOR_SHARING_API = 0x05001B00; // 5.0.27 - - public static final int MINIMUM_VERSION_WITH_FORBIDDEN_CHARS = 0x08010000; // 8.1 - - public static final int MINIMUM_SERVER_VERSION_FOR_REMOTE_THUMBNAILS = 0x07080000; // 7.8.0 - - public static final int MINIMUM_VERSION_FOR_SEARCHING_USERS = 0x08020000; //8.2 - - public static final int VERSION_8 = 0x08000000; // 8.0 - - public static final int MINIMUM_VERSION_CAPABILITIES_API = 0x08010000; // 8.1 - - private static final int MINIMUM_VERSION_WITH_NOT_RESHAREABLE_FEDERATED = 0x09010000; // 9.1 - - private static final int MINIMUM_VERSION_WITH_SESSION_MONITORING = 0x09010000; // 9.1 - - private static final int MINIMUM_VERSION_WITH_SESSION_MONITORING_WORKING_IN_PREEMPTIVE_MODE = 0x09010301; - // 9.1.3.1, final 9.1.3: https://github.com/owncloud/core/commit/f9a867b70c217463289a741d4d26079eb2a80dfd - - private static final int MINIMUM_VERSION_WITH_MULTIPLE_PUBLIC_SHARING = 0xA000000; // 10.0.0 - - private static final int MINIMUM_VERSION_WITH_WRITE_ONLY_PUBLIC_SHARING = 0xA000100; // 10.0.1 - - private static final String INVALID_ZERO_VERSION = "0.0.0"; - - private static final int MAX_DOTS = 3; - - // format is in version - // 0xAABBCCDD - // for version AA.BB.CC.DD - // ie version 2.0.3 will be stored as 0x02000300 - private int mVersion; - private boolean mIsValid; - - public OwnCloudVersion(String version) { - mVersion = 0; - mIsValid = false; - int countDots = version.length() - version.replace(".", "").length(); - - // Complete the version. Version must have 3 dots - for (int i = countDots; i < MAX_DOTS; i++) { - version = version + ".0"; - } - - parseVersion(version); - - } - - public String toString() { - // gets the first digit of version, shifting hexadecimal version to right 'til max position - String versionToString = String.valueOf((mVersion >> (8 * MAX_DOTS)) % 256); - for (int i = MAX_DOTS - 1; i >= 0; i--) { - // gets another digit of version, shifting hexadecimal version to right 8*i bits and... - // ...discarding left part with mod 256 - versionToString = versionToString + "." + String.valueOf((mVersion >> (8 * i)) % 256); - } - if (!mIsValid) { - versionToString += " INVALID"; - } - return versionToString; - } - - public String getVersion() { - if (mIsValid) { - return toString(); - } else { - return INVALID_ZERO_VERSION; - } - } - - public boolean isVersionValid() { - return mIsValid; - } - - @Override - public int compareTo(OwnCloudVersion another) { - return another.mVersion == mVersion ? 0 - : another.mVersion < mVersion ? 1 : -1; - } - - private void parseVersion(String version) { - try { - mVersion = getParsedVersion(version); - mIsValid = true; - - } catch (Exception e) { - mIsValid = false; - // if invalid, the instance will respond as if server is 8.1, minimum with capabilities API, - // and "dead" : https://github.com/owncloud/core/wiki/Maintenance-and-Release-Schedule - mVersion = MINIMUM_VERSION_CAPABILITIES_API; - } - } - - private int getParsedVersion(String version) throws NumberFormatException { - int versionValue = 0; - - // get only numeric part - version = version.replaceAll("[^\\d.]", ""); - - String[] nums = version.split("\\."); - for (int i = 0; i < nums.length && i <= MAX_DOTS; i++) { - versionValue += Integer.parseInt(nums[i]); - if (i < nums.length - 1) { - versionValue = versionValue << 8; - } - } - - return versionValue; - } - - public boolean isChunkedUploadSupported() { - return (mVersion >= MINIMUN_VERSION_FOR_CHUNKED_UPLOADS); - } - - public boolean isSharedSupported() { - return (mVersion >= MINIMUM_VERSION_FOR_SHARING_API); - } - - public boolean isVersionWithForbiddenCharacters() { - return (mVersion >= MINIMUM_VERSION_WITH_FORBIDDEN_CHARS); - } - - public boolean supportsRemoteThumbnails() { - return (mVersion >= MINIMUM_SERVER_VERSION_FOR_REMOTE_THUMBNAILS); - } - - public boolean isAfter8Version() { - return (mVersion >= VERSION_8); - } - - public boolean isSearchUsersSupported() { - return (mVersion >= MINIMUM_VERSION_FOR_SEARCHING_USERS); - } - - public boolean isVersionWithCapabilitiesAPI() { - return (mVersion >= MINIMUM_VERSION_CAPABILITIES_API); - } - - public boolean isNotReshareableFederatedSupported() { - return (mVersion >= MINIMUM_VERSION_WITH_NOT_RESHAREABLE_FEDERATED); - } - - public boolean isSessionMonitoringSupported() { - return (mVersion >= MINIMUM_VERSION_WITH_SESSION_MONITORING); - } - - /** - * From OC 9.1 session tracking is a feature, but to get it working in the OC app we need the preemptive - * mode of basic authentication is disabled. This changes in OC 9.1.3, where preemptive mode is compatible - * with session tracking again. - * - * @return True for every version before 9.1 and from 9.1.3, false otherwise - */ - public boolean isPreemptiveAuthenticationPreferred() { - return ( - (mVersion < MINIMUM_VERSION_WITH_SESSION_MONITORING) || - (mVersion >= MINIMUM_VERSION_WITH_SESSION_MONITORING_WORKING_IN_PREEMPTIVE_MODE) - ); - } - - public boolean isMultiplePublicSharingSupported() { - return (mVersion >= MINIMUM_VERSION_WITH_MULTIPLE_PUBLIC_SHARING); - } - - public boolean isPublicSharingWriteOnlySupported() { - return (mVersion >= MINIMUM_VERSION_WITH_WRITE_ONLY_PUBLIC_SHARING); - } -} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OwnCloudVersion.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OwnCloudVersion.kt new file mode 100644 index 00000000..ef9b6357 --- /dev/null +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OwnCloudVersion.kt @@ -0,0 +1,214 @@ +/* ownCloud 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 com.owncloud.android.lib.resources.status + +import android.os.Parcel +import android.os.Parcelable +import com.owncloud.android.lib.testing.OpenForTesting + +@OpenForTesting +class OwnCloudVersion(version: String) : Comparable, Parcelable { + + // format is in version + // 0xAABBCCDD + // for version AA.BB.CC.DD + // ie version 2.0.3 will be stored as 0x02000300 + private var mVersion: Int = 0 + var isVersionValid: Boolean = false + set + + val version: String + get() = if (isVersionValid) { + toString() + } else { + INVALID_ZERO_VERSION + } + + val isChunkedUploadSupported: Boolean + get() = mVersion >= MINIMUN_VERSION_FOR_CHUNKED_UPLOADS + + val isSharedSupported: Boolean + get() = mVersion >= MINIMUM_VERSION_FOR_SHARING_API + + val isVersionWithForbiddenCharacters: Boolean + get() = mVersion >= MINIMUM_VERSION_WITH_FORBIDDEN_CHARS + + val isAfter8Version: Boolean + get() = mVersion >= VERSION_8 + + val isSearchUsersSupported: Boolean + get() = mVersion >= MINIMUM_VERSION_FOR_SEARCHING_USERS + + val isVersionWithCapabilitiesAPI: Boolean + get() = mVersion >= MINIMUM_VERSION_CAPABILITIES_API + + val isNotReshareableFederatedSupported: Boolean + get() = mVersion >= MINIMUM_VERSION_WITH_NOT_RESHAREABLE_FEDERATED + + val isSessionMonitoringSupported: Boolean + get() = mVersion >= MINIMUM_VERSION_WITH_SESSION_MONITORING + + /** + * From OC 9.1 session tracking is a feature, but to get it working in the OC app we need the preemptive + * mode of basic authentication is disabled. This changes in OC 9.1.3, where preemptive mode is compatible + * with session tracking again. + * + * @return True for every version before 9.1 and from 9.1.3, false otherwise + */ + val isPreemptiveAuthenticationPreferred: Boolean + get() = mVersion < MINIMUM_VERSION_WITH_SESSION_MONITORING || mVersion >= MINIMUM_VERSION_WITH_SESSION_MONITORING_WORKING_IN_PREEMPTIVE_MODE + + val isMultiplePublicSharingSupported: Boolean + get() = mVersion >= MINIMUM_VERSION_WITH_MULTIPLE_PUBLIC_SHARING + + val isPublicSharingWriteOnlySupported: Boolean + get() = mVersion >= MINIMUM_VERSION_WITH_WRITE_ONLY_PUBLIC_SHARING + + val isPublicUploadPermissionNeeded: Boolean + get() = mVersion >= MINIMUN_MAJOR_VERSION_WITHOUT_PUBLIC_UPLOAD_PERMISSION && + (mVersion > MINIMUN_MINOR_VERSION_WITHOUT_PUBLIC_UPLOAD_PERMISSION || + mVersion > MINIMUN_MICRO_VERSION_WITHOUT_PUBLIC_UPLOAD_PERMISSION) + + init { + var version = version + mVersion = 0 + isVersionValid = false + val countDots = version.length - version.replace(".", "").length + + // Complete the version. Version must have 3 dots + for (i in countDots until MAX_DOTS) { + version = "$version.0" + } + + parseVersion(version) + + } + + override fun toString(): String { + // gets the first digit of version, shifting hexadecimal version to right 'til max position + var versionToString = ((mVersion shr 8 * MAX_DOTS) % 256).toString() + for (i in MAX_DOTS - 1 downTo 0) { + // gets another digit of version, shifting hexadecimal version to right 8*i bits and... + // ...discarding left part with mod 256 + versionToString = versionToString + "." + ((mVersion shr 8 * i) % 256).toString() + } + if (!isVersionValid) { + versionToString += " INVALID" + } + return versionToString + } + + override fun compareTo(another: OwnCloudVersion): Int { + return if (another.mVersion == mVersion) + 0 + else if (another.mVersion < mVersion) 1 else -1 + } + + private fun parseVersion(version: String) { + try { + mVersion = getParsedVersion(version) + isVersionValid = true + + } catch (e: Exception) { + isVersionValid = false + // if invalid, the instance will respond as if server is 8.1, minimum with capabilities API, + // and "dead" : https://github.com/owncloud/core/wiki/Maintenance-and-Release-Schedule + mVersion = MINIMUM_VERSION_CAPABILITIES_API + } + + } + + @Throws(NumberFormatException::class) + private fun getParsedVersion(version: String): Int { + var version = version + var versionValue = 0 + + // get only numeric part + version = version.replace("[^\\d.]".toRegex(), "") + + val nums = version.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + var i = 0 + while (i < nums.size && i <= MAX_DOTS) { + versionValue += Integer.parseInt(nums[i]) + if (i < nums.size - 1) { + versionValue = versionValue shl 8 + } + i++ + } + + return versionValue + } + + fun supportsRemoteThumbnails(): Boolean { + return mVersion >= MINIMUM_SERVER_VERSION_FOR_REMOTE_THUMBNAILS + } + + override fun describeContents(): Int { + return super.hashCode() + } + + override fun writeToParcel(dest: Parcel, flags: Int) { + dest.writeInt(mVersion) + dest.writeInt(if (isVersionValid) 1 else 0) + } + + companion object { + private const val MINIMUN_MINOR_VERSION_WITHOUT_PUBLIC_UPLOAD_PERMISSION = 0x01000000 // 1.0.0 + + private const val MINIMUN_MICRO_VERSION_WITHOUT_PUBLIC_UPLOAD_PERMISSION = 0x03000000 // 3.0.0 + + const val MINIMUN_VERSION_FOR_CHUNKED_UPLOADS = 0x04050000 // 4.5 + + const val MINIMUM_VERSION_FOR_SHARING_API = 0x05001B00 // 5.0.27 + + const val MINIMUM_VERSION_WITH_FORBIDDEN_CHARS = 0x08010000 // 8.1 + + const val MINIMUM_SERVER_VERSION_FOR_REMOTE_THUMBNAILS = 0x07080000 // 7.8.0 + + const val MINIMUM_VERSION_FOR_SEARCHING_USERS = 0x08020000 //8.2 + + const val VERSION_8 = 0x08000000 // 8.0 + + const val MINIMUM_VERSION_CAPABILITIES_API = 0x08010000 // 8.1 + + private const val MINIMUM_VERSION_WITH_NOT_RESHAREABLE_FEDERATED = 0x09010000 // 9.1 + + private const val MINIMUM_VERSION_WITH_SESSION_MONITORING = 0x09010000 // 9.1 + + private const val MINIMUM_VERSION_WITH_SESSION_MONITORING_WORKING_IN_PREEMPTIVE_MODE = 0x09010301 + // 9.1.3.1, final 9.1.3: https://github.com/owncloud/core/commit/f9a867b70c217463289a741d4d26079eb2a80dfd + + private const val MINIMUM_VERSION_WITH_MULTIPLE_PUBLIC_SHARING = 0xA000000 // 10.0.0 + + private const val MINIMUN_MAJOR_VERSION_WITHOUT_PUBLIC_UPLOAD_PERMISSION = 0xA000000 // 10.0.0 + + private const val MINIMUM_VERSION_WITH_WRITE_ONLY_PUBLIC_SHARING = 0xA000100 // 10.0.1 + + private const val INVALID_ZERO_VERSION = "0.0.0" + + private const val MAX_DOTS = 3 + } +} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/RemoteCapability.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/RemoteCapability.kt new file mode 100644 index 00000000..a38a9343 --- /dev/null +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/RemoteCapability.kt @@ -0,0 +1,101 @@ +/* ownCloud Android Library is available under MIT license + * @author masensio + * @author David González Verdugo + * Copyright (C) 2019 ownCloud GmbH. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ +package com.owncloud.android.lib.resources.status + +/** + * Contains data of the Capabilities for an account, from the Capabilities API + */ +class RemoteCapability { + var accountName: String + + // Server version + var versionMayor: Int + var versionMinor: Int + var versionMicro: Int + var versionString: String + var versionEdition: String + + // Core PollInterval + var corePollinterval: Int + + // Files Sharing + var filesSharingApiEnabled: CapabilityBooleanType + var filesSharingPublicEnabled: CapabilityBooleanType + var filesSharingPublicPasswordEnforced: CapabilityBooleanType + var filesSharingPublicPasswordEnforcedReadOnly: CapabilityBooleanType + var filesSharingPublicPasswordEnforcedReadWrite: CapabilityBooleanType + var filesSharingPublicPasswordEnforcedUploadOnly: CapabilityBooleanType + var filesSharingPublicExpireDateEnabled: CapabilityBooleanType + var filesSharingPublicExpireDateDays: Int + var filesSharingPublicExpireDateEnforced: CapabilityBooleanType + var filesSharingPublicSendMail: CapabilityBooleanType + var filesSharingPublicUpload: CapabilityBooleanType + var filesSharingPublicMultiple: CapabilityBooleanType + var filesSharingPublicSupportsUploadOnly: CapabilityBooleanType + var filesSharingUserSendMail: CapabilityBooleanType + var filesSharingResharing: CapabilityBooleanType + var filesSharingFederationOutgoing: CapabilityBooleanType + var filesSharingFederationIncoming: CapabilityBooleanType + + // Files + var filesBigFileChunking: CapabilityBooleanType + var filesUndelete: CapabilityBooleanType + var filesVersioning: CapabilityBooleanType + + init { + accountName = "" + + versionMayor = 0 + versionMinor = 0 + versionMicro = 0 + versionString = "" + versionEdition = "" + + corePollinterval = 0 + + filesSharingApiEnabled = CapabilityBooleanType.UNKNOWN + filesSharingPublicEnabled = CapabilityBooleanType.UNKNOWN + filesSharingPublicPasswordEnforced = CapabilityBooleanType.UNKNOWN + filesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.UNKNOWN + filesSharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.UNKNOWN + filesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.UNKNOWN + filesSharingPublicExpireDateEnabled = CapabilityBooleanType.UNKNOWN + filesSharingPublicExpireDateDays = 0 + filesSharingPublicExpireDateEnforced = CapabilityBooleanType.UNKNOWN + filesSharingPublicSendMail = CapabilityBooleanType.UNKNOWN + filesSharingPublicUpload = CapabilityBooleanType.UNKNOWN + filesSharingPublicMultiple = CapabilityBooleanType.UNKNOWN + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.UNKNOWN + filesSharingUserSendMail = CapabilityBooleanType.UNKNOWN + filesSharingResharing = CapabilityBooleanType.UNKNOWN + filesSharingFederationOutgoing = CapabilityBooleanType.UNKNOWN + filesSharingFederationIncoming = CapabilityBooleanType.UNKNOWN + + filesBigFileChunking = CapabilityBooleanType.UNKNOWN + filesUndelete = CapabilityBooleanType.UNKNOWN + filesVersioning = CapabilityBooleanType.UNKNOWN + } +} diff --git a/owncloudComLibrary/src/release/java/com/owncloud/android/lib/testing/OpenForTesting.kt b/owncloudComLibrary/src/release/java/com/owncloud/android/lib/testing/OpenForTesting.kt new file mode 100644 index 00000000..3c91e836 --- /dev/null +++ b/owncloudComLibrary/src/release/java/com/owncloud/android/lib/testing/OpenForTesting.kt @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2018 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.owncloud.android.lib.testing + +/** + * This annotation allows us to open some classes for mocking purposes while they are final in + * release builds. + */ +@Target(AnnotationTarget.ANNOTATION_CLASS) +annotation class OpenClass + +/** + * Annotate a class with [OpenForTesting] if you want it to be extendable in debug builds. + */ +@OpenClass +@Target(AnnotationTarget.CLASS) +annotation class OpenForTesting