|
| 1 | +/* |
| 2 | + * Nextcloud Android Library |
| 3 | + * |
| 4 | + * SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]> |
| 5 | + * SPDX-License-Identifier: MIT |
| 6 | + */ |
| 7 | + |
| 8 | +package com.owncloud.android.lib.resources.shares.extensions |
| 9 | + |
| 10 | +import com.owncloud.android.lib.resources.shares.OCShare |
| 11 | +import org.json.JSONArray |
| 12 | +import org.json.JSONObject |
| 13 | + |
| 14 | +private const val KEY = "key" |
| 15 | +private const val SCOPE_KEY = "scope" |
| 16 | +private const val DOWNLOAD_KEY = "download" |
| 17 | +private const val PERMISSIONS_KEY = "permissions" |
| 18 | +private const val VALUE_KEY = "value" |
| 19 | +private const val ENABLED_KEY = "enabled" |
| 20 | + |
| 21 | +fun toggleAllowDownloadAndSync( |
| 22 | + attributes: String?, |
| 23 | + isChecked: Boolean, |
| 24 | + useV2DownloadAttributes: Boolean |
| 25 | +): String? { |
| 26 | + var jsonArray = JSONArray() |
| 27 | + if (!attributes.isNullOrEmpty()) { |
| 28 | + jsonArray = JSONArray(attributes) |
| 29 | + } |
| 30 | + |
| 31 | + val downloadAttr = jsonArray.findDownloadAttribute() |
| 32 | + val enabledKey = getEnabledKey(useV2DownloadAttributes) |
| 33 | + |
| 34 | + if (downloadAttr != null) { |
| 35 | + downloadAttr.put(enabledKey, isChecked) |
| 36 | + } else { |
| 37 | + jsonArray.put( |
| 38 | + JSONObject().apply { |
| 39 | + put(KEY, DOWNLOAD_KEY) |
| 40 | + put(SCOPE_KEY, PERMISSIONS_KEY) |
| 41 | + put(enabledKey, isChecked) |
| 42 | + } |
| 43 | + ) |
| 44 | + } |
| 45 | + |
| 46 | + return jsonArray.toString() |
| 47 | +} |
| 48 | + |
| 49 | +@Suppress("ReturnCount") |
| 50 | +fun OCShare?.isAllowDownloadAndSyncEnabled(useV2DownloadAttributes: Boolean): Boolean { |
| 51 | + if (this?.attributes.isNullOrEmpty()) return false |
| 52 | + |
| 53 | + val jsonArray = JSONArray(this.attributes) |
| 54 | + val downloadAttr = jsonArray.findDownloadAttribute() ?: return false |
| 55 | + val enabledKey = getEnabledKey(useV2DownloadAttributes) |
| 56 | + |
| 57 | + return downloadAttr.optBoolean(enabledKey, false) |
| 58 | +} |
| 59 | + |
| 60 | +private fun JSONArray.findDownloadAttribute(): JSONObject? = |
| 61 | + (0 until length()) |
| 62 | + .asSequence() |
| 63 | + .map { getJSONObject(it) } |
| 64 | + .find { |
| 65 | + it.optString(KEY) == DOWNLOAD_KEY && |
| 66 | + it.optString(SCOPE_KEY) == PERMISSIONS_KEY |
| 67 | + } |
| 68 | + |
| 69 | +private fun getEnabledKey(isV2: Boolean): String = if (isV2) VALUE_KEY else ENABLED_KEY |
0 commit comments