Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fa4d3686d6 | ||
|
|
f0d6a1e41e | ||
|
|
2d0c23c6fe | ||
|
|
d21dbf664f | ||
|
|
36cb08291b | ||
|
|
a8ef34a4b5 | ||
|
|
24a40214b2 | ||
|
|
39219060c3 | ||
|
|
2553d082b4 | ||
|
|
2735487fff | ||
|
|
7972a8e03c | ||
|
|
3f4417d374 | ||
|
|
6f2b9ce8b2 | ||
|
|
7fe6bde6ed | ||
|
|
413ddaa77b | ||
|
|
d04ec2ae3d | ||
|
|
c0b53f894a | ||
|
|
d3dd3aac16 | ||
|
|
1b3da2686e | ||
|
|
996ce970e6 | ||
|
|
61b01b666b | ||
|
|
88148f3743 | ||
|
|
ecf31ffd22 | ||
|
|
7046830a1e | ||
|
|
2dc40b1836 | ||
|
|
03a2fbeb6f | ||
|
|
25f5fd4d9c | ||
|
|
a82067a2bb | ||
|
|
66a2b6d56b | ||
|
|
bac9e1c5a1 | ||
|
|
152108a7c3 | ||
|
|
bec39ce821 | ||
|
|
23f4c60c2c | ||
|
|
dc4e0e94f6 | ||
|
|
a9dc993969 | ||
|
|
f09acb1803 | ||
|
|
33ed8d00f7 | ||
|
|
d466b7802e | ||
|
|
0c8ec9e2b1 | ||
|
|
33014e63b4 | ||
|
|
928461697d | ||
|
|
bb45b7fa38 | ||
|
|
144b70b8e5 | ||
|
|
ae1397630e | ||
|
|
a9b083ede1 | ||
|
|
62dca7aa6b | ||
|
|
bbf06013cb | ||
|
|
63d4560c5e | ||
|
|
31ebe1e6a4 | ||
|
|
04226699a5 | ||
|
|
7091fc859d | ||
|
|
7dde2537ba | ||
|
|
29f20c1efc | ||
|
|
8d88042da4 | ||
|
|
a72dc25c55 | ||
|
|
98faff15cd | ||
|
|
3b53419d08 | ||
|
|
c00ccf726f | ||
|
|
64b90f11b0 | ||
|
|
4688d114d6 | ||
|
|
b6e7414e25 | ||
|
|
29f82ab766 | ||
|
|
cbe895f258 | ||
|
|
3b4ceb77df | ||
|
|
9e2f2181a9 | ||
|
|
2a03185aaa | ||
|
|
29c9b6201b | ||
|
|
caf6c2ca5e | ||
|
|
e5d38cf0bf | ||
|
|
8ad26c9f5e | ||
|
|
d6796e31b6 | ||
|
|
a9d7451ae4 | ||
|
|
9875eb5303 | ||
|
|
a0d9a0c3b6 | ||
|
|
e7fee59135 | ||
|
|
6533ecd576 | ||
|
|
8b491d86a8 | ||
|
|
54a8f0a495 | ||
|
|
01ce97e453 | ||
|
|
3a82580828 | ||
|
|
cfb75c64e1 | ||
|
|
232fa2ea6e | ||
|
|
7a5c48a9f0 |
No files matched your search
@@ -49,7 +49,7 @@ jobs:
|
||||
with:
|
||||
swap-size-gb: 10
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
uses: github/codeql-action/init@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
- name: Set up JDK 21
|
||||
@@ -63,4 +63,4 @@ jobs:
|
||||
echo "org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError" > "$HOME/.gradle/gradle.properties"
|
||||
./gradlew --no-daemon assembleDebug
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
uses: github/codeql-action/analyze@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2
|
||||
@@ -80,6 +80,8 @@ jobs:
|
||||
force-avd-creation: false
|
||||
arch: x86_64
|
||||
sdcard-path-or-size: 100M
|
||||
ram-size: 4096M
|
||||
heap-size: 512M
|
||||
target: google_apis
|
||||
emulator-options: -no-metrics -no-window -gpu swiftshader_indirect -no-snapshot -noaudio -no-boot-anim -skin 500x833
|
||||
script: scripts/runCombinedTest.sh ${{github.event.number}} ${{ secrets.LOG_USERNAME }} ${{ secrets.LOG_PASSWORD }} ${{github.event.number}} ${{ matrix.server }}
|
||||
|
||||
@@ -42,6 +42,6 @@ jobs:
|
||||
|
||||
# Upload the results to GitHub's code scanning dashboard.
|
||||
- name: "Upload to code-scanning"
|
||||
uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
uses: github/codeql-action/upload-sarif@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
@@ -2,3 +2,6 @@ source "https://rubygems.org"
|
||||
|
||||
gem "fastlane"
|
||||
gem "abbrev"
|
||||
|
||||
plugins_path = File.join(File.dirname(__FILE__), '.', 'Pluginfile')
|
||||
eval_gemfile(plugins_path) if File.exist?(plugins_path)
|
||||
+37
-41
@@ -7,10 +7,10 @@ GEM
|
||||
public_suffix (>= 2.0.2, < 8.0)
|
||||
artifactory (3.0.17)
|
||||
atomos (0.1.3)
|
||||
aws-eventstream (1.4.1)
|
||||
aws-partitions (1.1299.1)
|
||||
aws-sdk-core (3.262.0)
|
||||
aws-eventstream (~> 1, >= 1.4.1)
|
||||
aws-eventstream (1.4.0)
|
||||
aws-partitions (1.1290.0)
|
||||
aws-sdk-core (3.257.0)
|
||||
aws-eventstream (~> 1, >= 1.3.0)
|
||||
aws-partitions (~> 1, >= 1.992.0)
|
||||
aws-sigv4 (~> 1.9)
|
||||
base64
|
||||
@@ -18,11 +18,11 @@ GEM
|
||||
jmespath (~> 1, >= 1.6.1)
|
||||
logger
|
||||
rexml (~> 3.4, >= 3.4.2)
|
||||
aws-sdk-kms (1.137.0)
|
||||
aws-sdk-core (~> 3, >= 3.262.0)
|
||||
aws-sdk-kms (1.132.0)
|
||||
aws-sdk-core (~> 3, >= 3.256.0)
|
||||
aws-sigv4 (~> 1.5)
|
||||
aws-sdk-s3 (1.236.0)
|
||||
aws-sdk-core (~> 3, >= 3.262.0)
|
||||
aws-sdk-s3 (1.232.2)
|
||||
aws-sdk-core (~> 3, >= 3.256.0)
|
||||
aws-sdk-kms (~> 1)
|
||||
aws-sigv4 (~> 1.5)
|
||||
aws-sigv4 (1.12.1)
|
||||
@@ -37,17 +37,18 @@ GEM
|
||||
colored2 (3.1.2)
|
||||
commander (4.6.0)
|
||||
highline (~> 2.0.0)
|
||||
csv (3.3.7)
|
||||
csv (3.3.6)
|
||||
declarative (0.0.20)
|
||||
digest-crc (0.7.0)
|
||||
rake (>= 12.0.0, < 14.0.0)
|
||||
domain_name (0.7.20261007)
|
||||
domain_name (0.6.20260921)
|
||||
dotenv (2.8.1)
|
||||
emoji_regex (3.2.3)
|
||||
erb (6.0.7)
|
||||
excon (1.9.0)
|
||||
faraday (2.15.1)
|
||||
faraday-net_http (>= 2.0, < 3.6)
|
||||
excon (1.7.1)
|
||||
logger
|
||||
faraday (2.14.4)
|
||||
faraday-net_http (>= 2.0, < 3.5)
|
||||
json
|
||||
logger
|
||||
faraday-cookie_jar (0.0.8)
|
||||
@@ -57,12 +58,12 @@ GEM
|
||||
faraday (>= 1, < 3)
|
||||
faraday-multipart (1.2.0)
|
||||
multipart-post (~> 2.0)
|
||||
faraday-net_http (3.5.0)
|
||||
faraday-net_http (3.4.4)
|
||||
net-http (~> 0.5)
|
||||
faraday-retry (2.4.0)
|
||||
faraday (~> 2.0)
|
||||
fastimage (2.4.3)
|
||||
fastlane (2.241.2)
|
||||
fastimage (2.4.1)
|
||||
fastlane (2.240.1)
|
||||
CFPropertyList (>= 2.3, < 5.0.0)
|
||||
abbrev (~> 0.1)
|
||||
addressable (>= 2.9.0, < 3.0.0)
|
||||
@@ -78,8 +79,7 @@ GEM
|
||||
csv (~> 3.3)
|
||||
dotenv (>= 2.1.1, < 3.0.0)
|
||||
emoji_regex (>= 0.1, < 4.0)
|
||||
erb (>= 4.0, < 7.0)
|
||||
excon (>= 1.0.0, < 2.0.0)
|
||||
excon (>= 0.71.0, < 2.0.0)
|
||||
faraday (~> 2.7)
|
||||
faraday-cookie_jar (~> 0.0.8)
|
||||
faraday-follow_redirects (~> 0.3)
|
||||
@@ -90,7 +90,7 @@ GEM
|
||||
gh_inspector (>= 1.1.2, < 2.0.0)
|
||||
google-apis-androidpublisher_v3 (~> 0.99)
|
||||
google-apis-playcustomapp_v1 (~> 0.1)
|
||||
google-cloud-env (>= 1.6.0, < 2.5.0)
|
||||
google-cloud-env (>= 1.6.0, < 2.4.0)
|
||||
google-cloud-storage (~> 1.31)
|
||||
highline (~> 2.0)
|
||||
irb (>= 1.8)
|
||||
@@ -109,7 +109,7 @@ GEM
|
||||
rubyzip (>= 3.4.0, < 4.0.0)
|
||||
security (~> 0.3)
|
||||
simctl (~> 1.6.3)
|
||||
terminal-notifier (>= 3.1.0, < 4.0.0)
|
||||
terminal-notifier (>= 2.0.0, < 3.0.0)
|
||||
terminal-table (~> 4)
|
||||
tty-screen (>= 0.6.3, < 1.0.0)
|
||||
tty-spinner (>= 0.8.0, < 1.0.0)
|
||||
@@ -119,9 +119,9 @@ GEM
|
||||
xcpretty-travis-formatter (>= 0.0.3, < 2.0.0)
|
||||
fastlane-sirp (1.1.0)
|
||||
gh_inspector (1.1.3)
|
||||
google-apis-androidpublisher_v3 (0.110.0)
|
||||
google-apis-androidpublisher_v3 (0.109.0)
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-apis-core (1.4.0)
|
||||
google-apis-core (1.2.5)
|
||||
addressable (~> 2.9)
|
||||
faraday (~> 2.13)
|
||||
faraday-follow_redirects (~> 0.3)
|
||||
@@ -134,16 +134,16 @@ GEM
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-apis-playcustomapp_v1 (0.18.0)
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-apis-storage_v1 (0.70.0)
|
||||
google-apis-storage_v1 (0.68.0)
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-cloud-core (1.9.0)
|
||||
google-cloud-env (>= 1.0, < 3.a)
|
||||
google-cloud-errors (~> 1.0)
|
||||
google-cloud-env (2.4.1)
|
||||
google-cloud-env (2.3.1)
|
||||
base64 (~> 0.2)
|
||||
faraday (>= 1.0, < 3.a)
|
||||
google-cloud-errors (1.7.0)
|
||||
google-cloud-storage (1.62.1)
|
||||
google-cloud-storage (1.62.0)
|
||||
addressable (~> 2.8)
|
||||
digest-crc (~> 0.4)
|
||||
google-apis-core (>= 0.18, < 2)
|
||||
@@ -152,8 +152,8 @@ GEM
|
||||
google-cloud-core (~> 1.6)
|
||||
googleauth (~> 1.9)
|
||||
mini_mime (~> 1.0)
|
||||
google-logging-utils (0.2.1)
|
||||
googleauth (1.17.6)
|
||||
google-logging-utils (0.2.0)
|
||||
googleauth (1.17.4)
|
||||
faraday (>= 1.0, < 3.a)
|
||||
google-cloud-env (~> 2.2)
|
||||
google-logging-utils (~> 0.1)
|
||||
@@ -164,7 +164,7 @@ GEM
|
||||
highline (2.0.3)
|
||||
http-cookie (1.1.6)
|
||||
domain_name (~> 0.5)
|
||||
io-console (0.9.5)
|
||||
io-console (0.9.4)
|
||||
irb (1.18.0)
|
||||
pp (>= 0.6.0)
|
||||
prism (>= 1.3.0)
|
||||
@@ -182,11 +182,8 @@ GEM
|
||||
mutex_m (0.3.0)
|
||||
nanaimo (0.4.0)
|
||||
naturally (2.3.0)
|
||||
net-http (0.10.0)
|
||||
net-protocol (>= 0.3.0)
|
||||
net-http (0.9.1)
|
||||
uri (>= 0.11.1)
|
||||
net-protocol (0.4.0)
|
||||
timeout
|
||||
nkf (0.3.0)
|
||||
optparse (0.8.1)
|
||||
os (1.1.4)
|
||||
@@ -194,23 +191,23 @@ GEM
|
||||
plist (3.7.2)
|
||||
pp (0.6.4)
|
||||
prettyprint
|
||||
prettyprint (0.2.1)
|
||||
prettyprint (0.2.0)
|
||||
prism (1.9.0)
|
||||
pstore (0.3.0)
|
||||
pstore (0.2.1)
|
||||
public_suffix (7.0.5)
|
||||
rake (13.4.2)
|
||||
rbs (4.2.0)
|
||||
logger
|
||||
prism (>= 1.6.0)
|
||||
tsort
|
||||
rdoc (8.1.0)
|
||||
rdoc (8.0.0)
|
||||
erb
|
||||
prism (>= 1.6.0)
|
||||
rbs (>= 4.0.0)
|
||||
tsort
|
||||
reline (0.7.0)
|
||||
io-console (~> 0.5)
|
||||
representable (3.3.1)
|
||||
representable (3.3.0)
|
||||
declarative (< 0.1.0)
|
||||
trailblazer-option (>= 0.1.1, < 0.2.0)
|
||||
uber (< 0.2.0)
|
||||
@@ -218,18 +215,17 @@ GEM
|
||||
rexml (3.4.4)
|
||||
rouge (3.28.0)
|
||||
rubyzip (3.7.0)
|
||||
security (0.4.0)
|
||||
signet (0.22.1)
|
||||
security (0.3.0)
|
||||
signet (0.22.0)
|
||||
addressable (~> 2.8)
|
||||
faraday (>= 0.17.5, < 3.a)
|
||||
jwt (>= 1.5, < 4.0)
|
||||
simctl (1.6.10)
|
||||
CFPropertyList
|
||||
naturally
|
||||
terminal-notifier (3.1.0)
|
||||
terminal-notifier (2.0.0)
|
||||
terminal-table (4.0.0)
|
||||
unicode-display_width (>= 1.1.1, < 4)
|
||||
timeout (0.6.1)
|
||||
trailblazer-option (0.1.2)
|
||||
tsort (0.2.0)
|
||||
tty-cursor (0.7.1)
|
||||
@@ -240,7 +236,7 @@ GEM
|
||||
unicode-display_width (3.3.0)
|
||||
unicode-emoji (~> 4.3)
|
||||
unicode-emoji (4.3.0)
|
||||
uri (1.1.2)
|
||||
uri (1.1.1)
|
||||
word_wrap (1.0.0)
|
||||
xcodeproj (1.28.1)
|
||||
CFPropertyList (>= 2.3.3, < 4.0)
|
||||
|
||||
@@ -99,7 +99,7 @@ class ActivitiesFragmentIT : AbstractIT() {
|
||||
fun showActivities() {
|
||||
val capability = OCCapability()
|
||||
capability.versionMayor = 20
|
||||
fileDataStorageManager.saveCapabilities(capability)
|
||||
storageManager.saveCapabilities(capability)
|
||||
|
||||
val date = GregorianCalendar()
|
||||
date.set(2005, 4, 17, 10, 35, 30)
|
||||
|
||||
@@ -23,6 +23,7 @@ import com.owncloud.android.R
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.ui.activity.FileDisplayActivity
|
||||
import com.owncloud.android.ui.fragment.EmptyListState
|
||||
import com.owncloud.android.ui.fragment.FabState
|
||||
import com.owncloud.android.utils.ScreenshotTest
|
||||
import org.junit.Assert
|
||||
import org.junit.Rule
|
||||
@@ -48,7 +49,7 @@ class FileDisplayActivityScreenshotIT : AbstractIT() {
|
||||
scenario.onActivity { sut ->
|
||||
sut.run {
|
||||
listOfFilesFragment?.let {
|
||||
it.setFabEnabled(false)
|
||||
it.setFabState(FabState.DISABLED)
|
||||
resetScrolling(true)
|
||||
it.setEmptyListMessage(EmptyListState.LOADING)
|
||||
it.isLoading = false
|
||||
@@ -78,7 +79,7 @@ class FileDisplayActivityScreenshotIT : AbstractIT() {
|
||||
activity = sut
|
||||
val fragment = sut.listOfFilesFragment
|
||||
Assert.assertNotNull(fragment)
|
||||
fragment!!.setFabEnabled(false)
|
||||
fragment!!.setFabState(FabState.DISABLED)
|
||||
fragment.setEmptyListMessage(EmptyListState.LOADING)
|
||||
fragment.isLoading = false
|
||||
}
|
||||
@@ -91,7 +92,7 @@ class FileDisplayActivityScreenshotIT : AbstractIT() {
|
||||
.perform(NavigationViewActions.navigateTo(R.id.nav_all_files))
|
||||
|
||||
val fragment = activity!!.listOfFilesFragment
|
||||
fragment!!.setFabEnabled(false)
|
||||
fragment!!.setFabState(FabState.DISABLED)
|
||||
fragment.setEmptyListMessage(EmptyListState.LOADING)
|
||||
fragment.isLoading = false
|
||||
|
||||
@@ -117,7 +118,7 @@ class FileDisplayActivityScreenshotIT : AbstractIT() {
|
||||
resetScrolling(true)
|
||||
|
||||
listOfFilesFragment?.let {
|
||||
it.setFabEnabled(false)
|
||||
it.setFabState(FabState.DISABLED)
|
||||
it.setEmptyListMessage(EmptyListState.LOADING)
|
||||
it.isLoading = false
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ import androidx.test.espresso.Espresso.onView
|
||||
import androidx.test.espresso.assertion.ViewAssertions.matches
|
||||
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
|
||||
import androidx.test.espresso.matcher.ViewMatchers.isRoot
|
||||
import com.nextcloud.test.GrantStoragePermissionRule.Companion.grant
|
||||
import com.owncloud.android.AbstractIT
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProviderImpl
|
||||
import com.owncloud.android.ui.activity.RequestCredentialsActivity
|
||||
@@ -22,17 +21,12 @@ import com.owncloud.android.ui.activity.SettingsActivity
|
||||
import com.owncloud.android.utils.EncryptionUtils
|
||||
import com.owncloud.android.utils.ScreenshotTest
|
||||
import org.junit.Assert
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TestRule
|
||||
|
||||
@Suppress("FunctionNaming")
|
||||
class SettingsActivityIT : AbstractIT() {
|
||||
private val testClassName = "com.nextcloud.client.SettingsActivityIT"
|
||||
|
||||
@get:Rule
|
||||
var storagePermissionRule: TestRule = grant()
|
||||
|
||||
@Test
|
||||
@ScreenshotTest
|
||||
fun open() {
|
||||
|
||||
@@ -25,14 +25,14 @@ class AssistantRepositoryTests : AbstractOnServerIT() {
|
||||
|
||||
@Before
|
||||
fun setup() {
|
||||
sut = AssistantRemoteRepositoryImpl(nextcloudClient, capability)
|
||||
sut = AssistantRemoteRepositoryImpl(nextcloudClient, getCapability())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetTaskTypes() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_28)
|
||||
|
||||
if (capability.assistant.isFalse) {
|
||||
if (getCapability().assistant.isFalse) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ class AssistantRepositoryTests : AbstractOnServerIT() {
|
||||
fun testGetTaskList() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_28)
|
||||
|
||||
if (capability.assistant.isFalse) {
|
||||
if (getCapability().assistant.isFalse) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ class AssistantRepositoryTests : AbstractOnServerIT() {
|
||||
fun testCreateTask() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_28)
|
||||
|
||||
if (capability.assistant.isFalse) {
|
||||
if (getCapability().assistant.isFalse) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ class AssistantRepositoryTests : AbstractOnServerIT() {
|
||||
fun testDeleteTask() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_28)
|
||||
|
||||
if (capability.assistant.isFalse) {
|
||||
if (getCapability().assistant.isFalse) {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -101,7 +101,7 @@ class ContactsBackupIT : AbstractOnServerIT() {
|
||||
fail("folderPath cannot be empty")
|
||||
}
|
||||
|
||||
val folder = fileDataStorageManager.getFileByDecryptedRemotePath(folderPath)
|
||||
val folder = storageManager.getFileByDecryptedRemotePath(folderPath)
|
||||
if (folder == null) {
|
||||
fail("folder cannot be null")
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ import org.junit.Test
|
||||
@SinceServer(majorVersion = 30)
|
||||
class AutoRenameTests : AbstractOnServerIT() {
|
||||
|
||||
private var capability: OCCapability = fileDataStorageManager.getCapability(account.name)
|
||||
private var capability: OCCapability = storageManager.getCapability(account.name)
|
||||
private val forbiddenFilenameExtension = "."
|
||||
private val forbiddenFilenameCharacter = ">"
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ class FileNameValidatorTests : AbstractOnServerIT() {
|
||||
private const val MAX_FILENAME_SIZE = 250
|
||||
}
|
||||
|
||||
private var capability: OCCapability = fileDataStorageManager.getCapability(account.name)
|
||||
private var capability: OCCapability = storageManager.getCapability(account.name)
|
||||
|
||||
@Before
|
||||
fun setup() {
|
||||
|
||||
@@ -19,7 +19,7 @@ import org.junit.Test
|
||||
|
||||
@Suppress("MagicNumber")
|
||||
class OCCapabilityJsonToListTests : AbstractIT() {
|
||||
private var capability: OCCapability = fileDataStorageManager.getCapability(account.name)
|
||||
private var capability: OCCapability = storageManager.getCapability(account.name)
|
||||
|
||||
// region Valid Input
|
||||
@Test
|
||||
|
||||
@@ -1,511 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2018 Tobias Kaminsky <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.owncloud.android;
|
||||
|
||||
import android.accounts.Account;
|
||||
import android.accounts.AccountManager;
|
||||
import android.accounts.AuthenticatorException;
|
||||
import android.accounts.OperationCanceledException;
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.content.res.Configuration;
|
||||
import android.content.res.Resources;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.text.TextUtils;
|
||||
import android.view.View;
|
||||
|
||||
import com.facebook.testing.screenshot.Screenshot;
|
||||
import com.facebook.testing.screenshot.internal.TestNameDetector;
|
||||
import com.nextcloud.android.common.ui.theme.MaterialSchemes;
|
||||
import com.nextcloud.android.common.ui.theme.MaterialSchemesImpl;
|
||||
import com.nextcloud.client.account.User;
|
||||
import com.nextcloud.client.account.UserAccountManager;
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl;
|
||||
import com.nextcloud.utils.PowerManagementFactory;
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker;
|
||||
import com.nextcloud.client.network.ConnectivityManagerFactory;
|
||||
import com.nextcloud.client.network.ConnectivityService;
|
||||
import com.nextcloud.client.preferences.AppPreferencesImpl;
|
||||
import com.nextcloud.client.preferences.DarkMode;
|
||||
import com.nextcloud.common.NextcloudClient;
|
||||
import com.nextcloud.test.GrantStoragePermissionRule;
|
||||
import com.nextcloud.test.RandomStringGenerator;
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProvider;
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProviderImpl;
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager;
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager;
|
||||
import com.owncloud.android.db.OCUpload;
|
||||
import com.owncloud.android.files.services.NameCollisionPolicy;
|
||||
import com.owncloud.android.lib.common.OwnCloudClient;
|
||||
import com.owncloud.android.lib.common.OwnCloudClientFactory;
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils;
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
|
||||
import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
|
||||
import com.owncloud.android.lib.resources.status.CapabilityBooleanType;
|
||||
import com.owncloud.android.lib.resources.status.GetCapabilitiesRemoteOperation;
|
||||
import com.owncloud.android.lib.resources.status.OCCapability;
|
||||
import com.owncloud.android.lib.resources.status.OwnCloudVersion;
|
||||
import com.owncloud.android.operations.CreateFolderOperation;
|
||||
import com.owncloud.android.operations.UploadFileOperation;
|
||||
import com.owncloud.android.utils.FileStorageUtils;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Rule;
|
||||
import org.junit.rules.TestRule;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
import androidx.fragment.app.DialogFragment;
|
||||
import androidx.test.espresso.contrib.DrawerActions;
|
||||
import androidx.test.espresso.intent.rule.IntentsTestRule;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry;
|
||||
import androidx.test.runner.lifecycle.Stage;
|
||||
|
||||
import static androidx.test.InstrumentationRegistry.getInstrumentation;
|
||||
import static androidx.test.espresso.Espresso.onView;
|
||||
import static androidx.test.espresso.matcher.ViewMatchers.withId;
|
||||
import static com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assume.assumeTrue;
|
||||
|
||||
/**
|
||||
* Common base for all integration tests.
|
||||
*/
|
||||
public abstract class AbstractIT {
|
||||
@Rule
|
||||
public final TestRule storagePermissionRule = GrantStoragePermissionRule.grant();
|
||||
|
||||
protected ConnectivityService connectivityServiceMock = ConnectivityManagerFactory.INSTANCE.getMock();
|
||||
|
||||
protected static OwnCloudClient client;
|
||||
protected static NextcloudClient nextcloudClient;
|
||||
protected static Account account;
|
||||
protected static User user;
|
||||
protected static Context targetContext;
|
||||
protected static String DARK_MODE = "";
|
||||
protected static String COLOR = "";
|
||||
|
||||
protected Activity currentActivity;
|
||||
|
||||
protected FileDataStorageManager fileDataStorageManager =
|
||||
new FileDataStorageManager(user, targetContext.getContentResolver());
|
||||
|
||||
protected ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProviderImpl(targetContext);
|
||||
|
||||
@BeforeClass
|
||||
public static void beforeAll() {
|
||||
try {
|
||||
// clean up
|
||||
targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
|
||||
AccountManager platformAccountManager = AccountManager.get(targetContext);
|
||||
|
||||
for (Account account : platformAccountManager.getAccounts()) {
|
||||
if (account.type.equalsIgnoreCase(MainApp.getAccountType(targetContext))) {
|
||||
platformAccountManager.removeAccountExplicitly(account);
|
||||
}
|
||||
}
|
||||
|
||||
account = createAccount("test@https://nextcloud.localhost");
|
||||
user = getUser(account);
|
||||
|
||||
client = OwnCloudClientFactory.createOwnCloudClient(account, targetContext);
|
||||
nextcloudClient = OwnCloudClientFactory.createNextcloudClient(user, targetContext);
|
||||
} catch (OperationCanceledException |
|
||||
IOException |
|
||||
AccountUtils.AccountNotFoundException |
|
||||
AuthenticatorException e) {
|
||||
throw new RuntimeException("Error setting up clients", e);
|
||||
}
|
||||
|
||||
Bundle arguments = androidx.test.platform.app.InstrumentationRegistry.getArguments();
|
||||
|
||||
// color
|
||||
String colorParameter = arguments.getString("COLOR");
|
||||
if (!TextUtils.isEmpty(colorParameter)) {
|
||||
FileDataStorageManager fileDataStorageManager = new FileDataStorageManager(user,
|
||||
targetContext.getContentResolver());
|
||||
|
||||
String colorHex = null;
|
||||
COLOR = colorParameter;
|
||||
switch (colorParameter) {
|
||||
case "red":
|
||||
colorHex = "#7c0000";
|
||||
break;
|
||||
|
||||
case "green":
|
||||
colorHex = "#00ff00";
|
||||
break;
|
||||
|
||||
case "white":
|
||||
colorHex = "#ffffff";
|
||||
break;
|
||||
|
||||
case "black":
|
||||
colorHex = "#000000";
|
||||
break;
|
||||
|
||||
case "lightgreen":
|
||||
colorHex = "#aaff00";
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
OCCapability capability = fileDataStorageManager.getCapability(account.name);
|
||||
capability.setGroupfolders(CapabilityBooleanType.TRUE);
|
||||
|
||||
if (colorHex != null) {
|
||||
capability.setServerColor(colorHex);
|
||||
}
|
||||
|
||||
fileDataStorageManager.saveCapabilities(capability);
|
||||
}
|
||||
|
||||
// dark / light
|
||||
String darkModeParameter = arguments.getString("DARKMODE");
|
||||
|
||||
if (darkModeParameter != null) {
|
||||
if ("dark".equalsIgnoreCase(darkModeParameter)) {
|
||||
DARK_MODE = "dark";
|
||||
AppPreferencesImpl.fromContext(targetContext).setDarkThemeMode(DarkMode.DARK);
|
||||
MainApp.setAppTheme(DarkMode.DARK);
|
||||
} else {
|
||||
DARK_MODE = "light";
|
||||
}
|
||||
}
|
||||
|
||||
if ("light".equalsIgnoreCase(DARK_MODE) && "blue".equalsIgnoreCase(COLOR)) {
|
||||
// use already existing names
|
||||
DARK_MODE = "";
|
||||
COLOR = "";
|
||||
}
|
||||
}
|
||||
|
||||
protected void testOnlyOnServer(OwnCloudVersion version) throws AccountUtils.AccountNotFoundException {
|
||||
OCCapability ocCapability = getCapability();
|
||||
assumeTrue(ocCapability.getVersion().isNewerOrEqual(version));
|
||||
}
|
||||
|
||||
protected OCCapability getCapability() throws AccountUtils.AccountNotFoundException {
|
||||
NextcloudClient client = OwnCloudClientFactory.createNextcloudClient(user, targetContext);
|
||||
|
||||
return new GetCapabilitiesRemoteOperation().execute(client).getResultData();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void enableAccessibilityChecks() {
|
||||
androidx.test.espresso.accessibility.AccessibilityChecks.enable().setRunChecksFromRootView(true);
|
||||
}
|
||||
|
||||
@After
|
||||
public void after() {
|
||||
fileDataStorageManager.removeLocalFiles(user, fileDataStorageManager);
|
||||
fileDataStorageManager.deleteAllFiles();
|
||||
}
|
||||
|
||||
protected FileDataStorageManager getStorageManager() {
|
||||
return fileDataStorageManager;
|
||||
}
|
||||
|
||||
protected Account[] getAllAccounts() {
|
||||
return AccountManager.get(targetContext).getAccounts();
|
||||
}
|
||||
|
||||
protected static List<File> createDummyFiles() throws IOException {
|
||||
File tempPath = new File(FileStorageUtils.getTemporalPath(account.name));
|
||||
if (!tempPath.exists()) {
|
||||
assertTrue(tempPath.mkdirs());
|
||||
}
|
||||
|
||||
assertTrue(tempPath.exists());
|
||||
|
||||
return Arrays.asList(
|
||||
createFile("empty.txt", 0),
|
||||
createFile("nonEmpty.txt", 100),
|
||||
createFile("chunkedFile.txt", 500000)
|
||||
);
|
||||
}
|
||||
|
||||
protected static File getDummyFile(String name) throws IOException {
|
||||
File file = new File(FileStorageUtils.getInternalTemporalPath(account.name, targetContext) + File.separator + name);
|
||||
|
||||
if (file.exists()) {
|
||||
return file;
|
||||
} else if (name.endsWith("/")) {
|
||||
file.mkdirs();
|
||||
return file;
|
||||
} else {
|
||||
return switch (name) {
|
||||
case "empty.txt" -> createFile("empty.txt", 0);
|
||||
case "nonEmpty.txt" -> createFile("nonEmpty.txt", 100);
|
||||
case "chunkedFile.txt" -> createFile("chunkedFile.txt", 500000);
|
||||
default -> createFile(name, 0);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public static File createFile(String name, int iteration) throws IOException {
|
||||
File file = new File(FileStorageUtils.getTemporalPath(account.name) + File.separator + name);
|
||||
if (!file.getParentFile().exists()) {
|
||||
assertTrue(file.getParentFile().mkdirs());
|
||||
}
|
||||
|
||||
file.createNewFile();
|
||||
|
||||
FileWriter writer = new FileWriter(file);
|
||||
|
||||
for (int i = 0; i < iteration; i++) {
|
||||
writer.write("123123123123123123123123123\n");
|
||||
}
|
||||
writer.flush();
|
||||
writer.close();
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
protected File getFile(String filename) throws IOException {
|
||||
InputStream inputStream = getInstrumentation().getContext().getAssets().open(filename);
|
||||
File temp = File.createTempFile("file", "file");
|
||||
FileUtils.copyInputStreamToFile(inputStream, temp);
|
||||
|
||||
return temp;
|
||||
}
|
||||
|
||||
protected void waitForIdleSync() {
|
||||
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
|
||||
}
|
||||
|
||||
public void onIdleSync(Runnable recipient) {
|
||||
InstrumentationRegistry.getInstrumentation().waitForIdle(recipient);
|
||||
}
|
||||
|
||||
protected void openDrawer(IntentsTestRule activityRule) {
|
||||
Activity sut = activityRule.launchActivity(null);
|
||||
|
||||
shortSleep();
|
||||
|
||||
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
|
||||
|
||||
waitForIdleSync();
|
||||
|
||||
screenshot(sut);
|
||||
}
|
||||
|
||||
protected Activity getCurrentActivity() {
|
||||
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
|
||||
Collection<Activity> resumedActivities = ActivityLifecycleMonitorRegistry
|
||||
.getInstance()
|
||||
.getActivitiesInStage(Stage.RESUMED);
|
||||
|
||||
if (resumedActivities.iterator().hasNext()) {
|
||||
currentActivity = resumedActivities.iterator().next();
|
||||
}
|
||||
});
|
||||
|
||||
return currentActivity;
|
||||
}
|
||||
|
||||
protected static void shortSleep() {
|
||||
try {
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
protected void longSleep() {
|
||||
try {
|
||||
Thread.sleep(20000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
protected void sleep(int second) {
|
||||
try {
|
||||
Thread.sleep(1000L * second);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void createFolder(String remotePath) {
|
||||
RemoteOperationResult check = new ExistenceCheckRemoteOperation(remotePath, false).execute(client);
|
||||
|
||||
if (!check.isSuccess()) {
|
||||
assertTrue(new CreateFolderOperation(remotePath, user, targetContext, getStorageManager())
|
||||
.execute(client)
|
||||
.isSuccess());
|
||||
}
|
||||
}
|
||||
|
||||
public void uploadFile(File file, String remotePath) {
|
||||
OCUpload ocUpload = new OCUpload(file.getAbsolutePath(), remotePath, account.name);
|
||||
|
||||
uploadOCUpload(ocUpload);
|
||||
}
|
||||
|
||||
public void uploadOCUpload(OCUpload ocUpload) {
|
||||
final var powerManagementServiceMock = PowerManagementFactory.getMock();
|
||||
UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
|
||||
UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(accountManager,
|
||||
targetContext.getContentResolver());
|
||||
|
||||
UploadFileOperation newUpload = new UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
user,
|
||||
null,
|
||||
ocUpload,
|
||||
NameCollisionPolicy.DEFAULT,
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
false,
|
||||
getStorageManager()
|
||||
);
|
||||
newUpload.addRenameUploadListener(() -> {
|
||||
// dummy
|
||||
});
|
||||
|
||||
newUpload.setRemoteFolderToBeCreated();
|
||||
|
||||
var result = newUpload.execute(client);
|
||||
assertTrue(result.getLogMessage(), result.isSuccess());
|
||||
}
|
||||
|
||||
protected void enableRTL() {
|
||||
Locale locale = new Locale("ar");
|
||||
Resources resources = InstrumentationRegistry.getInstrumentation().getTargetContext().getResources();
|
||||
Configuration config = resources.getConfiguration();
|
||||
config.setLocale(locale);
|
||||
resources.updateConfiguration(config, null);
|
||||
}
|
||||
|
||||
protected void resetLocale() {
|
||||
Locale locale = new Locale("en");
|
||||
Resources resources = InstrumentationRegistry.getInstrumentation().getTargetContext().getResources();
|
||||
Configuration config = resources.getConfiguration();
|
||||
config.setLocale(locale);
|
||||
resources.updateConfiguration(config, null);
|
||||
}
|
||||
|
||||
protected void screenshot(View view) {
|
||||
screenshot(view, "");
|
||||
}
|
||||
|
||||
public void screenshotViaName(Activity activity, String name) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
|
||||
Screenshot.snapActivity(activity).setName(name).record();
|
||||
}
|
||||
}
|
||||
|
||||
protected void screenshotViaName(View view, String name) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
|
||||
Screenshot.snap(view).setName(name).record();
|
||||
}
|
||||
}
|
||||
|
||||
protected void screenshot(View view, String prefix) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
|
||||
Screenshot.snap(view).setName(createName(prefix)).record();
|
||||
}
|
||||
}
|
||||
|
||||
protected void screenshot(Activity sut) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
|
||||
Screenshot.snapActivity(sut).setName(createName()).record();
|
||||
}
|
||||
}
|
||||
|
||||
protected void screenshot(DialogFragment dialogFragment, String prefix) {
|
||||
screenshot(Objects.requireNonNull(dialogFragment.requireDialog().getWindow()).getDecorView(), prefix);
|
||||
}
|
||||
|
||||
private String createName() {
|
||||
return createName("");
|
||||
}
|
||||
|
||||
public String createName(String name, String prefix) {
|
||||
if (!TextUtils.isEmpty(prefix)) {
|
||||
name = name + "_" + prefix;
|
||||
}
|
||||
|
||||
if (!DARK_MODE.isEmpty()) {
|
||||
name = name + "_" + DARK_MODE;
|
||||
}
|
||||
|
||||
if (!COLOR.isEmpty()) {
|
||||
name = name + "_" + COLOR;
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
private String createName(String prefix) {
|
||||
String name = TestNameDetector.getTestClass() + "_" + TestNameDetector.getTestName();
|
||||
return createName(name, prefix);
|
||||
}
|
||||
|
||||
public static String getUserId(User user) {
|
||||
return AccountManager.get(targetContext).getUserData(user.toPlatformAccount(), KEY_USER_ID);
|
||||
}
|
||||
|
||||
public String getRandomName() {
|
||||
return getRandomName(5);
|
||||
}
|
||||
|
||||
public String getRandomName(int length) {
|
||||
return RandomStringGenerator.make(length);
|
||||
}
|
||||
|
||||
protected static User getUser(Account account) {
|
||||
Optional<User> optionalUser = UserAccountManagerImpl.fromContext(targetContext).getUser(account.name);
|
||||
return optionalUser.orElseThrow(IllegalAccessError::new);
|
||||
}
|
||||
|
||||
protected static Account createAccount(String name) {
|
||||
AccountManager platformAccountManager = AccountManager.get(targetContext);
|
||||
|
||||
Account temp = new Account(name, MainApp.getAccountType(targetContext));
|
||||
int atPos = name.lastIndexOf('@');
|
||||
platformAccountManager.addAccountExplicitly(temp, "password", null);
|
||||
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_BASE_URL,
|
||||
name.substring(atPos + 1));
|
||||
platformAccountManager.setUserData(temp, KEY_USER_ID, name.substring(0, atPos));
|
||||
|
||||
Account account = UserAccountManagerImpl.fromContext(targetContext).getAccountByName(name);
|
||||
if (Objects.equals(account.type, targetContext.getString(R.string.anonymous_account_type))) {
|
||||
throw new RuntimeException("Could not get account with name " + name);
|
||||
}
|
||||
return account;
|
||||
}
|
||||
|
||||
protected static boolean removeAccount(Account account) {
|
||||
return AccountManager.get(targetContext).removeAccountExplicitly(account);
|
||||
}
|
||||
|
||||
protected MaterialSchemes getMaterialSchemesForCurrentUser() {
|
||||
return new MaterialSchemesImpl(R.color.primary, false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android
|
||||
|
||||
import android.accounts.Account
|
||||
import android.accounts.AccountManager
|
||||
import android.accounts.AuthenticatorException
|
||||
import android.accounts.OperationCanceledException
|
||||
import android.app.Activity
|
||||
import android.app.Instrumentation
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.view.View
|
||||
import androidx.fragment.app.DialogFragment
|
||||
import androidx.test.espresso.Espresso.onView
|
||||
import androidx.test.espresso.accessibility.AccessibilityChecks
|
||||
import androidx.test.espresso.contrib.DrawerActions
|
||||
import androidx.test.espresso.intent.rule.IntentsTestRule
|
||||
import androidx.test.espresso.matcher.ViewMatchers.withId
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry
|
||||
import androidx.test.runner.lifecycle.Stage
|
||||
import com.facebook.testing.screenshot.RecordBuilder
|
||||
import com.facebook.testing.screenshot.Screenshot
|
||||
import com.facebook.testing.screenshot.internal.TestNameDetector
|
||||
import com.nextcloud.android.common.ui.theme.MaterialSchemes
|
||||
import com.nextcloud.client.account.User
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker
|
||||
import com.nextcloud.client.network.ConnectivityManagerFactory
|
||||
import com.nextcloud.client.network.ConnectivityService
|
||||
import com.nextcloud.client.preferences.AppPreferencesImpl
|
||||
import com.nextcloud.client.preferences.DarkMode
|
||||
import com.nextcloud.common.NextcloudClient
|
||||
import com.nextcloud.test.GrantStoragePermissionRule
|
||||
import com.nextcloud.utils.PowerManagementFactory
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProvider
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProviderImpl
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager
|
||||
import com.owncloud.android.db.OCUpload
|
||||
import com.owncloud.android.files.services.NameCollisionPolicy
|
||||
import com.owncloud.android.lib.common.OwnCloudClient
|
||||
import com.owncloud.android.lib.common.OwnCloudClientFactory
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_BASE_URL
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID
|
||||
import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation
|
||||
import com.owncloud.android.lib.resources.status.CapabilityBooleanType
|
||||
import com.owncloud.android.lib.resources.status.GetCapabilitiesRemoteOperation
|
||||
import com.owncloud.android.lib.resources.status.OCCapability
|
||||
import com.owncloud.android.lib.resources.status.OwnCloudVersion
|
||||
import com.owncloud.android.operations.CreateFolderOperation
|
||||
import com.owncloud.android.operations.UploadFileOperation
|
||||
import com.owncloud.android.utils.FileStorageUtils
|
||||
import org.apache.commons.io.FileUtils
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Before
|
||||
import org.junit.BeforeClass
|
||||
import org.junit.Rule
|
||||
import org.junit.rules.TestRule
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.util.Locale
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
abstract class AbstractIT {
|
||||
@get:Rule
|
||||
val storagePermissionRule: TestRule = GrantStoragePermissionRule.grant()
|
||||
|
||||
protected val connectivityServiceMock: ConnectivityService = ConnectivityManagerFactory.mock
|
||||
|
||||
private var currentActivity: Activity? = null
|
||||
|
||||
protected val storageManager = FileDataStorageManager(user, targetContext.contentResolver)
|
||||
|
||||
protected val arbitraryDataProvider: ArbitraryDataProvider = ArbitraryDataProviderImpl(targetContext)
|
||||
|
||||
protected val materialSchemesForCurrentUser: MaterialSchemes
|
||||
get() = MaterialSchemes.fromColor(R.color.primary)
|
||||
|
||||
@Before
|
||||
fun enableAccessibilityChecks() {
|
||||
AccessibilityChecks.enable().setRunChecksFromRootView(true)
|
||||
}
|
||||
|
||||
@After
|
||||
open fun after() {
|
||||
storageManager.removeLocalFiles(user, storageManager)
|
||||
storageManager.deleteAllFiles()
|
||||
}
|
||||
|
||||
@Throws(AccountUtils.AccountNotFoundException::class)
|
||||
protected fun testOnlyOnServer(version: OwnCloudVersion) {
|
||||
assumeTrue(getCapability().version.isNewerOrEqual(version))
|
||||
}
|
||||
|
||||
@Throws(AccountUtils.AccountNotFoundException::class)
|
||||
protected fun getCapability(): OCCapability {
|
||||
val client = OwnCloudClientFactory.createNextcloudClient(user, targetContext)
|
||||
return GetCapabilitiesRemoteOperation().execute(client).resultData
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
protected fun getFile(filename: String): File = instrumentation.context.assets.open(filename).use { asset ->
|
||||
File.createTempFile("file", "file").also { FileUtils.copyInputStreamToFile(asset, it) }
|
||||
}
|
||||
|
||||
protected fun waitForIdleSync() {
|
||||
instrumentation.waitForIdleSync()
|
||||
}
|
||||
|
||||
fun onIdleSync(recipient: Runnable) {
|
||||
instrumentation.waitForIdle(recipient)
|
||||
}
|
||||
|
||||
protected fun openDrawer(activityRule: IntentsTestRule<*>) {
|
||||
val sut = activityRule.launchActivity(null)
|
||||
shortSleep()
|
||||
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open())
|
||||
waitForIdleSync()
|
||||
screenshot(sut)
|
||||
}
|
||||
|
||||
protected fun getCurrentActivity(): Activity? {
|
||||
instrumentation.runOnMainSync {
|
||||
ActivityLifecycleMonitorRegistry.getInstance()
|
||||
.getActivitiesInStage(Stage.RESUMED)
|
||||
.firstOrNull()
|
||||
?.let { currentActivity = it }
|
||||
}
|
||||
return currentActivity
|
||||
}
|
||||
|
||||
protected fun longSleep() = sleepIgnoringInterrupt(LONG_SLEEP_MILLIS)
|
||||
|
||||
fun createFolder(remotePath: String) {
|
||||
if (ExistenceCheckRemoteOperation(remotePath, false).execute(client).isSuccess) return
|
||||
|
||||
val result = CreateFolderOperation(remotePath, user, targetContext, storageManager).execute(client)
|
||||
assertTrue(result.isSuccess)
|
||||
}
|
||||
|
||||
fun uploadFile(file: File, remotePath: String) {
|
||||
uploadOCUpload(OCUpload(file.absolutePath, remotePath, account.name))
|
||||
}
|
||||
|
||||
open fun uploadOCUpload(ocUpload: OCUpload) {
|
||||
executeUpload(ocUpload, NameCollisionPolicy.DEFAULT, FileUploadWorker.LOCAL_BEHAVIOUR_COPY)
|
||||
}
|
||||
|
||||
protected fun executeUpload(ocUpload: OCUpload, nameCollisionPolicy: NameCollisionPolicy, localBehaviour: Int) {
|
||||
val uploadsStorageManager = UploadsStorageManager(
|
||||
UserAccountManagerImpl.fromContext(targetContext),
|
||||
targetContext.contentResolver
|
||||
)
|
||||
|
||||
val existingFile: OCFile? = null
|
||||
val onWifiOnly = false
|
||||
val whileChargingOnly = false
|
||||
|
||||
val operation = UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
PowerManagementFactory.mock,
|
||||
user,
|
||||
existingFile,
|
||||
ocUpload,
|
||||
nameCollisionPolicy,
|
||||
localBehaviour,
|
||||
targetContext,
|
||||
onWifiOnly,
|
||||
whileChargingOnly,
|
||||
storageManager
|
||||
).apply {
|
||||
addRenameUploadListener { }
|
||||
setRemoteFolderToBeCreated()
|
||||
}
|
||||
|
||||
val result = operation.execute(client)
|
||||
assertTrue(result.logMessage, result.isSuccess)
|
||||
}
|
||||
|
||||
protected fun enableRTL() = applyLocale(Locale.forLanguageTag("ar"))
|
||||
|
||||
protected fun resetLocale() = applyLocale(Locale.forLanguageTag("en"))
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun applyLocale(locale: Locale) {
|
||||
val resources = instrumentation.targetContext.resources
|
||||
val config = resources.configuration.apply { setLocale(locale) }
|
||||
resources.updateConfiguration(config, null)
|
||||
}
|
||||
|
||||
fun screenshotViaName(activity: Activity?, name: String) =
|
||||
recordScreenshot { Screenshot.snapActivity(activity).setName(name) }
|
||||
|
||||
protected fun screenshotViaName(view: View?, name: String) = recordScreenshot {
|
||||
Screenshot.snap(view).setName(name)
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
protected fun screenshot(view: View?, prefix: String = "") =
|
||||
recordScreenshot { Screenshot.snap(view).setName(createName(prefix)) }
|
||||
|
||||
protected fun screenshot(sut: Activity?) = recordScreenshot { Screenshot.snapActivity(sut).setName(createName()) }
|
||||
|
||||
protected fun screenshot(dialogFragment: DialogFragment, prefix: String) =
|
||||
screenshot(requireNotNull(dialogFragment.requireDialog().window).decorView, prefix)
|
||||
|
||||
private inline fun recordScreenshot(snap: () -> RecordBuilder) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) return
|
||||
snap().record()
|
||||
}
|
||||
|
||||
fun createName(name: String, prefix: String): String {
|
||||
val suffixes = listOf(prefix, darkMode, color).filter { it.isNotEmpty() }
|
||||
return (listOf(name) + suffixes).joinToString("_")
|
||||
}
|
||||
|
||||
private fun createName(prefix: String = ""): String =
|
||||
createName("${TestNameDetector.getTestClass()}_${TestNameDetector.getTestName()}", prefix)
|
||||
|
||||
companion object {
|
||||
private const val TEST_ACCOUNT_NAME = "test@https://nextcloud.localhost"
|
||||
private const val TEST_ACCOUNT_PASSWORD = "password"
|
||||
private const val DUMMY_FILE_LINE = "123123123123123123123123123\n"
|
||||
private const val SHORT_SLEEP_MILLIS = 2_000L
|
||||
private const val LONG_SLEEP_MILLIS = 20_000L
|
||||
private const val DARK = "dark"
|
||||
private const val LIGHT = "light"
|
||||
private const val DEFAULT_COLOR = "blue"
|
||||
|
||||
private val DUMMY_FILE_LINE_COUNTS = linkedMapOf(
|
||||
"empty.txt" to 0,
|
||||
"nonEmpty.txt" to 100,
|
||||
"chunkedFile.txt" to 500_000
|
||||
)
|
||||
|
||||
private val SERVER_COLORS = mapOf(
|
||||
"red" to "#7c0000",
|
||||
"green" to "#00ff00",
|
||||
"white" to "#ffffff",
|
||||
"black" to "#000000",
|
||||
"lightgreen" to "#aaff00"
|
||||
)
|
||||
|
||||
private val CLIENT_SETUP_FAILURES = listOf(
|
||||
OperationCanceledException::class.java,
|
||||
IOException::class.java,
|
||||
AccountUtils.AccountNotFoundException::class.java,
|
||||
AuthenticatorException::class.java
|
||||
)
|
||||
|
||||
private val instrumentation: Instrumentation
|
||||
get() = InstrumentationRegistry.getInstrumentation()
|
||||
|
||||
@JvmStatic
|
||||
protected lateinit var client: OwnCloudClient
|
||||
|
||||
@JvmStatic
|
||||
protected lateinit var nextcloudClient: NextcloudClient
|
||||
|
||||
@JvmStatic
|
||||
protected lateinit var account: Account
|
||||
|
||||
@JvmStatic
|
||||
protected lateinit var user: User
|
||||
|
||||
@JvmStatic
|
||||
protected lateinit var targetContext: Context
|
||||
|
||||
private var darkMode = ""
|
||||
private var color = ""
|
||||
|
||||
@BeforeClass
|
||||
@JvmStatic
|
||||
fun beforeAll() {
|
||||
targetContext = instrumentation.targetContext
|
||||
removeAccountsOfType(MainApp.getAccountType(targetContext))
|
||||
|
||||
rethrowClientSetupFailure {
|
||||
account = createAccount(TEST_ACCOUNT_NAME)
|
||||
user = getUser(account)
|
||||
client = OwnCloudClientFactory.createOwnCloudClient(account, targetContext)
|
||||
nextcloudClient = OwnCloudClientFactory.createNextcloudClient(user, targetContext)
|
||||
}
|
||||
|
||||
val arguments = InstrumentationRegistry.getArguments()
|
||||
arguments.getString("COLOR")?.takeIf { it.isNotEmpty() }?.let(::applyServerColor)
|
||||
arguments.getString("DARKMODE")?.let(::applyDarkMode)
|
||||
|
||||
if (LIGHT.equals(darkMode, ignoreCase = true) && DEFAULT_COLOR.equals(color, ignoreCase = true)) {
|
||||
darkMode = ""
|
||||
color = ""
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyServerColor(colorArgument: String) {
|
||||
color = colorArgument
|
||||
val fileDataStorageManager = FileDataStorageManager(user, targetContext.contentResolver)
|
||||
val capability = fileDataStorageManager.getCapability(account.name).apply {
|
||||
groupfolders = CapabilityBooleanType.TRUE
|
||||
SERVER_COLORS[colorArgument]?.let { serverColor = it }
|
||||
}
|
||||
fileDataStorageManager.saveCapabilities(capability)
|
||||
}
|
||||
|
||||
private fun applyDarkMode(darkModeArgument: String) {
|
||||
if (!DARK.equals(darkModeArgument, ignoreCase = true)) {
|
||||
darkMode = LIGHT
|
||||
return
|
||||
}
|
||||
|
||||
darkMode = DARK
|
||||
AppPreferencesImpl.fromContext(targetContext).setDarkThemeMode(DarkMode.DARK)
|
||||
MainApp.setAppTheme(DarkMode.DARK)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
protected fun <T> rethrowClientSetupFailure(setup: () -> T): T = try {
|
||||
setup()
|
||||
} catch (e: Exception) {
|
||||
if (CLIENT_SETUP_FAILURES.none { it.isInstance(e) }) throw e
|
||||
throw RuntimeException("Error setting up clients", e)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
protected fun removeAccountsOfType(accountType: String) = with(AccountManager.get(targetContext)) {
|
||||
accounts
|
||||
.filter { it.type.equals(accountType, ignoreCase = true) }
|
||||
.forEach(this::removeAccountExplicitly)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
@Throws(IOException::class)
|
||||
protected fun createDummyFiles(): List<File> {
|
||||
val tempPath = File(FileStorageUtils.getTemporalPath(account.name))
|
||||
if (!tempPath.exists()) assertTrue(tempPath.mkdirs())
|
||||
assertTrue(tempPath.exists())
|
||||
|
||||
return DUMMY_FILE_LINE_COUNTS.map { (name, lineCount) -> createFile(name, lineCount) }
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
@Throws(IOException::class)
|
||||
protected fun getDummyFile(name: String): File {
|
||||
val file = File(FileStorageUtils.getInternalTemporalPath(account.name, targetContext), name)
|
||||
return when {
|
||||
file.exists() -> file
|
||||
name.endsWith("/") -> file.apply { mkdirs() }
|
||||
else -> createFile(name, DUMMY_FILE_LINE_COUNTS.getOrElse(name) { 0 })
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
@Throws(IOException::class)
|
||||
fun createFile(name: String, iteration: Int): File {
|
||||
val file = File(FileStorageUtils.getTemporalPath(account.name), name)
|
||||
val parent = requireNotNull(file.parentFile)
|
||||
if (!parent.exists()) assertTrue(parent.mkdirs())
|
||||
|
||||
file.bufferedWriter().use { writer -> repeat(iteration) { writer.write(DUMMY_FILE_LINE) } }
|
||||
return file
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
protected fun shortSleep() = sleepIgnoringInterrupt(SHORT_SLEEP_MILLIS)
|
||||
|
||||
@JvmStatic
|
||||
protected fun sleepIgnoringInterrupt(millis: Long) {
|
||||
try {
|
||||
Thread.sleep(millis)
|
||||
} catch (e: InterruptedException) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun getUserId(user: User): String = requireNotNull(
|
||||
AccountManager.get(targetContext).getUserData(user.toPlatformAccount(), KEY_USER_ID)
|
||||
) { "No user id stored for ${user.accountName}" }
|
||||
|
||||
@JvmStatic
|
||||
protected fun getUser(account: Account): User =
|
||||
UserAccountManagerImpl.fromContext(targetContext).getUser(account.name).orElseThrow { IllegalAccessError() }
|
||||
|
||||
@JvmStatic
|
||||
protected fun createAccount(name: String): Account {
|
||||
val platformAccount = Account(name, MainApp.getAccountType(targetContext))
|
||||
|
||||
AccountManager.get(targetContext).run {
|
||||
addAccountExplicitly(platformAccount, TEST_ACCOUNT_PASSWORD, null)
|
||||
setUserData(platformAccount, KEY_OC_BASE_URL, name.substringAfterLast('@'))
|
||||
setUserData(platformAccount, KEY_USER_ID, name.substringBeforeLast('@'))
|
||||
}
|
||||
|
||||
return getRegisteredAccount(name)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
protected fun getRegisteredAccount(name: String): Account {
|
||||
val account = UserAccountManagerImpl.fromContext(targetContext).getAccountByName(name)
|
||||
if (account.type == targetContext.getString(R.string.anonymous_account_type)) {
|
||||
throw RuntimeException("Could not get account with name $name")
|
||||
}
|
||||
return account
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
protected fun removeAccount(account: Account): Boolean =
|
||||
AccountManager.get(targetContext).removeAccountExplicitly(account)
|
||||
}
|
||||
}
|
||||
@@ -1,260 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2020 Tobias Kaminsky <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.owncloud.android;
|
||||
|
||||
import android.accounts.Account;
|
||||
import android.accounts.AccountManager;
|
||||
import android.accounts.AuthenticatorException;
|
||||
import android.accounts.OperationCanceledException;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
|
||||
import com.nextcloud.client.account.User;
|
||||
import com.nextcloud.client.account.UserAccountManager;
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl;
|
||||
import com.nextcloud.utils.PowerManagementFactory;
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker;
|
||||
import com.owncloud.android.datamodel.OCFile;
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager;
|
||||
import com.owncloud.android.db.OCUpload;
|
||||
import com.owncloud.android.files.services.NameCollisionPolicy;
|
||||
import com.owncloud.android.lib.common.OwnCloudClient;
|
||||
import com.owncloud.android.lib.common.OwnCloudClientFactory;
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils;
|
||||
import com.owncloud.android.lib.resources.e2ee.ToggleEncryptionRemoteOperation;
|
||||
import com.owncloud.android.lib.resources.files.ReadFolderRemoteOperation;
|
||||
import com.owncloud.android.lib.resources.files.RemoveFileRemoteOperation;
|
||||
import com.owncloud.android.lib.resources.files.model.RemoteFile;
|
||||
import com.owncloud.android.operations.RefreshFolderOperation;
|
||||
import com.owncloud.android.operations.UploadFileOperation;
|
||||
import com.owncloud.android.utils.MimeType;
|
||||
|
||||
import org.apache.commons.httpclient.HttpStatus;
|
||||
import org.apache.commons.httpclient.methods.GetMethod;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.BeforeClass;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/// Common base for all integration tests requiring a server connection.
|
||||
/// ATTENTION: Deletes ALL files of the test user on the server after each test run.
|
||||
/// So you MUST use a dedicated test user.
|
||||
/// Uses server, user and password given as `testInstrumentationRunnerArgument`
|
||||
/// - TEST_SERVER_URL
|
||||
/// - TEST_SERVER_USERNAME
|
||||
/// - TEST_SERVER_PASSWORD
|
||||
/// These are supplied via build.gradle, which takes them from gradle.properties.
|
||||
/// So look in the latter file to set to your own server & test user.
|
||||
public abstract class AbstractOnServerIT extends AbstractIT {
|
||||
@BeforeClass
|
||||
public static void beforeAll() {
|
||||
try {
|
||||
// clean up
|
||||
targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
|
||||
AccountManager platformAccountManager = AccountManager.get(targetContext);
|
||||
|
||||
for (Account account : platformAccountManager.getAccounts()) {
|
||||
if (account.type.equalsIgnoreCase("nextcloud")) {
|
||||
platformAccountManager.removeAccountExplicitly(account);
|
||||
}
|
||||
}
|
||||
|
||||
Bundle arguments = androidx.test.platform.app.InstrumentationRegistry.getArguments();
|
||||
|
||||
Uri baseUrl = Uri.parse(arguments.getString("TEST_SERVER_URL"));
|
||||
String loginName = arguments.getString("TEST_SERVER_USERNAME");
|
||||
String password = arguments.getString("TEST_SERVER_PASSWORD");
|
||||
|
||||
Account temp = new Account(loginName + "@" + baseUrl, MainApp.getAccountType(targetContext));
|
||||
UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
|
||||
if (!accountManager.exists(temp)) {
|
||||
platformAccountManager.addAccountExplicitly(temp, password, null);
|
||||
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION,
|
||||
Integer.toString(UserAccountManager.ACCOUNT_VERSION));
|
||||
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_VERSION, "14.0.0.0");
|
||||
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_BASE_URL, baseUrl.toString());
|
||||
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_USER_ID, loginName); // same as userId
|
||||
}
|
||||
|
||||
final UserAccountManager userAccountManager = UserAccountManagerImpl.fromContext(targetContext);
|
||||
account = userAccountManager.getAccountByName(loginName + "@" + baseUrl);
|
||||
|
||||
if (Objects.equals(account.type, targetContext.getString(R.string.anonymous_account_type))) {
|
||||
throw new RuntimeException("Could not get account with name " + loginName + "@" + baseUrl);
|
||||
}
|
||||
|
||||
Optional<User> optionalUser = userAccountManager.getUser(account.name);
|
||||
user = optionalUser.orElseThrow(IllegalAccessError::new);
|
||||
|
||||
client = OwnCloudClientFactory.createOwnCloudClient(account, targetContext);
|
||||
nextcloudClient = OwnCloudClientFactory.createNextcloudClient(user, targetContext);
|
||||
|
||||
createDummyFiles();
|
||||
|
||||
waitForServer(client, baseUrl);
|
||||
|
||||
// deleteAllFilesOnServer(); // makes sure that no file/folder is in root
|
||||
|
||||
} catch (OperationCanceledException |
|
||||
IOException |
|
||||
AccountUtils.AccountNotFoundException |
|
||||
AuthenticatorException e) {
|
||||
throw new RuntimeException("Error setting up clients", e);
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
public void after() {
|
||||
deleteAllFilesOnServer();
|
||||
|
||||
super.after();
|
||||
}
|
||||
|
||||
private static boolean isFolder(RemoteFile file) {
|
||||
// TODO: should probably move to RemoteFile class
|
||||
return MimeType.DIRECTORY.equals(file.getMimeType()) || MimeType.WEBDAV_FOLDER.equals(file.getMimeType());
|
||||
}
|
||||
|
||||
public static void deleteAllFilesOnServer() {
|
||||
var result = new ReadFolderRemoteOperation("/").execute(client);
|
||||
assertTrue(result.getLogMessage(targetContext), result.isSuccess());
|
||||
|
||||
for (Object object : result.getData()) {
|
||||
RemoteFile remoteFile = (RemoteFile) object;
|
||||
|
||||
if (!Objects.equals(remoteFile.getRemotePath(), "/")) {
|
||||
if (remoteFile.isEncrypted()) {
|
||||
ToggleEncryptionRemoteOperation operation = new ToggleEncryptionRemoteOperation(remoteFile.getLocalId(),
|
||||
remoteFile.getRemotePath(),
|
||||
false);
|
||||
|
||||
boolean operationResult = operation
|
||||
.execute(client)
|
||||
.isSuccess();
|
||||
|
||||
if (!operationResult && isFolder(remoteFile)) {
|
||||
// Deleting encrypted folder is not possible due to bug
|
||||
// https://github.com/nextcloud/end_to_end_encryption/issues/421
|
||||
// Toggling encryption also fails, when the folder is not empty. So we ignore this folder
|
||||
continue;
|
||||
}
|
||||
|
||||
assertTrue(operationResult);
|
||||
}
|
||||
|
||||
if (remoteFile.getPermissions().contains("M")) {
|
||||
// skip Teamfolders
|
||||
continue;
|
||||
}
|
||||
|
||||
boolean removeResult = false;
|
||||
for (int i = 0; i < 5; i++) {
|
||||
removeResult = new RemoveFileRemoteOperation(remoteFile.getRemotePath())
|
||||
.execute(client)
|
||||
.isSuccess();
|
||||
|
||||
if (removeResult) {
|
||||
break;
|
||||
}
|
||||
|
||||
shortSleep();
|
||||
}
|
||||
|
||||
assertTrue("Remove of " + remoteFile.getRemotePath() + " failed", removeResult);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void waitForServer(OwnCloudClient client, Uri baseUrl) {
|
||||
GetMethod get = new GetMethod(baseUrl + "/status.php");
|
||||
|
||||
try {
|
||||
int i = 0;
|
||||
while (client.executeMethod(get) != HttpStatus.SC_OK && i < 3) {
|
||||
System.out.println("wait…");
|
||||
Thread.sleep(60 * 1000);
|
||||
i++;
|
||||
}
|
||||
|
||||
if (i == 3) {
|
||||
Assert.fail("Server not ready!");
|
||||
}
|
||||
|
||||
} catch (IOException | InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void uploadOCUpload(OCUpload ocUpload) {
|
||||
uploadOCUpload(ocUpload, FileUploadWorker.LOCAL_BEHAVIOUR_COPY);
|
||||
}
|
||||
|
||||
public void uploadOCUpload(OCUpload ocUpload, int localBehaviour) {
|
||||
final var powerManagementServiceMock = PowerManagementFactory.getMock();
|
||||
UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
|
||||
UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(accountManager,
|
||||
targetContext.getContentResolver());
|
||||
|
||||
UploadFileOperation newUpload = new UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
user,
|
||||
null,
|
||||
ocUpload,
|
||||
NameCollisionPolicy.OVERWRITE,
|
||||
localBehaviour,
|
||||
targetContext,
|
||||
false,
|
||||
false,
|
||||
getStorageManager()
|
||||
);
|
||||
newUpload.addRenameUploadListener(() -> {
|
||||
// dummy
|
||||
});
|
||||
|
||||
newUpload.setRemoteFolderToBeCreated();
|
||||
|
||||
var result = newUpload.execute(client);
|
||||
assertTrue(result.getLogMessage(), result.isSuccess());
|
||||
|
||||
OCFile parentFolder = getStorageManager()
|
||||
.getFileByEncryptedRemotePath(new File(ocUpload.getRemotePath()).getParent() + "/");
|
||||
String uploadedFileName = new File(ocUpload.getRemotePath()).getName();
|
||||
OCFile uploadedFile = getStorageManager().
|
||||
getFileByDecryptedRemotePath(parentFolder.getDecryptedRemotePath() + uploadedFileName);
|
||||
|
||||
assertNotNull(uploadedFile);
|
||||
assertNotNull(uploadedFile.getRemoteId());
|
||||
assertNotNull(uploadedFile.getPermissions());
|
||||
|
||||
if (localBehaviour == FileUploadWorker.LOCAL_BEHAVIOUR_COPY ||
|
||||
localBehaviour == FileUploadWorker.LOCAL_BEHAVIOUR_MOVE) {
|
||||
assertTrue(new File(uploadedFile.getStoragePath()).exists());
|
||||
}
|
||||
}
|
||||
|
||||
protected void refreshFolder(String path) {
|
||||
assertTrue(new RefreshFolderOperation(getStorageManager().getFileByEncryptedRemotePath(path),
|
||||
System.currentTimeMillis(),
|
||||
false,
|
||||
false,
|
||||
getStorageManager(),
|
||||
user,
|
||||
targetContext
|
||||
).execute(client).isSuccess());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android
|
||||
|
||||
import android.accounts.Account
|
||||
import android.accounts.AccountManager
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.nextcloud.client.account.UserAccountManager
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker
|
||||
import com.owncloud.android.db.OCUpload
|
||||
import com.owncloud.android.files.services.NameCollisionPolicy
|
||||
import com.owncloud.android.lib.common.OwnCloudClient
|
||||
import com.owncloud.android.lib.common.OwnCloudClientFactory
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_BASE_URL
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_VERSION
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID
|
||||
import com.owncloud.android.lib.resources.e2ee.ToggleEncryptionRemoteOperation
|
||||
import com.owncloud.android.lib.resources.files.ReadFolderRemoteOperation
|
||||
import com.owncloud.android.lib.resources.files.RemoveFileRemoteOperation
|
||||
import com.owncloud.android.lib.resources.files.model.RemoteFile
|
||||
import com.owncloud.android.operations.RefreshFolderOperation
|
||||
import com.owncloud.android.utils.FileStorageUtils
|
||||
import com.owncloud.android.utils.MimeType
|
||||
import org.apache.commons.httpclient.HttpStatus
|
||||
import org.apache.commons.httpclient.methods.GetMethod
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.BeforeClass
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
abstract class AbstractOnServerIT : AbstractIT() {
|
||||
@After
|
||||
override fun after() {
|
||||
deleteAllFilesOnServer()
|
||||
super.after()
|
||||
}
|
||||
|
||||
override fun uploadOCUpload(ocUpload: OCUpload) {
|
||||
uploadOCUpload(ocUpload, FileUploadWorker.LOCAL_BEHAVIOUR_COPY)
|
||||
}
|
||||
|
||||
fun uploadOCUpload(ocUpload: OCUpload, localBehaviour: Int) {
|
||||
executeUpload(ocUpload, NameCollisionPolicy.OVERWRITE, localBehaviour)
|
||||
|
||||
val remotePath = ocUpload.remotePath
|
||||
val parentPath = FileStorageUtils.getParentPath(remotePath)
|
||||
?: throw AssertionError("$remotePath has no parent folder")
|
||||
val parentFolder = storageManager.getFileByEncryptedRemotePath(parentPath)
|
||||
?: throw AssertionError("Parent folder $parentPath not found")
|
||||
val uploadedFile = storageManager.getFileByDecryptedRemotePath(
|
||||
parentFolder.decryptedRemotePath + File(remotePath).name
|
||||
) ?: throw AssertionError("Uploaded file $remotePath not found")
|
||||
|
||||
assertNotNull(uploadedFile.remoteId)
|
||||
assertNotNull(uploadedFile.permissions)
|
||||
|
||||
if (localBehaviour in LOCAL_COPY_BEHAVIOURS) {
|
||||
assertTrue(File(uploadedFile.storagePath).exists())
|
||||
}
|
||||
}
|
||||
|
||||
protected fun refreshFolder(path: String) {
|
||||
val operation = RefreshFolderOperation(
|
||||
storageManager.getFileByEncryptedRemotePath(path),
|
||||
System.currentTimeMillis(),
|
||||
false,
|
||||
false,
|
||||
storageManager,
|
||||
user,
|
||||
targetContext
|
||||
)
|
||||
assertTrue(operation.execute(client).isSuccess)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val SERVER_ACCOUNT_TYPE = "nextcloud"
|
||||
private const val SERVER_VERSION = "14.0.0.0"
|
||||
private const val ROOT_PATH = "/"
|
||||
private const val TEAM_FOLDER_PERMISSION = "M"
|
||||
private const val REMOVE_ATTEMPTS = 5
|
||||
private const val SERVER_READY_RETRIES = 3
|
||||
private const val SERVER_READY_RETRY_DELAY_MILLIS = 60_000L
|
||||
|
||||
private val FOLDER_MIME_TYPES = setOf(MimeType.DIRECTORY, MimeType.WEBDAV_FOLDER)
|
||||
private val LOCAL_COPY_BEHAVIOURS = setOf(
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_MOVE
|
||||
)
|
||||
|
||||
@BeforeClass
|
||||
@JvmStatic
|
||||
fun beforeAll() {
|
||||
rethrowClientSetupFailure {
|
||||
targetContext = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
removeAccountsOfType(SERVER_ACCOUNT_TYPE)
|
||||
|
||||
val arguments = InstrumentationRegistry.getArguments()
|
||||
val baseUrl = Uri.parse(arguments.requireString("TEST_SERVER_URL"))
|
||||
val loginName = arguments.requireString("TEST_SERVER_USERNAME")
|
||||
val password = arguments.requireString("TEST_SERVER_PASSWORD")
|
||||
val accountName = "$loginName@$baseUrl"
|
||||
|
||||
addServerAccountIfMissing(accountName, loginName, password, baseUrl)
|
||||
|
||||
account = getRegisteredAccount(accountName)
|
||||
user = getUser(account)
|
||||
client = OwnCloudClientFactory.createOwnCloudClient(account, targetContext)
|
||||
nextcloudClient = OwnCloudClientFactory.createNextcloudClient(user, targetContext)
|
||||
|
||||
createDummyFiles()
|
||||
|
||||
waitForServer(client, baseUrl)
|
||||
}
|
||||
}
|
||||
|
||||
private fun addServerAccountIfMissing(accountName: String, loginName: String, password: String, baseUrl: Uri) {
|
||||
val platformAccount = Account(accountName, MainApp.getAccountType(targetContext))
|
||||
if (UserAccountManagerImpl.fromContext(targetContext).exists(platformAccount)) return
|
||||
|
||||
AccountManager.get(targetContext).run {
|
||||
addAccountExplicitly(platformAccount, password, null)
|
||||
setUserData(platformAccount, KEY_OC_ACCOUNT_VERSION, UserAccountManager.ACCOUNT_VERSION.toString())
|
||||
setUserData(platformAccount, KEY_OC_VERSION, SERVER_VERSION)
|
||||
setUserData(platformAccount, KEY_OC_BASE_URL, baseUrl.toString())
|
||||
setUserData(platformAccount, KEY_USER_ID, loginName)
|
||||
}
|
||||
}
|
||||
|
||||
private fun isFolder(file: RemoteFile): Boolean = file.mimeType in FOLDER_MIME_TYPES
|
||||
|
||||
private fun isTeamFolder(file: RemoteFile): Boolean = file.permissions?.contains(TEAM_FOLDER_PERMISSION) == true
|
||||
|
||||
private fun deleteAllFilesOnServer() {
|
||||
val result = ReadFolderRemoteOperation(ROOT_PATH).execute(client)
|
||||
assertTrue(result.getLogMessage(targetContext), result.isSuccess)
|
||||
|
||||
result.data
|
||||
.filterIsInstance<RemoteFile>()
|
||||
.filterNot { it.remotePath == ROOT_PATH }
|
||||
.forEach(::deleteRemoteFile)
|
||||
}
|
||||
|
||||
private fun deleteRemoteFile(remoteFile: RemoteFile) {
|
||||
if (remoteFile.isEncrypted) {
|
||||
val isEncryptionDisabled = disableEncryption(remoteFile)
|
||||
|
||||
if (!isEncryptionDisabled && isFolder(remoteFile)) return
|
||||
|
||||
assertTrue(isEncryptionDisabled)
|
||||
}
|
||||
|
||||
if (isTeamFolder(remoteFile)) return
|
||||
|
||||
assertTrue("Remove of ${remoteFile.remotePath} failed", removeWithRetry(remoteFile))
|
||||
}
|
||||
|
||||
private fun disableEncryption(remoteFile: RemoteFile): Boolean =
|
||||
ToggleEncryptionRemoteOperation(remoteFile.localId, remoteFile.remotePath, false)
|
||||
.execute(client)
|
||||
.isSuccess
|
||||
|
||||
private fun removeWithRetry(remoteFile: RemoteFile): Boolean {
|
||||
repeat(REMOVE_ATTEMPTS) {
|
||||
if (RemoveFileRemoteOperation(remoteFile.remotePath).execute(client).isSuccess) return true
|
||||
shortSleep()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun waitForServer(client: OwnCloudClient, baseUrl: Uri) {
|
||||
val statusRequest = GetMethod("$baseUrl/status.php")
|
||||
|
||||
repeat(SERVER_READY_RETRIES) {
|
||||
if (isServerReady(client, statusRequest)) return
|
||||
println("wait…")
|
||||
sleepIgnoringInterrupt(SERVER_READY_RETRY_DELAY_MILLIS)
|
||||
}
|
||||
|
||||
assertTrue("Server not ready!", isServerReady(client, statusRequest))
|
||||
}
|
||||
|
||||
private fun isServerReady(client: OwnCloudClient, statusRequest: GetMethod): Boolean = try {
|
||||
client.executeMethod(statusRequest) == HttpStatus.SC_OK
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
false
|
||||
}
|
||||
|
||||
private fun Bundle.requireString(key: String): String =
|
||||
requireNotNull(getString(key)) { "Missing instrumentation argument $key" }
|
||||
}
|
||||
}
|
||||
@@ -70,8 +70,8 @@ class DownloadIT : AbstractOnServerIT() {
|
||||
|
||||
refreshFolder(FOLDER)
|
||||
|
||||
var file1 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt")
|
||||
var file2 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty2.txt")
|
||||
var file1 = storageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt")
|
||||
var file2 = storageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty2.txt")
|
||||
|
||||
if (file1 == null) {
|
||||
fail("file 1 cannot be null")
|
||||
@@ -88,8 +88,8 @@ class DownloadIT : AbstractOnServerIT() {
|
||||
Assert.assertTrue(operation2Result.isSuccess)
|
||||
|
||||
refreshFolder(FOLDER)
|
||||
file1 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt")
|
||||
file2 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty2.txt")
|
||||
file1 = storageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt")
|
||||
file2 = storageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty2.txt")
|
||||
|
||||
verifyDownload(file1, file2)
|
||||
}
|
||||
|
||||
+2
-1
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
package com.owncloud.android.datamodel
|
||||
|
||||
import com.nextcloud.utils.extensions.saveFolder
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
@@ -41,7 +42,7 @@ class FileDataStorageManagerContentResolverIT : FileDataStorageManagerIT() {
|
||||
|
||||
val storedFile = sut.getFileByDecryptedRemotePath("/folderA/file$it")
|
||||
Assert.assertNotNull(storedFile)
|
||||
storedFile
|
||||
requireNotNull(storedFile)
|
||||
}
|
||||
|
||||
// save files in folder
|
||||
|
||||
+218
-59
@@ -7,30 +7,45 @@
|
||||
|
||||
package com.owncloud.android.providers
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.content.ContentUris
|
||||
import android.content.ContentValues
|
||||
import android.content.pm.ProviderInfo
|
||||
import android.net.Uri
|
||||
import androidx.room.Room
|
||||
import androidx.sqlite.db.SimpleSQLiteQuery
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.nextcloud.client.database.NextcloudDatabase
|
||||
import com.nextcloud.client.database.typeConverter.OfflineOperationTypeConverter
|
||||
import com.nextcloud.utils.extensions.toFileEntity
|
||||
import com.nextcloud.utils.extensions.toFolderMetadataUpdate
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.db.ProviderMeta
|
||||
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
|
||||
import com.owncloud.android.utils.MimeType
|
||||
import io.mockk.Runs
|
||||
import io.mockk.every
|
||||
import io.mockk.just
|
||||
import io.mockk.mockk
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
@Suppress("MagicNumber")
|
||||
@Suppress("MagicNumber", "TooManyFunctions")
|
||||
class FileContentProviderTests {
|
||||
|
||||
companion object {
|
||||
private const val OWNER = "[email protected]"
|
||||
private const val OTHER_OWNER = "[email protected]"
|
||||
private const val NO_PARENT = 0L
|
||||
}
|
||||
|
||||
private lateinit var provider: FileContentProvider
|
||||
private lateinit var db: SupportSQLiteDatabase
|
||||
private var inMemoryDatabase: NextcloudDatabase? = null
|
||||
|
||||
@Before
|
||||
fun setup() {
|
||||
@@ -38,6 +53,11 @@ class FileContentProviderTests {
|
||||
db = mockk()
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
inMemoryDatabase?.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun insertNewFileShouldReturnNewId() {
|
||||
val values = ContentValues().apply {
|
||||
@@ -45,6 +65,11 @@ class FileContentProviderTests {
|
||||
put(ProviderMeta.ProviderTableMeta.FILE_ACCOUNT_OWNER, "[email protected]")
|
||||
}
|
||||
|
||||
val cursor = mockk<android.database.Cursor>()
|
||||
every { cursor.moveToFirst() } returns false
|
||||
every { cursor.close() } just Runs
|
||||
every { db.query(any<SimpleSQLiteQuery>()) } returns cursor
|
||||
|
||||
// Mock insert to return new ID
|
||||
every { db.insert(any(), any(), any()) } returns 42L
|
||||
|
||||
@@ -67,9 +92,6 @@ class FileContentProviderTests {
|
||||
put(ProviderMeta.ProviderTableMeta.FILE_ACCOUNT_OWNER, "[email protected]")
|
||||
}
|
||||
|
||||
// Simulate insert conflict
|
||||
every { db.insert(ProviderMeta.ProviderTableMeta.FILE_TABLE_NAME, any(), values) } returns -1L
|
||||
|
||||
// Simulate update returning 1 row affected
|
||||
every {
|
||||
db.update(
|
||||
@@ -100,59 +122,196 @@ class FileContentProviderTests {
|
||||
cursor.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testConcurrentUpserts() = runBlocking {
|
||||
private fun createProviderWithInMemoryDatabase(): FileContentProvider {
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
val database = Room.inMemoryDatabaseBuilder(context, NextcloudDatabase::class.java)
|
||||
.addTypeConverter(OfflineOperationTypeConverter())
|
||||
.allowMainThreadQueries()
|
||||
.build()
|
||||
inMemoryDatabase = database
|
||||
|
||||
val provider = FileContentProvider()
|
||||
provider.attachInfo(context, ProviderInfo().apply { authority = context.getString(R.string.authority) })
|
||||
FileContentProvider::class.java.getDeclaredField("mDbHelper")
|
||||
.apply { isAccessible = true }
|
||||
.set(provider, database.openHelper)
|
||||
return provider
|
||||
}
|
||||
|
||||
private fun FileContentProvider.insertFile(
|
||||
path: String,
|
||||
parentId: Long,
|
||||
owner: String = OWNER,
|
||||
isFolder: Boolean = false
|
||||
): Long {
|
||||
val values = ContentValues().apply {
|
||||
put(ProviderMeta.ProviderTableMeta.FILE_PATH, "/path/to/file.txt")
|
||||
put(ProviderMeta.ProviderTableMeta.FILE_ACCOUNT_OWNER, "[email protected]")
|
||||
put(ProviderTableMeta.FILE_PATH, path)
|
||||
put(ProviderTableMeta.FILE_ACCOUNT_OWNER, owner)
|
||||
put(ProviderTableMeta.FILE_PARENT, parentId)
|
||||
put(ProviderTableMeta.FILE_CONTENT_TYPE, if (isFolder) MimeType.DIRECTORY else "text/plain")
|
||||
}
|
||||
val uri = insert(ProviderTableMeta.CONTENT_URI_FILE, values)
|
||||
return ContentUris.parseId(requireNotNull(uri))
|
||||
}
|
||||
|
||||
private fun storedPaths(owner: String = OWNER): List<String?> =
|
||||
requireNotNull(inMemoryDatabase).fileDao().getAllFiles(owner).map { it.path }
|
||||
|
||||
@Test
|
||||
fun queryReturnsChildrenOfDirectoryWhenNoSelectionIsGiven() {
|
||||
val provider = createProviderWithInMemoryDatabase()
|
||||
val rootId = provider.insertFile("/", NO_PARENT, isFolder = true)
|
||||
provider.insertFile("/a.txt", rootId)
|
||||
provider.insertFile("/b.txt", rootId)
|
||||
|
||||
val cursor = provider.query(
|
||||
ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, rootId),
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null
|
||||
)
|
||||
|
||||
assertEquals(2, requireNotNull(cursor).use { it.count })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deletingDirectoryRemovesAllOfItsDescendants() {
|
||||
val provider = createProviderWithInMemoryDatabase()
|
||||
val rootId = provider.insertFile("/", NO_PARENT, isFolder = true)
|
||||
val folderId = provider.insertFile("/folder/", rootId, isFolder = true)
|
||||
val subFolderId = provider.insertFile("/folder/sub/", folderId, isFolder = true)
|
||||
provider.insertFile("/folder/a.txt", folderId)
|
||||
provider.insertFile("/folder/sub/b.txt", subFolderId)
|
||||
|
||||
provider.delete(ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, folderId), null, null)
|
||||
|
||||
assertEquals(listOf("/"), storedPaths())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deletingDirectoriesWithoutIdRemovesOnlyMatchingDirectoriesAndTheirDescendants() {
|
||||
val provider = createProviderWithInMemoryDatabase()
|
||||
val ownerRootId = provider.insertFile("/", NO_PARENT, isFolder = true)
|
||||
provider.insertFile("/a.txt", ownerRootId)
|
||||
val otherRootId = provider.insertFile("/", NO_PARENT, owner = OTHER_OWNER, isFolder = true)
|
||||
provider.insertFile("/b.txt", otherRootId, owner = OTHER_OWNER)
|
||||
|
||||
provider.delete(
|
||||
ProviderTableMeta.CONTENT_URI_DIR,
|
||||
"${ProviderTableMeta.FILE_ACCOUNT_OWNER} = ? AND ${ProviderTableMeta.FILE_PATH} = ?",
|
||||
arrayOf(OWNER, "/")
|
||||
)
|
||||
|
||||
assertTrue(storedPaths().isEmpty())
|
||||
assertEquals(listOf("/", "/b.txt"), storedPaths(OTHER_OWNER).sortedBy { it })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun insertingExistingPathUpdatesRowInsteadOfAddingDuplicate() {
|
||||
val provider = createProviderWithInMemoryDatabase()
|
||||
val rootId = provider.insertFile("/", NO_PARENT, isFolder = true)
|
||||
val firstId = provider.insertFile("/a.txt", rootId)
|
||||
|
||||
val secondId = provider.insertFile("/a.txt", rootId)
|
||||
|
||||
assertEquals(firstId, secondId)
|
||||
assertEquals(listOf("/", "/a.txt"), storedPaths().sortedBy { it })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fileDaoDeleteAllFilesRemovesOnlyRowsOfGivenOwner() {
|
||||
val provider = createProviderWithInMemoryDatabase()
|
||||
provider.insertFile("/", NO_PARENT, isFolder = true)
|
||||
provider.insertFile("/", NO_PARENT, owner = OTHER_OWNER, isFolder = true)
|
||||
|
||||
requireNotNull(inMemoryDatabase).fileDao().deleteAllFiles(OWNER)
|
||||
|
||||
assertTrue(storedPaths().isEmpty())
|
||||
assertEquals(listOf("/"), storedPaths(OTHER_OWNER))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fileDaoUpsertInsertsNewRowAndUpdatesExistingRowInPlace() {
|
||||
createProviderWithInMemoryDatabase()
|
||||
val fileDao = requireNotNull(inMemoryDatabase).fileDao()
|
||||
val file = OCFile("/a.txt").apply { etag = "first" }
|
||||
|
||||
val insertedId = fileDao.upsert(file.toFileEntity(OWNER))
|
||||
val updateResult = fileDao.upsert(file.apply { etag = "second" }.toFileEntity(OWNER).copy(id = insertedId))
|
||||
|
||||
assertEquals(-1L, updateResult)
|
||||
assertEquals(listOf("/a.txt"), storedPaths())
|
||||
assertEquals("second", fileDao.getFileById(insertedId)?.etag)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fileDaoDeleteFolderRemovesFolderAndAllDescendants() {
|
||||
val provider = createProviderWithInMemoryDatabase()
|
||||
val rootId = provider.insertFile("/", NO_PARENT, isFolder = true)
|
||||
val folderId = provider.insertFile("/folder/", rootId, isFolder = true)
|
||||
val subFolderId = provider.insertFile("/folder/sub/", folderId, isFolder = true)
|
||||
provider.insertFile("/folder/a.txt", folderId)
|
||||
provider.insertFile("/folder/sub/b.txt", subFolderId)
|
||||
|
||||
requireNotNull(inMemoryDatabase).fileDao().deleteFolder(folderId, OWNER, "/folder/")
|
||||
|
||||
assertEquals(listOf("/"), storedPaths())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fileDaoDeleteFolderKeepsFolderRowWhenPathDoesNotMatch() {
|
||||
val provider = createProviderWithInMemoryDatabase()
|
||||
val rootId = provider.insertFile("/", NO_PARENT, isFolder = true)
|
||||
val folderId = provider.insertFile("/folder/", rootId, isFolder = true)
|
||||
provider.insertFile("/folder/a.txt", folderId)
|
||||
|
||||
requireNotNull(inMemoryDatabase).fileDao().deleteFolder(folderId, OWNER, "/other/")
|
||||
|
||||
assertEquals(listOf("/", "/folder/"), storedPaths().sortedBy { it })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fileDaoDeleteFileRemovesOnlyRowMatchingIdOwnerAndPath() {
|
||||
val provider = createProviderWithInMemoryDatabase()
|
||||
val rootId = provider.insertFile("/", NO_PARENT, isFolder = true)
|
||||
val fileId = provider.insertFile("/a.txt", rootId)
|
||||
provider.insertFile("/b.txt", rootId)
|
||||
val fileDao = requireNotNull(inMemoryDatabase).fileDao()
|
||||
|
||||
fileDao.deleteFile(fileId, OTHER_OWNER, "/a.txt")
|
||||
fileDao.deleteFile(fileId, OWNER, "/b.txt")
|
||||
assertEquals(listOf("/", "/a.txt", "/b.txt"), storedPaths().sortedBy { it })
|
||||
|
||||
fileDao.deleteFile(fileId, OWNER, "/a.txt")
|
||||
assertEquals(listOf("/", "/b.txt"), storedPaths().sortedBy { it })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fileDaoUpdateFolderMetadataKeepsFileOnlyColumns() {
|
||||
createProviderWithInMemoryDatabase()
|
||||
val fileDao = requireNotNull(inMemoryDatabase).fileDao()
|
||||
val storedFolder = OCFile("/folder/").apply {
|
||||
setFolder()
|
||||
etag = "old"
|
||||
storagePath = "/storage/folder"
|
||||
setE2eCounter(5L)
|
||||
etagInConflict = "conflict"
|
||||
}
|
||||
val folderId = fileDao.upsert(storedFolder.toFileEntity(OWNER))
|
||||
val serverFolder = OCFile("/folder/").apply {
|
||||
setFolder()
|
||||
fileId = folderId
|
||||
etag = "new"
|
||||
}
|
||||
|
||||
// shared state to simulate race
|
||||
val inserted = mutableListOf<Long>()
|
||||
fileDao.updateFolderMetadata(serverFolder.toFolderMetadataUpdate(OWNER))
|
||||
|
||||
// mock insert: fail first call, succeed second
|
||||
every { db.insert(any(), any(), any()) } answers {
|
||||
synchronized(inserted) {
|
||||
if (inserted.isEmpty()) {
|
||||
// first thread "fails" insert which means already existing file id will be returned
|
||||
inserted.add(-1L)
|
||||
-1L
|
||||
} else {
|
||||
// second thread "succeeds" it will update existing one
|
||||
inserted.add(42L)
|
||||
42L
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// mock update only one row should be affected
|
||||
every { db.update(any(), any(), any(), any(), any()) } returns 1
|
||||
|
||||
// mock query existing file id will return 99
|
||||
val cursor = mockk<android.database.Cursor>()
|
||||
every { cursor.moveToFirst() } returns true
|
||||
every { cursor.getLong(0) } returns 99L
|
||||
every { cursor.close() } just Runs
|
||||
every { db.query(any<SimpleSQLiteQuery>()) } returns cursor
|
||||
|
||||
// launch two coroutines simulating concurrent threads
|
||||
val results = mutableListOf<Uri>()
|
||||
coroutineScope {
|
||||
val job1 =
|
||||
async {
|
||||
results.add(provider.upsertSingleFile(db, ProviderMeta.ProviderTableMeta.CONTENT_URI_FILE, values))
|
||||
}
|
||||
val job2 =
|
||||
async {
|
||||
results.add(provider.upsertSingleFile(db, ProviderMeta.ProviderTableMeta.CONTENT_URI_FILE, values))
|
||||
}
|
||||
awaitAll(job1, job2)
|
||||
}
|
||||
|
||||
// both URIs should be correct (one updated, one inserted)
|
||||
assertTrue(results.contains(ContentUris.withAppendedId(ProviderMeta.ProviderTableMeta.CONTENT_URI_FILE, 99)))
|
||||
assertTrue(results.contains(ContentUris.withAppendedId(ProviderMeta.ProviderTableMeta.CONTENT_URI_FILE, 42)))
|
||||
|
||||
cursor.close()
|
||||
val updatedFolder = requireNotNull(fileDao.getFileById(folderId))
|
||||
assertEquals("new", updatedFolder.etag)
|
||||
assertEquals(0L, updatedFolder.contentLength)
|
||||
assertEquals(storedFolder.storagePath, updatedFolder.storagePath)
|
||||
assertEquals(5L, updatedFolder.e2eCounter)
|
||||
assertEquals("conflict", updatedFolder.etagInConflict)
|
||||
}
|
||||
}
|
||||
+14
@@ -274,6 +274,8 @@ class DocumentsStorageProviderIT : AbstractOnServerIT() {
|
||||
it!!.write(content2)
|
||||
}
|
||||
|
||||
awaitWriteSaved(file1, content2.size.toLong())
|
||||
|
||||
// read back content bytes
|
||||
val bytes = contentResolver.openInputStream(file1.uri)?.readBytes() ?: ByteArray(0)
|
||||
assertEquals(String(content2), String(bytes))
|
||||
@@ -304,6 +306,18 @@ class DocumentsStorageProviderIT : AbstractOnServerIT() {
|
||||
fail("upload of $remotePath did not finish, stored uploads: ${describeUploads()}")
|
||||
}
|
||||
|
||||
private fun awaitWriteSaved(file: DocumentFile, expectedLength: Long) {
|
||||
repeat(UPLOAD_POLL_ATTEMPTS) {
|
||||
if (file.getOCFile(storageManager)?.fileLength == expectedLength) {
|
||||
return
|
||||
}
|
||||
|
||||
shortSleep()
|
||||
}
|
||||
|
||||
fail("write of ${file.uri} was not saved with length $expectedLength")
|
||||
}
|
||||
|
||||
private fun upload(remotePath: String): OCUpload? = uploadsStorageManager
|
||||
.getUploadsForAccount(user.accountName)
|
||||
.firstOrNull { it.remotePath == remotePath }
|
||||
|
||||
+3
-9
@@ -26,7 +26,6 @@ import androidx.test.espresso.matcher.ViewMatchers.withText
|
||||
import com.facebook.testing.screenshot.internal.TestNameDetector
|
||||
import com.nextcloud.client.preferences.AppPreferencesImpl
|
||||
import com.nextcloud.test.Flaky
|
||||
import com.nextcloud.test.GrantStoragePermissionRule
|
||||
import com.nextcloud.test.withSelectedText
|
||||
import com.nextcloud.utils.extensions.removeFileExtension
|
||||
import com.owncloud.android.AbstractIT
|
||||
@@ -37,16 +36,11 @@ import org.hamcrest.Matchers.not
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TestRule
|
||||
import java.io.File
|
||||
|
||||
class ReceiveExternalFilesActivityIT : AbstractIT() {
|
||||
|
||||
@get:Rule
|
||||
var storagePermissionRule: TestRule = GrantStoragePermissionRule.grant()
|
||||
|
||||
lateinit var mainFolder: OCFile
|
||||
lateinit var subFolder: OCFile
|
||||
lateinit var existingImageFile: OCFile
|
||||
@@ -57,15 +51,15 @@ class ReceiveExternalFilesActivityIT : AbstractIT() {
|
||||
mainFolder = OCFile("/folder/").apply {
|
||||
permissions = OCFile.PERMISSION_CAN_CREATE_FILE_AND_FOLDER
|
||||
setFolder()
|
||||
fileDataStorageManager.saveNewFile(this)
|
||||
storageManager.saveNewFile(this)
|
||||
}
|
||||
subFolder = OCFile("${mainFolder.remotePath}sub folder/").apply {
|
||||
permissions = OCFile.PERMISSION_CAN_CREATE_FILE_AND_FOLDER
|
||||
setFolder()
|
||||
fileDataStorageManager.saveNewFile(this)
|
||||
storageManager.saveNewFile(this)
|
||||
}
|
||||
existingImageFile = OCFile("${mainFolder.remotePath}Existing Image File.jpg").apply {
|
||||
fileDataStorageManager.saveNewFile(this)
|
||||
storageManager.saveNewFile(this)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,23 +14,17 @@ import androidx.test.espresso.Espresso.onView
|
||||
import androidx.test.espresso.assertion.ViewAssertions.matches
|
||||
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
|
||||
import androidx.test.espresso.matcher.ViewMatchers.isRoot
|
||||
import com.nextcloud.test.GrantStoragePermissionRule.Companion.grant
|
||||
import com.owncloud.android.AbstractIT
|
||||
import com.owncloud.android.utils.FileStorageUtils
|
||||
import com.owncloud.android.utils.ScreenshotTest
|
||||
import org.junit.After
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TestRule
|
||||
import java.io.File
|
||||
|
||||
class UploadFilesActivityIT : AbstractIT() {
|
||||
private val testClassName = "com.owncloud.android.ui.activity.UploadFilesActivityIT"
|
||||
|
||||
@get:Rule
|
||||
var storagePermissionRule: TestRule = grant()
|
||||
|
||||
private val directories = listOf("A", "B", "C", "D")
|
||||
.map { File("${FileStorageUtils.getTemporalPath(account.name)}${File.separator}$it") }
|
||||
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ class FileDetailFragmentStaticServerIT : AbstractIT() {
|
||||
private val oCFile: OCFile = OCFile("/").apply {
|
||||
storagePath = file.absolutePath
|
||||
fileId = 12
|
||||
fileDataStorageManager.saveFile(this)
|
||||
storageManager.saveFile(this)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -75,7 +75,7 @@ class FileDetailSharingFragmentIT : AbstractIT() {
|
||||
remoteId = "00000001"
|
||||
parentId = activity.storageManager.getFileByEncryptedRemotePath("/").fileId
|
||||
permissions = OCFile.PERMISSION_CAN_RESHARE
|
||||
fileDataStorageManager.saveFile(this)
|
||||
storageManager.saveFile(this)
|
||||
}
|
||||
|
||||
folder = OCFile("/test").apply {
|
||||
|
||||
-6
@@ -23,7 +23,6 @@ import androidx.test.espresso.matcher.ViewMatchers.isRoot
|
||||
import androidx.test.espresso.matcher.ViewMatchers.withId
|
||||
import androidx.test.espresso.matcher.ViewMatchers.withText
|
||||
import com.nextcloud.test.Flaky
|
||||
import com.nextcloud.test.GrantStoragePermissionRule.Companion.grant
|
||||
import com.nextcloud.test.TestActivity
|
||||
import com.owncloud.android.AbstractIT
|
||||
import com.owncloud.android.R
|
||||
@@ -40,16 +39,11 @@ import org.hamcrest.Matchers.not
|
||||
import org.junit.After
|
||||
import org.junit.Assert
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TestRule
|
||||
|
||||
class OCFileListFragmentStaticServerIT : AbstractIT() {
|
||||
private val testClassName = "com.owncloud.android.ui.fragment.OCFileListFragmentStaticServerIT"
|
||||
|
||||
@get:Rule
|
||||
var storagePermissionRule: TestRule = grant()
|
||||
|
||||
@Before
|
||||
fun initIntentRecording() {
|
||||
Intents.init()
|
||||
|
||||
@@ -14,7 +14,6 @@ import androidx.test.espresso.IdlingRegistry
|
||||
import androidx.test.espresso.assertion.ViewAssertions.matches
|
||||
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
|
||||
import androidx.test.espresso.matcher.ViewMatchers.isRoot
|
||||
import com.nextcloud.test.GrantStoragePermissionRule.Companion.grant
|
||||
import com.nextcloud.test.TestActivity
|
||||
import com.owncloud.android.AbstractIT
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
@@ -26,9 +25,7 @@ import com.owncloud.android.utils.ScreenshotTest
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.After
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TestRule
|
||||
|
||||
internal class SharedListFragmentIT : AbstractIT() {
|
||||
private val testClassName = "com.owncloud.android.ui.fragment.SharedListFragmentIT"
|
||||
@@ -43,9 +40,6 @@ internal class SharedListFragmentIT : AbstractIT() {
|
||||
IdlingRegistry.getInstance().unregister(EspressoIdlingResource.countingIdlingResource)
|
||||
}
|
||||
|
||||
@get:Rule
|
||||
var storagePermissionRule: TestRule = grant()
|
||||
|
||||
@Test
|
||||
@ScreenshotTest
|
||||
fun showSharedFiles() {
|
||||
|
||||
@@ -80,7 +80,7 @@ class PreviewMediaActivityIT : AbstractOnServerIT() {
|
||||
}
|
||||
uploadOCUpload(ocUpload)
|
||||
|
||||
fileDataStorageManager.getFileByDecryptedRemotePath(folder + pngFile.name)!!
|
||||
storageManager.getFileByDecryptedRemotePath(folder + pngFile.name)!!
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -965,7 +965,7 @@ class EncryptionUtilsV2IT : EncryptionIT() {
|
||||
getUserId(user),
|
||||
EncryptionTestIT.privateKey,
|
||||
folder,
|
||||
fileDataStorageManager,
|
||||
storageManager,
|
||||
client,
|
||||
decryptedFolderMetadata1.metadata.counter,
|
||||
signature,
|
||||
|
||||
@@ -612,6 +612,10 @@
|
||||
android:name="com.nextcloud.client.jobs.folderDownload.FolderDownloadWorkerReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<receiver
|
||||
android:name="com.nextcloud.client.jobs.download.FileDownloadCancelReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<activity
|
||||
android:name=".ui.activity.CopyToClipboardActivity"
|
||||
android:exported="false"
|
||||
|
||||
@@ -10,7 +10,9 @@ package com.nextcloud.client.database.dao
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Query
|
||||
import androidx.room.Update
|
||||
import androidx.room.Upsert
|
||||
import com.nextcloud.client.database.entity.FileEntity
|
||||
import com.nextcloud.client.database.entity.model.FolderMetadataUpdate
|
||||
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
|
||||
import com.owncloud.android.utils.MimeType
|
||||
|
||||
@@ -19,6 +21,30 @@ interface FileDao {
|
||||
@Update
|
||||
fun update(entity: FileEntity)
|
||||
|
||||
@Upsert
|
||||
fun upsert(entity: FileEntity): Long
|
||||
|
||||
@Update(entity = FileEntity::class)
|
||||
fun updateFolderMetadata(metadata: FolderMetadataUpdate)
|
||||
|
||||
@Query("DELETE FROM filelist WHERE _id = :id AND file_owner = :fileOwner AND path = :path")
|
||||
fun deleteFile(id: Long, fileOwner: String, path: String): Int
|
||||
|
||||
@Query(
|
||||
"""
|
||||
WITH RECURSIVE descendants(_id) AS (
|
||||
SELECT _id FROM filelist WHERE parent = :folderId
|
||||
UNION
|
||||
SELECT f._id FROM filelist f
|
||||
INNER JOIN descendants d ON f.parent = d._id
|
||||
)
|
||||
DELETE FROM filelist
|
||||
WHERE _id IN (SELECT _id FROM descendants)
|
||||
OR (_id = :folderId AND file_owner = :fileOwner AND path = :path)
|
||||
"""
|
||||
)
|
||||
fun deleteFolder(folderId: Long, fileOwner: String, path: String): Int
|
||||
|
||||
@Query("SELECT * FROM filelist WHERE _id = :id LIMIT 1")
|
||||
fun getFileById(id: Long): FileEntity?
|
||||
|
||||
@@ -199,6 +225,9 @@ interface FileDao {
|
||||
@Query("DELETE FROM filelist WHERE file_owner = :fileOwner AND path = :remotePath")
|
||||
fun deleteFileByRemotePath(fileOwner: String, remotePath: String): Int
|
||||
|
||||
@Query("DELETE FROM filelist WHERE file_owner = :fileOwner")
|
||||
fun deleteAllFiles(fileOwner: String): Int
|
||||
|
||||
@Query("UPDATE filelist SET is_read_only = :readOnly WHERE file_owner = :fileOwner AND path = :path")
|
||||
fun setReadOnly(fileOwner: String, path: String, readOnly: Int): Int
|
||||
|
||||
|
||||
@@ -90,6 +90,22 @@ interface UploadDao {
|
||||
)
|
||||
suspend fun updateStatuses(remotePaths: List<String>, accountName: String, status: Int): Int
|
||||
|
||||
@Query(
|
||||
"""
|
||||
UPDATE ${ProviderTableMeta.UPLOADS_TABLE_NAME}
|
||||
SET ${ProviderTableMeta.UPLOADS_STATUS} = :newStatus,
|
||||
${ProviderTableMeta.UPLOADS_LAST_RESULT} = :lastResult
|
||||
WHERE ${ProviderTableMeta.UPLOADS_ACCOUNT_NAME} = :accountName
|
||||
AND ${ProviderTableMeta.UPLOADS_STATUS} = :currentStatus
|
||||
"""
|
||||
)
|
||||
suspend fun updateStatusAndResultByAccount(
|
||||
accountName: String,
|
||||
currentStatus: Int,
|
||||
newStatus: Int,
|
||||
lastResult: Int
|
||||
): Int
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM ${ProviderTableMeta.UPLOADS_TABLE_NAME}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.client.database.entity.model
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
|
||||
|
||||
data class FolderMetadataUpdate(
|
||||
@ColumnInfo(name = ProviderTableMeta._ID)
|
||||
val id: Long,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_MODIFIED)
|
||||
val modified: Long?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA)
|
||||
val modifiedAtLastSyncForData: Long?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_PARENT)
|
||||
val parent: Long?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_UPLOADED)
|
||||
val uploaded: Long?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_CREATION)
|
||||
val creation: Long?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_CONTENT_TYPE)
|
||||
val contentType: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_CONTENT_LENGTH)
|
||||
val contentLength: Long?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_NAME)
|
||||
val name: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_PATH)
|
||||
val path: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_PATH_DECRYPTED)
|
||||
val pathDecrypted: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_ACCOUNT_OWNER)
|
||||
val accountOwner: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_IS_ENCRYPTED)
|
||||
val isEncrypted: Int?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_IS_READ_ONLY)
|
||||
val isReadOnly: Int?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_LAST_SYNC_DATE)
|
||||
val lastSyncDate: Long?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA)
|
||||
val lastSyncDateForData: Long?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_ETAG)
|
||||
val etag: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_ETAG_ON_SERVER)
|
||||
val etagOnServer: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_SHARED_VIA_LINK)
|
||||
val sharedViaLink: Int?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_SHARED_WITH_SHAREE)
|
||||
val sharedWithSharee: Int?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_PERMISSIONS)
|
||||
val permissions: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_REMOTE_ID)
|
||||
val remoteId: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_LOCAL_ID)
|
||||
val localId: Long,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_FAVORITE)
|
||||
val favorite: Int?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_HIDDEN)
|
||||
val hidden: Int?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_UNREAD_COMMENTS_COUNT)
|
||||
val unreadCommentsCount: Int?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_OWNER_ID)
|
||||
val ownerId: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_OWNER_DISPLAY_NAME)
|
||||
val ownerDisplayName: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_NOTE)
|
||||
val note: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_SHAREES)
|
||||
val sharees: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_TAGS)
|
||||
val tags: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_RICH_WORKSPACE)
|
||||
val richWorkspace: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_INTERNAL_TWO_WAY_SYNC_TIMESTAMP)
|
||||
val internalTwoWaySync: Long?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_INTERNAL_TWO_WAY_SYNC_RESULT)
|
||||
val internalTwoWaySyncResult: String?
|
||||
)
|
||||
@@ -54,7 +54,7 @@ import com.owncloud.android.ui.activity.BaseActivity
|
||||
import com.owncloud.android.ui.activity.ConflictsResolveActivity
|
||||
import com.owncloud.android.ui.activity.ContactsPreferenceActivity
|
||||
import com.owncloud.android.ui.activity.CopyToClipboardActivity
|
||||
import com.owncloud.android.ui.activity.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.ErrorsWhileCopyingHandlerActivity
|
||||
import com.owncloud.android.ui.activity.ExternalSiteWebView
|
||||
import com.owncloud.android.ui.activity.FileActivity
|
||||
|
||||
@@ -365,6 +365,12 @@ class AutoUploadWorker(
|
||||
return@withContext
|
||||
}
|
||||
|
||||
if (result.code == ResultCode.QUOTA_EXCEEDED) {
|
||||
Log_OC.w(TAG, "quota exceeded, stopping auto upload")
|
||||
sendUploadFinishEvent(operation, result)
|
||||
return@withContext
|
||||
}
|
||||
|
||||
// Mark CONFLICT files as handled to prevent retries
|
||||
if (result.code.isConflict()) {
|
||||
repository.markFileAsHandled(localPath, syncedFolder)
|
||||
|
||||
@@ -35,13 +35,35 @@ class DownloadNotificationManager(id: Int, private val context: Context, viewThe
|
||||
setContentTitle(currentOperationTitle)
|
||||
setOngoing(false)
|
||||
setProgress(100, 0, operation.size < 0)
|
||||
clearActions()
|
||||
addAction(
|
||||
R.drawable.ic_cancel,
|
||||
context.getString(R.string.common_cancel),
|
||||
getCancelPendingIntent(operation)
|
||||
)
|
||||
}
|
||||
|
||||
showNotification()
|
||||
}
|
||||
|
||||
private fun getCancelPendingIntent(operation: DownloadFileOperation): PendingIntent {
|
||||
val intent = Intent(context, FileDownloadCancelReceiver::class.java).apply {
|
||||
putExtra(FileDownloadCancelReceiver.ACCOUNT_NAME, operation.user.accountName)
|
||||
putExtra(FileDownloadCancelReceiver.FILE_ID, operation.file.fileId)
|
||||
setPackage(context.packageName)
|
||||
}
|
||||
|
||||
return PendingIntent.getBroadcast(
|
||||
context,
|
||||
getId(),
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
}
|
||||
|
||||
fun prepareForResult() {
|
||||
notificationBuilder
|
||||
.clearActions()
|
||||
.setAutoCancel(true)
|
||||
.setOngoing(false)
|
||||
.setProgress(0, 0, false)
|
||||
@@ -61,6 +83,7 @@ class DownloadNotificationManager(id: Int, private val context: Context, viewThe
|
||||
val notifyId = SecureRandom().nextInt()
|
||||
|
||||
notificationBuilder.run {
|
||||
clearActions()
|
||||
setProgress(0, 0, false)
|
||||
setContentTitle(text)
|
||||
setOngoing(false)
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.client.jobs.download
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
|
||||
class FileDownloadCancelReceiver : BroadcastReceiver() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "FileDownloadCancelReceiver"
|
||||
private const val INVALID_FILE_ID = -1L
|
||||
|
||||
const val ACCOUNT_NAME = "ACCOUNT_NAME"
|
||||
const val FILE_ID = "FILE_ID"
|
||||
}
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val accountName = intent.getStringExtra(ACCOUNT_NAME)
|
||||
if (accountName.isNullOrEmpty()) {
|
||||
return
|
||||
}
|
||||
|
||||
val fileId = intent.getLongExtra(FILE_ID, INVALID_FILE_ID)
|
||||
if (fileId == INVALID_FILE_ID) {
|
||||
return
|
||||
}
|
||||
|
||||
Log_OC.d(TAG, "cancelling download of file: $fileId")
|
||||
FileDownloadWorker.cancelOperation(accountName, fileId)
|
||||
}
|
||||
}
|
||||
@@ -350,7 +350,7 @@ class FileDownloadWorker(
|
||||
private fun showDownloadErrorNotification(downloadError: FileDownloadError) {
|
||||
val text = when (downloadError) {
|
||||
FileDownloadError.Cancelled -> {
|
||||
context.getString(R.string.downloader_file_download_cancelled)
|
||||
context.getString(R.string.downloader_download_canceled)
|
||||
}
|
||||
|
||||
FileDownloadError.Failed -> {
|
||||
|
||||
@@ -14,9 +14,13 @@ import com.nextcloud.client.account.User
|
||||
import com.nextcloud.utils.extensions.getNonEncryptedSubfolders
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.operations.RefreshFolderOperation
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
@@ -107,7 +111,7 @@ class MetadataWorker(private val context: Context, params: WorkerParameters, pri
|
||||
|
||||
val operation = RefreshFolderOperation(folder, storageManager, user, context)
|
||||
return@withContext try {
|
||||
val result = operation.execute(user, context)
|
||||
val result = operation.executeCancellable()
|
||||
if (result.isSuccess) {
|
||||
Log_OC.d(TAG, "Successfully fetched metadata for: ${folder.remotePath}")
|
||||
true
|
||||
@@ -115,9 +119,21 @@ class MetadataWorker(private val context: Context, params: WorkerParameters, pri
|
||||
Log_OC.e(TAG, "Failed to fetch metadata for: ${folder.remotePath}")
|
||||
false
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log_OC.e(TAG, "Exception refreshing folder ${folder.remotePath}: ${e.message}", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun RefreshFolderOperation.executeCancellable(): RemoteOperationResult<*> = coroutineScope {
|
||||
val execution = async { execute(user, context) }
|
||||
try {
|
||||
execution.await()
|
||||
} catch (e: CancellationException) {
|
||||
cancel()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -272,8 +272,9 @@ class AlbumFileUploadWorker(
|
||||
|
||||
if (result.code == ResultCode.QUOTA_EXCEEDED) {
|
||||
Log_OC.w(TAG, "Quota exceeded, stopping uploads")
|
||||
notificationManager.showQuotaExceedNotification(operation)
|
||||
break
|
||||
uploadsStorageManager.markInProgressUploadsAsQuotaExceeded(accountName)
|
||||
fileUploadEventBroadcaster.sendUploadCompleted(operation, result, context)
|
||||
return@withContext Result.failure()
|
||||
}
|
||||
|
||||
sendUploadFinishEvent(totalUploadSize, currentUploadIndex, operation, result)
|
||||
|
||||
@@ -348,8 +348,9 @@ class FileUploadWorker(
|
||||
// check quota first
|
||||
if (result.code == ResultCode.QUOTA_EXCEEDED) {
|
||||
Log_OC.w(TAG, "Quota exceeded, stopping uploads")
|
||||
notificationManager.showQuotaExceedNotification(operation)
|
||||
break
|
||||
uploadsStorageManager.markInProgressUploadsAsQuotaExceeded(accountName)
|
||||
fileUploadEventBroadcaster.sendUploadCompleted(operation, result, context)
|
||||
return@withContext Result.failure()
|
||||
}
|
||||
|
||||
if (!result.isSuccess && !result.code.isUserCancellation()) {
|
||||
|
||||
@@ -91,17 +91,6 @@ class UploadNotificationManager(private val context: Context, viewThemeUtils: Vi
|
||||
)
|
||||
}
|
||||
|
||||
fun showQuotaExceedNotification(operation: UploadFileOperation) {
|
||||
val notification = notificationBuilder.run {
|
||||
setContentTitle(context.getString(R.string.upload_quota_exceeded))
|
||||
setContentText("")
|
||||
clearActions()
|
||||
setProgress(0, 0, false)
|
||||
}.build()
|
||||
|
||||
showNotification(operation.file.fileId.toInt(), notification)
|
||||
}
|
||||
|
||||
fun showConnectionErrorNotification() {
|
||||
notificationManager.cancel(getId())
|
||||
|
||||
|
||||
@@ -76,6 +76,11 @@ object UploadErrorNotificationManager {
|
||||
return
|
||||
}
|
||||
|
||||
if (result.code == ResultCode.QUOTA_EXCEEDED) {
|
||||
AppWideNotificationManager.showQuotaExceededNotification(context)
|
||||
return
|
||||
}
|
||||
|
||||
// do not show an error notification when uploading the same file again
|
||||
if (result.code.isConflict()) {
|
||||
val isSameFile = withContext(Dispatchers.IO) {
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
package com.nextcloud.client.notifications
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Notification
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
@@ -33,10 +34,11 @@ object AppWideNotificationManager {
|
||||
|
||||
private const val TAG = "AppWideNotificationManager"
|
||||
|
||||
private const val SYNC_CONFLICT_NOTIFICATION_INTENT_REQ_CODE = 16
|
||||
private const val UPLOAD_LIST_REQUEST_CODE = 16
|
||||
private const val SYNC_CONFLICT_NOTIFICATION_INTENT_ACTION_REQ_CODE = 17
|
||||
|
||||
private const val SYNC_CONFLICT_NOTIFICATION_ID = 112
|
||||
private const val QUOTA_EXCEEDED_NOTIFICATION_ID = 113
|
||||
|
||||
fun getUploadListPendingIntent(context: Context): PendingIntent {
|
||||
val intent = NavigatorActivity.intent(context, NavigatorScreen.UploadList).apply {
|
||||
@@ -45,7 +47,7 @@ object AppWideNotificationManager {
|
||||
|
||||
return PendingIntent.getActivity(
|
||||
context,
|
||||
SYNC_CONFLICT_NOTIFICATION_INTENT_REQ_CODE,
|
||||
UPLOAD_LIST_REQUEST_CODE,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
@@ -84,16 +86,36 @@ object AppWideNotificationManager {
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.build()
|
||||
|
||||
notify(context, SYNC_CONFLICT_NOTIFICATION_ID, notification)
|
||||
}
|
||||
|
||||
fun showQuotaExceededNotification(context: Context) {
|
||||
val description = context.getString(R.string.upload_quota_exceeded_notification_description)
|
||||
|
||||
val notification = NotificationCompat.Builder(context, NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD)
|
||||
.setSmallIcon(R.drawable.uploads)
|
||||
.setContentTitle(context.getString(R.string.upload_quota_exceeded))
|
||||
.setContentText(description)
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(description))
|
||||
.setContentIntent(getUploadListPendingIntent(context))
|
||||
.setAutoCancel(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.build()
|
||||
|
||||
notify(context, QUOTA_EXCEEDED_NOTIFICATION_ID, notification)
|
||||
}
|
||||
|
||||
private fun notify(context: Context, id: Int, notification: Notification) {
|
||||
if (ActivityCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.POST_NOTIFICATIONS
|
||||
) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
Log_OC.w(TAG, "cannot show sync conflict notification, post notification permission is not granted")
|
||||
Log_OC.w(TAG, "cannot show notification $id, post notification permission is not granted")
|
||||
return
|
||||
}
|
||||
|
||||
NotificationManagerCompat.from(context)
|
||||
.notify(SYNC_CONFLICT_NOTIFICATION_ID, notification)
|
||||
NotificationManagerCompat.from(context).notify(id, notification)
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ import com.nextcloud.ui.ClientIntegrationScreen
|
||||
import com.nextcloud.utils.extensions.getParcelableArgument
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.databinding.ActivityComposeBinding
|
||||
import com.owncloud.android.ui.activity.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
|
||||
class ComposeActivity : DrawerActivity() {
|
||||
|
||||
@@ -81,7 +81,8 @@ class ComposeActivity : DrawerActivity() {
|
||||
composeViewModel.updateSelectedText(text.toString())
|
||||
}
|
||||
|
||||
override fun getMenuItemId(): Int = R.id.nav_assistant
|
||||
override val menuItemId: Int
|
||||
get() = R.id.nav_assistant
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
|
||||
@@ -37,7 +37,7 @@ import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
import com.owncloud.android.lib.resources.users.Status
|
||||
import com.owncloud.android.ui.StatusDrawable
|
||||
import com.owncloud.android.ui.activity.BaseActivity
|
||||
import com.owncloud.android.ui.activity.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.adapter.UserListAdapter
|
||||
import com.owncloud.android.ui.adapter.UserListItem
|
||||
import com.owncloud.android.utils.theme.ViewThemeUtils
|
||||
|
||||
@@ -87,7 +87,7 @@ class FileActionHandler @Inject constructor(
|
||||
|
||||
R.id.action_unset_favorite -> setFavorite(files, false, host)
|
||||
|
||||
else -> return host.helper?.handle(itemId, files, host.view, backgroundJobManager) == true
|
||||
else -> return host.helper?.handle(itemId, files, backgroundJobManager) == true
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
@@ -10,7 +10,7 @@ package com.nextcloud.utils.extensions
|
||||
import android.content.Intent
|
||||
import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.ui.activity.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.FileDisplayActivity
|
||||
import com.owncloud.android.ui.navigation.model.ActionBarStyle
|
||||
|
||||
|
||||
+81
-5
@@ -8,17 +8,18 @@
|
||||
package com.nextcloud.utils.extensions
|
||||
|
||||
import com.nextcloud.client.database.dao.FileDao
|
||||
import com.nextcloud.client.database.entity.FileEntity
|
||||
import com.nextcloud.client.database.entity.model.ShareeKey
|
||||
import com.nextcloud.client.database.entity.toOCCapability
|
||||
import com.nextcloud.model.HTTPStatusCodes
|
||||
import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
|
||||
import com.owncloud.android.lib.common.OwnCloudClient
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation
|
||||
import com.owncloud.android.lib.resources.files.model.RemoteFile
|
||||
import com.owncloud.android.lib.resources.shares.OCShare
|
||||
import com.owncloud.android.lib.resources.status.OCCapability
|
||||
import com.owncloud.android.operations.upload.RemoteFileExistence
|
||||
import com.owncloud.android.utils.FileStorageUtils
|
||||
import com.owncloud.android.utils.MimeType
|
||||
@@ -125,9 +126,6 @@ fun FileDataStorageManager.getNonEncryptedSubfolders(id: Long, accountName: Stri
|
||||
createFileInstance(it)
|
||||
}
|
||||
|
||||
suspend fun FileDataStorageManager.getCapabilitiesByAccountName(accountName: String): OCCapability =
|
||||
capabilityDao.getByAccountName(accountName).toOCCapability()
|
||||
|
||||
fun FileDataStorageManager.moveFiles(ocFile: OCFile?, targetPath: String, targetParentPath: String) {
|
||||
Log_OC.d(
|
||||
FileDataStorageManager.TAG,
|
||||
@@ -357,3 +355,81 @@ private fun FileDataStorageManager.saveFolder(remotePath: String, parent: OCFile
|
||||
saveFile(this)
|
||||
Log_OC.d(FileDataStorageManager.TAG, "createDirectoryTree: created $remotePath in Database")
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts or updates the content of [folder] and removes [filesToRemove] that are its direct children.
|
||||
*
|
||||
* Caller is responsible for granting the right to update the information; this function only keeps the data
|
||||
* consistent.
|
||||
*/
|
||||
fun FileDataStorageManager.saveFolder(folder: OCFile, updatedFiles: List<OCFile>, filesToRemove: Collection<OCFile>) {
|
||||
Log_OC.d(
|
||||
FileDataStorageManager.TAG,
|
||||
"Saving folder ${folder.remotePath} with ${updatedFiles.size} children and " +
|
||||
"${filesToRemove.size} files to remove"
|
||||
)
|
||||
|
||||
val removedChildren = filesToRemove.filter { it.parentId == folder.fileId }
|
||||
removedChildren.forEach { deleteLocalCopy(it) }
|
||||
|
||||
db.runInTransaction {
|
||||
upsertFolderContent(folder, updatedFiles)
|
||||
removedChildren.forEach { deleteFromDatabase(it) }
|
||||
fileDao.updateFolderMetadata(folder.toFolderMetadataUpdate(user.accountName))
|
||||
}
|
||||
|
||||
MainApp.getAppContext().contentResolver.notifyChange(ProviderTableMeta.CONTENT_URI, null)
|
||||
}
|
||||
|
||||
private fun FileDataStorageManager.upsertFolderContent(folder: OCFile, files: List<OCFile>) {
|
||||
files.forEach { file ->
|
||||
val existingFile = findExistingFile(file)
|
||||
val entity = file.toFileEntity(user.accountName).copy(
|
||||
id = existingFile?.id,
|
||||
parent = folder.fileId,
|
||||
mountType = existingFile?.mountType
|
||||
)
|
||||
|
||||
val insertedRowId = fileDao.upsert(entity)
|
||||
if (existingFile == null) {
|
||||
file.fileId = insertedRowId
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun FileDataStorageManager.findExistingFile(file: OCFile): FileEntity? {
|
||||
val fileById = fileDao.getFileById(file.fileId)
|
||||
if (fileById != null) {
|
||||
return fileById
|
||||
}
|
||||
|
||||
return fileDao.getFileByEncryptedRemotePath(file.remotePath, user.accountName)
|
||||
}
|
||||
|
||||
private fun FileDataStorageManager.deleteLocalCopy(file: OCFile) {
|
||||
if (file.isFolder) {
|
||||
val localFolder = File(FileStorageUtils.getDefaultSavePathFor(user.accountName, file))
|
||||
if (localFolder.exists()) {
|
||||
removeLocalFolder(localFolder)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (!file.isDown) {
|
||||
return
|
||||
}
|
||||
|
||||
val storagePath = file.storagePath
|
||||
if (File(storagePath).delete() && MimeTypeUtil.isMedia(file.mimeType)) {
|
||||
FileDataStorageManager.triggerMediaScan(storagePath, file)
|
||||
}
|
||||
}
|
||||
|
||||
private fun FileDataStorageManager.deleteFromDatabase(file: OCFile) {
|
||||
if (file.isFolder) {
|
||||
fileDao.deleteFolder(file.fileId, user.accountName, file.remotePath)
|
||||
return
|
||||
}
|
||||
|
||||
fileDao.deleteFile(file.fileId, user.accountName, file.remotePath)
|
||||
}
|
||||
@@ -32,11 +32,10 @@ fun FileOperationsHelper.handle(@IdRes itemId: Int, file: OCFile, view: View?):
|
||||
fun FileOperationsHelper.handle(
|
||||
@IdRes itemId: Int,
|
||||
files: Collection<OCFile>,
|
||||
view: View?,
|
||||
backgroundJobManager: BackgroundJobManager
|
||||
): Boolean {
|
||||
when (itemId) {
|
||||
R.id.action_export_file -> exportFiles(files, view?.context, view, backgroundJobManager)
|
||||
R.id.action_export_file -> exportFiles(files, backgroundJobManager)
|
||||
R.id.action_add_to_album -> addFileToAlbum(files)
|
||||
else -> return false
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
|
||||
package com.nextcloud.utils.extensions
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.nextcloud.client.database.entity.FileEntity
|
||||
import com.nextcloud.client.database.entity.model.FolderMetadataUpdate
|
||||
import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.datamodel.GalleryItems
|
||||
import com.owncloud.android.datamodel.GalleryRow
|
||||
@@ -17,12 +20,30 @@ import com.owncloud.android.datamodel.OCFileDepth.DeepLevel
|
||||
import com.owncloud.android.datamodel.OCFileDepth.FirstLevel
|
||||
import com.owncloud.android.datamodel.OCFileDepth.Root
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.lib.resources.shares.OCShare
|
||||
import com.owncloud.android.lib.resources.shares.ShareeUser
|
||||
import com.owncloud.android.ui.events.EncryptionEvent
|
||||
import com.owncloud.android.utils.FileStorageUtils
|
||||
import java.io.File
|
||||
import java.util.Calendar
|
||||
|
||||
private const val TAG = "OCFileExtensions"
|
||||
private const val NO_LOCK_TYPE = -1
|
||||
private const val FOLDER_CONTENT_LENGTH = 0L
|
||||
|
||||
private val gson = Gson()
|
||||
|
||||
private fun OCShare.toShareeUser() = ShareeUser(shareWith, sharedWithDisplayName, shareType)
|
||||
|
||||
fun OCFile.addShare(share: OCShare) {
|
||||
val sharee = share.toShareeUser()
|
||||
if (sharee !in sharees) sharees.add(sharee)
|
||||
}
|
||||
|
||||
fun OCFile.removeShare(share: OCShare) {
|
||||
val sharee = share.toShareeUser()
|
||||
sharees.removeAll { it == sharee }
|
||||
}
|
||||
|
||||
fun List<OCFile>.filterFilenames(): List<OCFile> = distinctBy { it.fileName }
|
||||
|
||||
@@ -32,12 +53,7 @@ fun OCFile.isTempFile(): Boolean {
|
||||
return storagePath?.startsWith(appTempPath) == true
|
||||
}
|
||||
|
||||
fun OCFile?.isPNG(): Boolean {
|
||||
if (this == null) {
|
||||
return false
|
||||
}
|
||||
return "image/png".equals(mimeType, ignoreCase = true)
|
||||
}
|
||||
fun OCFile?.isPNG(): Boolean = this != null && "image/png".equals(mimeType, ignoreCase = true)
|
||||
|
||||
fun OCFile?.getDepth(): OCFileDepth? {
|
||||
if (this == null) {
|
||||
@@ -117,3 +133,101 @@ fun OCFile.isLocalETagOutdated(): Boolean {
|
||||
val serverETag = etagInConflict
|
||||
return !serverETag.isNullOrEmpty() && etag.eTagChanged(serverETag)
|
||||
}
|
||||
|
||||
fun OCFile.toFileEntity(accountName: String): FileEntity = FileEntity(
|
||||
id = fileId.takeIf { it > 0 },
|
||||
name = fileName,
|
||||
encryptedName = encryptedFileName,
|
||||
path = remotePath,
|
||||
pathDecrypted = decryptedRemotePath,
|
||||
parent = parentId,
|
||||
creation = creationTimestamp,
|
||||
modified = modificationTimestamp,
|
||||
contentType = mimeType,
|
||||
contentLength = fileLength,
|
||||
storagePath = storagePath,
|
||||
accountOwner = accountName,
|
||||
lastSyncDate = lastSyncDateForProperties,
|
||||
lastSyncDateForData = lastSyncDateForData,
|
||||
modifiedAtLastSyncForData = modificationTimestampAtLastSyncForData,
|
||||
etag = etag,
|
||||
etagOnServer = etagOnServer,
|
||||
sharedViaLink = isSharedViaLink.toInt(),
|
||||
permissions = permissions,
|
||||
remoteId = remoteId,
|
||||
localId = localId,
|
||||
updateThumbnail = isUpdateThumbnailNeeded.toInt(),
|
||||
isDownloading = isDownloading.toInt(),
|
||||
favorite = isFavorite.toInt(),
|
||||
hidden = shouldHide().toInt(),
|
||||
isEncrypted = isEncrypted.toInt(),
|
||||
etagInConflict = etagInConflict,
|
||||
sharedWithSharee = isSharedWithSharee.toInt(),
|
||||
mountType = null,
|
||||
hasPreview = isPreviewAvailable.toInt(),
|
||||
unreadCommentsCount = unreadCommentsCount,
|
||||
ownerId = ownerId,
|
||||
ownerDisplayName = ownerDisplayName,
|
||||
note = note,
|
||||
sharees = gson.toJson(sharees),
|
||||
richWorkspace = richWorkspace,
|
||||
metadataSize = gson.toJson(imageDimension),
|
||||
metadataLivePhoto = linkedFileIdForLivePhoto,
|
||||
locked = isLocked.toInt(),
|
||||
lockType = lockType?.value ?: NO_LOCK_TYPE,
|
||||
lockOwner = lockOwnerId,
|
||||
lockOwnerDisplayName = lockOwnerDisplayName,
|
||||
lockOwnerEditor = lockOwnerEditor,
|
||||
lockTimestamp = lockTimestamp,
|
||||
lockTimeout = lockTimeout.toInt(),
|
||||
lockToken = lockToken,
|
||||
tags = gson.toJson(tags),
|
||||
metadataGPS = gson.toJson(geoLocation),
|
||||
e2eCounter = e2eCounter,
|
||||
internalTwoWaySync = internalFolderSyncTimestamp,
|
||||
internalTwoWaySyncResult = internalFolderSyncResult,
|
||||
uploaded = uploadTimestamp,
|
||||
isReadOnly = isReadOnly.toInt()
|
||||
)
|
||||
|
||||
fun OCFile.toFolderMetadataUpdate(accountName: String): FolderMetadataUpdate {
|
||||
val entity = toFileEntity(accountName)
|
||||
return FolderMetadataUpdate(
|
||||
id = fileId,
|
||||
modified = entity.modified,
|
||||
modifiedAtLastSyncForData = entity.modifiedAtLastSyncForData,
|
||||
parent = entity.parent,
|
||||
uploaded = entity.uploaded,
|
||||
creation = entity.creation,
|
||||
contentType = entity.contentType,
|
||||
contentLength = FOLDER_CONTENT_LENGTH,
|
||||
name = entity.name,
|
||||
path = entity.path,
|
||||
pathDecrypted = entity.pathDecrypted,
|
||||
accountOwner = entity.accountOwner,
|
||||
isEncrypted = entity.isEncrypted,
|
||||
isReadOnly = entity.isReadOnly,
|
||||
lastSyncDate = entity.lastSyncDate,
|
||||
lastSyncDateForData = entity.lastSyncDateForData,
|
||||
etag = entity.etag,
|
||||
etagOnServer = entity.etagOnServer,
|
||||
sharedViaLink = entity.sharedViaLink,
|
||||
sharedWithSharee = entity.sharedWithSharee,
|
||||
permissions = entity.permissions,
|
||||
remoteId = entity.remoteId,
|
||||
localId = entity.localId,
|
||||
favorite = entity.favorite,
|
||||
hidden = entity.hidden,
|
||||
unreadCommentsCount = entity.unreadCommentsCount,
|
||||
ownerId = entity.ownerId,
|
||||
ownerDisplayName = entity.ownerDisplayName,
|
||||
note = entity.note,
|
||||
sharees = entity.sharees,
|
||||
tags = entity.tags,
|
||||
richWorkspace = entity.richWorkspace,
|
||||
internalTwoWaySync = entity.internalTwoWaySync,
|
||||
internalTwoWaySyncResult = entity.internalTwoWaySyncResult
|
||||
)
|
||||
}
|
||||
|
||||
private fun Boolean.toInt(): Int = if (this) 1 else 0
|
||||
@@ -20,7 +20,6 @@ fun UploadResult.isNonRetryable(): Boolean = when (this) {
|
||||
UploadResult.SAME_FILE_CONFLICT,
|
||||
UploadResult.LOCAL_STORAGE_NOT_COPIED,
|
||||
UploadResult.VIRUS_DETECTED,
|
||||
UploadResult.QUOTA_EXCEEDED,
|
||||
UploadResult.PRIVILEGES_ERROR,
|
||||
|
||||
// user's choice
|
||||
|
||||
@@ -132,7 +132,7 @@ import static com.owncloud.android.ui.activity.ContactsPreferenceActivity.PREFER
|
||||
*/
|
||||
public class MainApp extends Application implements HasAndroidInjector, NetworkChangeListener {
|
||||
public static final OwnCloudVersion OUTDATED_SERVER_VERSION = NextcloudVersion.nextcloud_30;
|
||||
public static final OwnCloudVersion MINIMUM_SUPPORTED_SERVER_VERSION = OwnCloudVersion.nextcloud_20;
|
||||
public static final OwnCloudVersion MINIMUM_SUPPORTED_SERVER_VERSION = NextcloudVersion.nextcloud_23;
|
||||
|
||||
private static final String TAG = MainApp.class.getSimpleName();
|
||||
public static final String DOT = ".";
|
||||
|
||||
@@ -937,17 +937,6 @@ open class AuthenticatorActivity :
|
||||
return createAccount(result)
|
||||
}
|
||||
|
||||
val existingLoginName = account?.let { AccountUtils.getUsernameForAccount(it) }
|
||||
if (existingLoginName != null && !existingLoginName.equals(webViewUser, ignoreCase = true)) {
|
||||
Log_OC.w(TAG, "Account: login name does not match ${account?.name}, credentials not updated")
|
||||
authStatus = AuthenticatorStatus(
|
||||
R.drawable.ic_alert,
|
||||
getString(R.string.auth_login_name_mismatch, existingLoginName)
|
||||
)
|
||||
showAuthStatus()
|
||||
return false
|
||||
}
|
||||
|
||||
return try {
|
||||
updateAccountAuthentication()
|
||||
true
|
||||
|
||||
@@ -13,12 +13,9 @@
|
||||
*/
|
||||
package com.owncloud.android.datamodel;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.ContentProviderClient;
|
||||
import android.content.ContentProviderOperation;
|
||||
import android.content.ContentProviderResult;
|
||||
import android.content.ContentResolver;
|
||||
import android.content.ContentUris;
|
||||
import android.content.ContentValues;
|
||||
import android.content.Context;
|
||||
import android.content.OperationApplicationException;
|
||||
@@ -47,9 +44,7 @@ import com.nextcloud.model.OfflineOperationRawType;
|
||||
import com.nextcloud.model.OfflineOperationType;
|
||||
import com.nextcloud.model.ShareeEntry;
|
||||
import com.nextcloud.utils.AppConstants;
|
||||
import com.nextcloud.utils.date.DateFormatPattern;
|
||||
import com.nextcloud.utils.e2ee.E2EVersionHelper;
|
||||
import com.nextcloud.utils.extensions.DateExtensionsKt;
|
||||
import com.nextcloud.utils.extensions.FileDataStorageManagerExtensionsKt;
|
||||
import com.nextcloud.utils.extensions.FileExtensionsKt;
|
||||
import com.nextcloud.utils.extensions.OCFileExtensionsKt;
|
||||
@@ -73,7 +68,6 @@ import com.owncloud.android.lib.resources.status.E2EVersion;
|
||||
import com.owncloud.android.lib.resources.status.OCCapability;
|
||||
import com.owncloud.android.lib.resources.tags.Tag;
|
||||
import com.owncloud.android.operations.RemoteOperationFailedException;
|
||||
import com.owncloud.android.operations.UploadFileOperation;
|
||||
import com.owncloud.android.utils.FileStorageUtils;
|
||||
import com.owncloud.android.utils.MimeType;
|
||||
import com.owncloud.android.utils.MimeTypeUtil;
|
||||
@@ -84,11 +78,8 @@ import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
@@ -116,11 +107,12 @@ public class FileDataStorageManager {
|
||||
private final ContentProviderClient contentProviderClient;
|
||||
private final User user;
|
||||
|
||||
public final RecommendedFileDao recommendedFileDao = NextcloudDatabase.getInstance(MainApp.getAppContext()).recommendedFileDao();
|
||||
public final OfflineOperationDao offlineOperationDao = NextcloudDatabase.getInstance(MainApp.getAppContext()).offlineOperationDao();
|
||||
public final FileDao fileDao = NextcloudDatabase.getInstance(MainApp.getAppContext()).fileDao();
|
||||
public final ShareDao shareDao = NextcloudDatabase.getInstance(MainApp.getAppContext()).shareDao();
|
||||
public final CapabilityDao capabilityDao = NextcloudDatabase.instance().capabilityDao();
|
||||
public final NextcloudDatabase db = NextcloudDatabase.instance();
|
||||
public final RecommendedFileDao recommendedFileDao = db.recommendedFileDao();
|
||||
public final OfflineOperationDao offlineOperationDao = db.offlineOperationDao();
|
||||
public final FileDao fileDao = db.fileDao();
|
||||
public final ShareDao shareDao = db.shareDao();
|
||||
public final CapabilityDao capabilityDao = db.capabilityDao();
|
||||
|
||||
private final Gson gson = new Gson();
|
||||
public final OfflineOperationsRepositoryType offlineOperationsRepository;
|
||||
@@ -743,128 +735,10 @@ public class FileDataStorageManager {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Inserts or updates the list of files contained in a given folder.
|
||||
* <p>
|
||||
* CALLER IS RESPONSIBLE FOR GRANTING RIGHT UPDATE OF INFORMATION, NOT THIS METHOD. HERE ONLY DATA CONSISTENCY
|
||||
* SHOULD BE GRANTED
|
||||
*
|
||||
* @param folder
|
||||
* @param updatedFiles
|
||||
* @param filesToRemove
|
||||
*/
|
||||
public void saveFolder(OCFile folder, List<OCFile> updatedFiles, Collection<OCFile> filesToRemove) {
|
||||
Log_OC.d(TAG, "Saving folder " + folder.getRemotePath() + " with " + updatedFiles.size()
|
||||
+ " children and " + filesToRemove.size() + " files to remove");
|
||||
|
||||
ArrayList<ContentProviderOperation> operations = new ArrayList<>(updatedFiles.size());
|
||||
|
||||
// prepare operations to insert or update files to save in the given folder
|
||||
for (OCFile ocFile : updatedFiles) {
|
||||
ContentValues contentValues = createContentValuesForFile(ocFile);
|
||||
contentValues.put(ProviderTableMeta.FILE_PARENT, folder.getFileId());
|
||||
|
||||
if (fileExists(ocFile.getFileId()) || fileExists(ocFile.getRemotePath())) {
|
||||
long fileId;
|
||||
if (ocFile.getFileId() != -1) {
|
||||
fileId = ocFile.getFileId();
|
||||
} else {
|
||||
fileId = getFileByPath(ocFile.getRemotePath()).getFileId();
|
||||
}
|
||||
// updating an existing file
|
||||
operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI)
|
||||
.withValues(contentValues)
|
||||
.withSelection(ProviderTableMeta._ID + " = ?", new String[]{String.valueOf(fileId)})
|
||||
.build());
|
||||
} else {
|
||||
// adding a new file
|
||||
operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI)
|
||||
.withValues(contentValues)
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
// prepare operations to remove files in the given folder
|
||||
String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + AND + ProviderTableMeta.FILE_PATH + " = ?";
|
||||
String[] whereArgs = new String[2];
|
||||
whereArgs[0] = user.getAccountName();
|
||||
for (OCFile ocFile : filesToRemove) {
|
||||
if (ocFile.getParentId() == folder.getFileId()) {
|
||||
whereArgs[1] = ocFile.getRemotePath();
|
||||
if (ocFile.isFolder()) {
|
||||
operations.add(ContentProviderOperation.newDelete(
|
||||
ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, ocFile.getFileId()))
|
||||
.withSelection(where, whereArgs).build());
|
||||
|
||||
File localFolder = new File(FileStorageUtils.getDefaultSavePathFor(user.getAccountName(), ocFile));
|
||||
if (localFolder.exists()) {
|
||||
removeLocalFolder(localFolder);
|
||||
}
|
||||
} else {
|
||||
operations.add(ContentProviderOperation.newDelete(
|
||||
ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, ocFile.getFileId()))
|
||||
.withSelection(where, whereArgs).build());
|
||||
|
||||
if (ocFile.isDown()) {
|
||||
String path = ocFile.getStoragePath();
|
||||
if (new File(path).delete() && MimeTypeUtil.isMedia(ocFile.getMimeType())) {
|
||||
triggerMediaScan(path, ocFile); // notify MediaScanner about removed file
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// update metadata of folder
|
||||
ContentValues contentValues = createContentValuesForFolder(folder);
|
||||
|
||||
operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI)
|
||||
.withValues(contentValues)
|
||||
.withSelection(ProviderTableMeta._ID + " = ?", new String[]{String.valueOf(folder.getFileId())})
|
||||
.build());
|
||||
|
||||
// apply operations in batch
|
||||
ContentProviderResult[] results = null;
|
||||
Log_OC.d(TAG, String.format(Locale.ENGLISH, SENDING_TO_FILECONTENTPROVIDER_MSG, operations.size()));
|
||||
|
||||
try {
|
||||
if (getContentResolver() != null) {
|
||||
results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
|
||||
|
||||
} else {
|
||||
results = getContentProviderClient().applyBatch(operations);
|
||||
}
|
||||
|
||||
} catch (OperationApplicationException | RemoteException e) {
|
||||
Log_OC.e(TAG, EXCEPTION_MSG + e.getMessage(), e);
|
||||
}
|
||||
|
||||
// update new id in file objects for insertions
|
||||
if (results != null) {
|
||||
long newId;
|
||||
Iterator<OCFile> fileIterator = updatedFiles.iterator();
|
||||
OCFile ocFile;
|
||||
for (ContentProviderResult result : results) {
|
||||
if (fileIterator.hasNext()) {
|
||||
ocFile = fileIterator.next();
|
||||
} else {
|
||||
ocFile = null;
|
||||
}
|
||||
if (result.uri != null) {
|
||||
newId = Long.parseLong(result.uri.getPathSegments().get(1));
|
||||
if (ocFile != null) {
|
||||
ocFile.setFileId(newId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a {@link ContentValues} filled with values that are common to both files and folders
|
||||
*
|
||||
* @see #createContentValuesForFile(OCFile)
|
||||
* @see #createContentValuesForFolder(OCFile)
|
||||
*/
|
||||
@SuppressFBWarnings("CE")
|
||||
private ContentValues createContentValuesBase(OCFile fileOrFolder) {
|
||||
@@ -904,22 +778,9 @@ public class FileDataStorageManager {
|
||||
return cv;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a {@link ContentValues} filled with values for a folder
|
||||
*
|
||||
* @see #createContentValuesForFile(OCFile)
|
||||
* @see #createContentValuesBase(OCFile)
|
||||
*/
|
||||
private ContentValues createContentValuesForFolder(OCFile folder) {
|
||||
final ContentValues cv = createContentValuesBase(folder);
|
||||
cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, 0);
|
||||
return cv;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a {@link ContentValues} filled with values for a file
|
||||
*
|
||||
* @see #createContentValuesForFolder(OCFile)
|
||||
* @see #createContentValuesBase(OCFile)
|
||||
*/
|
||||
@SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
|
||||
@@ -1127,7 +988,7 @@ public class FileDataStorageManager {
|
||||
return success;
|
||||
}
|
||||
|
||||
private boolean removeLocalFolder(File localFolder) {
|
||||
public boolean removeLocalFolder(File localFolder) {
|
||||
if (localFolder == null) {
|
||||
Log_OC.d(TAG, "removeLocalFolder(File): folder is null");
|
||||
return false;
|
||||
@@ -2734,19 +2595,7 @@ public class FileDataStorageManager {
|
||||
}
|
||||
|
||||
public void deleteAllFiles() {
|
||||
String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "= ? AND " +
|
||||
ProviderTableMeta.FILE_PATH + "= ?";
|
||||
String[] whereArgs = new String[]{user.getAccountName(), OCFile.ROOT_PATH};
|
||||
|
||||
if (getContentResolver() != null) {
|
||||
getContentResolver().delete(ProviderTableMeta.CONTENT_URI_DIR, where, whereArgs);
|
||||
} else {
|
||||
try {
|
||||
getContentProviderClient().delete(ProviderTableMeta.CONTENT_URI_DIR, where, whereArgs);
|
||||
} catch (RemoteException e) {
|
||||
Log_OC.e(TAG, "Exception in deleteAllFiles for account " + user.getAccountName() + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
fileDao.deleteAllFiles(user.getAccountName());
|
||||
}
|
||||
|
||||
public String getFolderName(String path) {
|
||||
|
||||
@@ -197,6 +197,17 @@ class UploadsStorageManager(
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun markInProgressUploadsAsQuotaExceeded(accountName: String) {
|
||||
val count = uploadDao.updateStatusAndResultByAccount(
|
||||
accountName = accountName,
|
||||
currentStatus = UploadStatus.UPLOAD_IN_PROGRESS.value,
|
||||
newStatus = UploadStatus.UPLOAD_FAILED.value,
|
||||
lastResult = UploadResult.QUOTA_EXCEEDED.value
|
||||
)
|
||||
Log_OC.d(TAG, "marked $count in progress uploads as quota exceeded")
|
||||
notifyObserversNow()
|
||||
}
|
||||
|
||||
fun removeUpload(upload: OCUpload?): Int = if (upload == null) 0 else removeUpload(upload.uploadId)
|
||||
|
||||
fun removeUpload(id: Long): Int {
|
||||
|
||||
@@ -18,6 +18,7 @@ import com.nextcloud.client.network.ClientFactory;
|
||||
import com.nextcloud.client.network.ClientFactoryImpl;
|
||||
import com.nextcloud.common.NextcloudClient;
|
||||
import com.nextcloud.utils.extensions.DecryptedUserExtensionsKt;
|
||||
import com.nextcloud.utils.extensions.OCFileExtensionsKt;
|
||||
import com.owncloud.android.R;
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProvider;
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager;
|
||||
@@ -263,6 +264,7 @@ public class CreateShareWithShareeOperation extends SyncOperation {
|
||||
OCFile file = getStorageManager().getFileByPath(path);
|
||||
if (file != null) {
|
||||
file.setSharedWithSharee(true); // TODO - this should be done by the FileContentProvider, as part of getStorageManager().saveShare(share)
|
||||
OCFileExtensionsKt.addShare(file, share);
|
||||
getStorageManager().saveFile(file);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,6 +57,9 @@ class DownloadFileOperation(
|
||||
private val cancellationRequested = AtomicBoolean(false)
|
||||
private val mainThreadHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
@Volatile
|
||||
private var downloadOperation: DownloadFileRemoteOperation? = null
|
||||
|
||||
constructor(user: User, file: OCFile, context: Context?) : this(
|
||||
user,
|
||||
file,
|
||||
@@ -165,6 +168,8 @@ class DownloadFileOperation(
|
||||
if (downloadType == DownloadType.DOWNLOAD) {
|
||||
dataTransferListeners.forEach { op.addProgressListener(it) }
|
||||
}
|
||||
downloadOperation = op
|
||||
if (cancellationRequested.get()) op.cancel()
|
||||
}
|
||||
val result = operation.execute(client.toNextcloudClient(operationContext)) as RemoteOperationResult<Unit>
|
||||
return DownloadResult(operation, result)
|
||||
@@ -261,6 +266,7 @@ class DownloadFileOperation(
|
||||
|
||||
fun cancel() {
|
||||
cancellationRequested.set(true)
|
||||
downloadOperation?.cancel()
|
||||
}
|
||||
|
||||
fun addProgressListener(listener: OnDatatransferProgressListener) {
|
||||
|
||||
@@ -18,9 +18,10 @@ import com.nextcloud.client.account.User;
|
||||
import com.nextcloud.common.NextcloudClient;
|
||||
import com.nextcloud.utils.ResultParser;
|
||||
import com.nextcloud.utils.e2ee.E2EVersionHelper;
|
||||
import com.nextcloud.utils.share.UnifiedShareSharees;
|
||||
import com.nextcloud.utils.extensions.FileDataStorageManagerExtensionsKt;
|
||||
import com.nextcloud.utils.extensions.OCFileExtensionsKt;
|
||||
import com.nextcloud.utils.extensions.StringExtensionsKt;
|
||||
import com.nextcloud.utils.share.UnifiedShareSharees;
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProvider;
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProviderImpl;
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager;
|
||||
@@ -33,6 +34,7 @@ import com.owncloud.android.lib.common.OwnCloudClient;
|
||||
import com.owncloud.android.lib.common.OwnCloudClientFactory;
|
||||
import com.owncloud.android.lib.common.UserInfo;
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils;
|
||||
import com.owncloud.android.lib.common.operations.OperationCancelledException;
|
||||
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;
|
||||
@@ -56,6 +58,7 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Vector;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
@@ -122,6 +125,8 @@ public class RefreshFolderOperation extends RemoteOperation {
|
||||
*/
|
||||
private final AtomicInteger mFailsInKeptInSyncFound = new AtomicInteger();
|
||||
|
||||
private final AtomicBoolean cancellationRequested = new AtomicBoolean(false);
|
||||
|
||||
/**
|
||||
* Map of remote and local paths to files that where locally stored in a location out of the ownCloud folder and
|
||||
* couldn't be copied automatically into it
|
||||
@@ -342,6 +347,10 @@ public class RefreshFolderOperation extends RemoteOperation {
|
||||
return result;
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
cancellationRequested.set(true);
|
||||
}
|
||||
|
||||
private void updateOCVersion(OwnCloudClient client) {
|
||||
UpdateOCVersionOperation update = new UpdateOCVersionOperation(user, mContext);
|
||||
RemoteOperationResult result = update.execute(client);
|
||||
@@ -488,6 +497,11 @@ public class RefreshFolderOperation extends RemoteOperation {
|
||||
|
||||
if (result.isSuccess()) {
|
||||
synchronizeData(result.getData());
|
||||
|
||||
if (cancellationRequested.get()) {
|
||||
return new RemoteOperationResult<>(new OperationCancelledException());
|
||||
}
|
||||
|
||||
if (mConflictsFound.get() > 0 || mFailsInKeptInSyncFound.get() > 0) {
|
||||
result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
|
||||
// should be a different result code, but will do the job
|
||||
@@ -657,7 +671,15 @@ public class RefreshFolderOperation extends RemoteOperation {
|
||||
|
||||
UnifiedShareSharees.fillBlocking(user, updatedFiles);
|
||||
|
||||
fileDataStorageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
|
||||
if (cancellationRequested.get()) {
|
||||
Log_OC.d(TAG, "Refresh of " + mLocalFolder.getRemotePath() + " cancelled, local data is not updated");
|
||||
return;
|
||||
}
|
||||
|
||||
FileDataStorageManagerExtensionsKt.saveFolder(fileDataStorageManager,
|
||||
remoteFolder,
|
||||
updatedFiles,
|
||||
localFilesMap.values());
|
||||
|
||||
mChildren = updatedFiles;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import com.nextcloud.utils.share.UnifiedShareSharees;
|
||||
import com.nextcloud.client.jobs.download.FileDownloadHelper;
|
||||
import com.nextcloud.client.jobs.folderDownload.FolderDownloadWorkerNotificationManager;
|
||||
import com.nextcloud.utils.extensions.ExtensionsKt;
|
||||
import com.nextcloud.utils.extensions.FileDataStorageManagerExtensionsKt;
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager;
|
||||
import com.owncloud.android.datamodel.OCFile;
|
||||
import com.owncloud.android.datamodel.e2e.v1.decrypted.DecryptedFolderMetadataFileV1;
|
||||
@@ -368,7 +369,7 @@ public class SynchronizeFolderOperation extends SyncOperation {
|
||||
// save updated contents in local database
|
||||
UnifiedShareSharees.fillBlocking(user, updatedFiles);
|
||||
|
||||
storageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
|
||||
FileDataStorageManagerExtensionsKt.saveFolder(storageManager, remoteFolder, updatedFiles, localFilesMap.values());
|
||||
mLocalFolder.setLastSyncDateForData(System.currentTimeMillis());
|
||||
storageManager.saveFile(mLocalFolder);
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ package com.owncloud.android.operations;
|
||||
import android.content.Context;
|
||||
|
||||
import com.nextcloud.client.account.User;
|
||||
import com.nextcloud.utils.extensions.OCFileExtensionsKt;
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager;
|
||||
import com.owncloud.android.datamodel.OCFile;
|
||||
import com.owncloud.android.datamodel.e2e.v1.decrypted.DecryptedFolderMetadataFileV1;
|
||||
@@ -138,6 +139,7 @@ public class UnshareOperation extends SyncOperation {
|
||||
if (sharesWith.size() == SINGLY_SHARED) {
|
||||
file.setSharedWithSharee(false);
|
||||
}
|
||||
OCFileExtensionsKt.removeShare(file, share);
|
||||
}
|
||||
|
||||
getStorageManager().saveFile(file);
|
||||
|
||||
@@ -150,30 +150,31 @@ public class FileContentProvider extends ContentProvider {
|
||||
private int deleteDirectory(SupportSQLiteDatabase db, Uri uri, String where, String... whereArgs) {
|
||||
int count = 0;
|
||||
|
||||
Cursor children = query(uri, PROJECTION_CONTENT_TYPE, null, null, null);
|
||||
if (children != null) {
|
||||
if (children.moveToFirst()) {
|
||||
long childId;
|
||||
boolean isDir;
|
||||
while (!children.isAfterLast()) {
|
||||
childId = children.getLong(children.getColumnIndexOrThrow(ProviderTableMeta._ID));
|
||||
isDir = MimeType.DIRECTORY.equals(children.getString(
|
||||
children.getColumnIndexOrThrow(ProviderTableMeta.FILE_CONTENT_TYPE)
|
||||
));
|
||||
if (isDir) {
|
||||
count += delete(db, ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, childId),
|
||||
null, (String[]) null);
|
||||
} else {
|
||||
count += delete(db, ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, childId),
|
||||
null, (String[]) null);
|
||||
}
|
||||
children.moveToNext();
|
||||
boolean isSingleDirectory = uri.getPathSegments().size() > MINIMUM_PATH_SEGMENTS_SIZE;
|
||||
Cursor children = isSingleDirectory
|
||||
? query(db, uri, PROJECTION_CONTENT_TYPE, null, null, null)
|
||||
: query(db, uri, PROJECTION_CONTENT_TYPE, where, whereArgs, null);
|
||||
if (children.moveToFirst()) {
|
||||
long childId;
|
||||
boolean isDir;
|
||||
while (!children.isAfterLast()) {
|
||||
childId = children.getLong(children.getColumnIndexOrThrow(ProviderTableMeta._ID));
|
||||
isDir = MimeType.DIRECTORY.equals(children.getString(
|
||||
children.getColumnIndexOrThrow(ProviderTableMeta.FILE_CONTENT_TYPE)
|
||||
));
|
||||
if (isDir) {
|
||||
count += delete(db, ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, childId),
|
||||
null, (String[]) null);
|
||||
} else {
|
||||
count += delete(db, ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, childId),
|
||||
null, (String[]) null);
|
||||
}
|
||||
children.moveToNext();
|
||||
}
|
||||
children.close();
|
||||
}
|
||||
children.close();
|
||||
|
||||
if (uri.getPathSegments().size() > MINIMUM_PATH_SEGMENTS_SIZE) {
|
||||
if (isSingleDirectory) {
|
||||
count += deleteWithUri(db, uri, where, whereArgs);
|
||||
}
|
||||
|
||||
@@ -340,40 +341,21 @@ public class FileContentProvider extends ContentProvider {
|
||||
String where = ProviderTableMeta.FILE_PATH + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?";
|
||||
String[] whereArgs = {filePath, accountOwner};
|
||||
|
||||
// Try insert first, ignore conflict
|
||||
long rowId = db.insert(
|
||||
ProviderTableMeta.FILE_TABLE_NAME,
|
||||
SQLiteDatabase.CONFLICT_IGNORE,
|
||||
values);
|
||||
|
||||
if (rowId <= 0) {
|
||||
// Already exists: update
|
||||
int count = db.update(
|
||||
ProviderTableMeta.FILE_TABLE_NAME,
|
||||
SQLiteDatabase.CONFLICT_NONE,
|
||||
values,
|
||||
where,
|
||||
whereArgs);
|
||||
|
||||
if (count == 0) {
|
||||
throw new SQLException("Failed to update existing file: " + uri);
|
||||
}
|
||||
|
||||
try (Cursor cursor = db.query(
|
||||
new SimpleSQLiteQuery(
|
||||
"SELECT " + ProviderTableMeta._ID +
|
||||
" FROM " + ProviderTableMeta.FILE_TABLE_NAME +
|
||||
" WHERE " + where,
|
||||
whereArgs
|
||||
))) {
|
||||
if (cursor.moveToFirst()) {
|
||||
rowId = cursor.getLong(0);
|
||||
} else {
|
||||
throw new SQLException("Failed to fetch ID after update: " + uri);
|
||||
}
|
||||
try (Cursor cursor = db.query(
|
||||
new SimpleSQLiteQuery(
|
||||
"SELECT " + ProviderTableMeta._ID +
|
||||
" FROM " + ProviderTableMeta.FILE_TABLE_NAME +
|
||||
" WHERE " + where,
|
||||
whereArgs
|
||||
))) {
|
||||
if (cursor.moveToFirst()) {
|
||||
long existingRowId = cursor.getLong(0);
|
||||
db.update(ProviderTableMeta.FILE_TABLE_NAME, SQLiteDatabase.CONFLICT_NONE, values, where, whereArgs);
|
||||
return ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, existingRowId);
|
||||
}
|
||||
}
|
||||
|
||||
long rowId = db.insert(ProviderTableMeta.FILE_TABLE_NAME, SQLiteDatabase.CONFLICT_NONE, values);
|
||||
return ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, rowId);
|
||||
}
|
||||
|
||||
@@ -508,7 +490,8 @@ public class FileContentProvider extends ContentProvider {
|
||||
// add ID to arguments if Uri has more than one segment
|
||||
if (uriMatch != ROOT_DIRECTORY && uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {
|
||||
String idColumn = uriMatch == DIRECTORY ? ProviderTableMeta.FILE_PARENT : ProviderTableMeta._ID;
|
||||
selection = idColumn + "=? AND " + selection;
|
||||
String idSelection = idColumn + "=?";
|
||||
selection = TextUtils.isEmpty(selection) ? idSelection : idSelection + " AND " + selection;
|
||||
selectionArgs = VerificationUtils.prependUriFirstSegmentToSelectionArgs(selectionArgs, uri);
|
||||
}
|
||||
|
||||
|
||||
@@ -49,10 +49,10 @@ public abstract class BaseActivity extends AppCompatActivity implements Injectab
|
||||
private final MixinRegistry mixinRegistry = new MixinRegistry();
|
||||
private SessionMixin sessionMixin;
|
||||
|
||||
@Inject UserAccountManager accountManager;
|
||||
@Inject AppPreferences preferences;
|
||||
@Inject FileDataStorageManager fileDataStorageManager;
|
||||
@Inject ClientRepository clientRepository;
|
||||
@Inject protected UserAccountManager accountManager;
|
||||
@Inject protected AppPreferences preferences;
|
||||
@Inject protected FileDataStorageManager fileDataStorageManager;
|
||||
@Inject protected ClientRepository clientRepository;
|
||||
|
||||
private final AppPreferences.Listener onPreferencesChanged = new AppPreferences.Listener() {
|
||||
@Override
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -75,6 +75,7 @@ import com.owncloud.android.providers.UsersAndGroupsSearchConfig;
|
||||
import com.owncloud.android.providers.UsersAndGroupsSearchProvider;
|
||||
import com.owncloud.android.services.OperationsService;
|
||||
import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity;
|
||||
import com.owncloud.android.ui.asynctasks.CheckRemoteWipeTask;
|
||||
import com.owncloud.android.ui.asynctasks.LoadingVersionNumberTask;
|
||||
import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
|
||||
|
||||
@@ -649,7 +649,7 @@ class FileDisplayActivity :
|
||||
|
||||
else -> {
|
||||
fragment.listDirectory(startFile, false)
|
||||
updateActionBarTitleAndHomeButton(startFile)
|
||||
updateActionBarTitleAndHomeButton(currentDir ?: startFile)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -747,8 +747,7 @@ class FileDisplayActivity :
|
||||
listFragmentJustCreated = true
|
||||
}
|
||||
|
||||
// the onResume() following this intent already lists and re-syncs the current directory
|
||||
browseToRoot(performRefresh = false)
|
||||
browseToRoot()
|
||||
}
|
||||
|
||||
@SuppressLint("UnsafeIntentLaunch")
|
||||
@@ -978,7 +977,8 @@ class FileDisplayActivity :
|
||||
* 2) Currently visible fragment (and its active child)
|
||||
* 3) Fallback to All Files
|
||||
*/
|
||||
override fun getMenuItemId(): Int = MainApp.getMenuItemId() ?: listOfFilesFragment?.menuItemId ?: R.id.nav_all_files
|
||||
override val menuItemId: Int
|
||||
get() = MainApp.getMenuItemId() ?: listOfFilesFragment?.menuItemId ?: R.id.nav_all_files
|
||||
|
||||
override fun setFile(file: OCFile?) {
|
||||
super.setFile(file)
|
||||
@@ -1069,15 +1069,12 @@ class FileDisplayActivity :
|
||||
}
|
||||
}
|
||||
|
||||
fun browseToRoot(performRefresh: Boolean = true) {
|
||||
private fun browseToRoot() {
|
||||
listOfFilesFragment?.let {
|
||||
val root = storageManager.getFileByPath(OCFile.ROOT_PATH)
|
||||
it.resetSearchAttributes()
|
||||
file = root
|
||||
if (performRefresh) {
|
||||
it.listDirectory(root, MainApp.isOnlyOnDevice())
|
||||
startSyncFolderOperation(root, false)
|
||||
}
|
||||
it.listDirectory(root, MainApp.isOnlyOnDevice())
|
||||
}
|
||||
|
||||
binding.fabMain.setImageResource(R.drawable.ic_plus)
|
||||
@@ -1098,7 +1095,7 @@ class FileDisplayActivity :
|
||||
file = currentFile
|
||||
|
||||
currentFile?.let {
|
||||
listOfFiles.setFabVisible(it.canCreateFileAndFolder())
|
||||
listOfFiles.updateFabState()
|
||||
listOfFiles.registerFabListener()
|
||||
}
|
||||
|
||||
@@ -1185,7 +1182,8 @@ class FileDisplayActivity :
|
||||
supportInvalidateOptionsMenu()
|
||||
}
|
||||
|
||||
override fun isDrawerIndicatorAvailable(): Boolean = isRoot(getCurrentDir())
|
||||
override val isDrawerIndicatorAvailable: Boolean
|
||||
get() = isRoot(getCurrentDir())
|
||||
|
||||
fun configureToolbarForPreview(file: OCFile) {
|
||||
lockScrolling()
|
||||
@@ -1301,7 +1299,7 @@ class FileDisplayActivity :
|
||||
view.onActionViewCollapsed()
|
||||
setDrawerIndicatorEnabled(isDrawerIndicatorAvailable) // order matters
|
||||
supportActionBar?.setDisplayHomeAsUpEnabled(true)
|
||||
mDrawerToggle.syncState()
|
||||
mDrawerToggle?.syncState()
|
||||
|
||||
listOfFilesFragment?.run {
|
||||
isSearchFragment = false
|
||||
@@ -2334,7 +2332,7 @@ class FileDisplayActivity :
|
||||
|
||||
private fun refreshGalleryFragmentIfNeeded() {
|
||||
if (topFileListFragment is GalleryFragment) {
|
||||
startPhotoSearch(R.id.nav_gallery)
|
||||
startPhotoSearch()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import com.owncloud.android.BuildConfig
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.databinding.InternalTwoWaySyncLayoutBinding
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.adapter.InternalTwoWaySyncAdapter
|
||||
import com.owncloud.android.ui.navigation.model.ActionBarStyle
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
|
||||
@@ -100,7 +100,7 @@ import androidx.core.content.ContextCompat;
|
||||
import androidx.core.content.res.ResourcesCompat;
|
||||
import kotlin.Unit;
|
||||
|
||||
import static com.owncloud.android.ui.activity.DrawerActivity.REQ_ALL_FILES_ACCESS;
|
||||
import static com.owncloud.android.ui.activity.drawer.DrawerActivity.REQ_ALL_FILES_ACCESS;
|
||||
|
||||
/**
|
||||
* An Activity that allows the user to change the application's settings.
|
||||
|
||||
@@ -32,6 +32,7 @@ import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.datamodel.OCFileDepth
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.fragment.OCFileListFragment
|
||||
import com.owncloud.android.ui.fragment.SearchType
|
||||
import com.owncloud.android.ui.navigation.model.ActionBarStyle
|
||||
|
||||
@@ -40,6 +40,7 @@ import com.owncloud.android.R
|
||||
import com.owncloud.android.databinding.UploadFilesLayoutBinding
|
||||
import com.owncloud.android.datamodel.SyncedFolderProvider
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.uploadfiles.UploadBehaviourSelector
|
||||
import com.owncloud.android.ui.activity.uploadfiles.UploadFilesDialogs
|
||||
import com.owncloud.android.ui.activity.uploadfiles.UploadFilesDialogs.Companion.QUERY_TO_MOVE_DIALOG_TAG
|
||||
|
||||
@@ -44,6 +44,7 @@ import com.owncloud.android.lib.common.accounts.AccountUtils;
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
|
||||
import com.owncloud.android.lib.common.utils.Log_OC;
|
||||
import com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation;
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity;
|
||||
import com.owncloud.android.ui.adapter.UserInfoAdapter;
|
||||
import com.owncloud.android.ui.dialog.AccountRemovalDialog;
|
||||
import com.owncloud.android.ui.events.TokenPushEvent;
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer
|
||||
|
||||
import android.content.Intent
|
||||
import android.content.res.Configuration
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.PersistableBundle
|
||||
import android.os.SystemClock
|
||||
import android.view.Menu
|
||||
import android.view.View
|
||||
import androidx.activity.result.ActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.ActionBarDrawerToggle
|
||||
import androidx.core.content.res.ResourcesCompat
|
||||
import androidx.core.view.GravityCompat
|
||||
import androidx.drawerlayout.widget.DrawerLayout
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.google.android.material.bottomnavigation.BottomNavigationView
|
||||
import com.google.android.material.navigation.NavigationView
|
||||
import com.nextcloud.android.common.core.utils.ecosystem.EcosystemManager
|
||||
import com.nextcloud.android.common.ui.color.ColorUtil
|
||||
import com.nextcloud.client.account.User
|
||||
import com.nextcloud.client.di.Injectable
|
||||
import com.nextcloud.client.onboarding.FirstRunActivity
|
||||
import com.nextcloud.client.player.media3.PlaybackModel
|
||||
import com.nextcloud.client.preferences.AppPreferences
|
||||
import com.nextcloud.client.systembars.SystemBarBackgroundCallbacks
|
||||
import com.nextcloud.ui.dialog.account.ChooseAccountDialogFragment
|
||||
import com.nextcloud.utils.avatar.AvatarGenerationListener
|
||||
import com.nextcloud.utils.avatar.AvatarGenerator
|
||||
import com.nextcloud.utils.extensions.getSelectedMenuItemId
|
||||
import com.nextcloud.utils.extensions.highlightNavigationView
|
||||
import com.nextcloud.utils.extensions.setVisibleIf
|
||||
import com.nextcloud.utils.mdm.MDMConfig
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.authentication.PassCodeManager
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProviderImpl
|
||||
import com.owncloud.android.datamodel.ExternalLinksProvider
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.ui.activity.ManageAccountsActivity
|
||||
import com.owncloud.android.ui.activity.RequestCredentialsActivity
|
||||
import com.owncloud.android.ui.activity.ToolbarActivity
|
||||
import com.owncloud.android.ui.activity.UploadFilesActivity
|
||||
import com.owncloud.android.ui.activity.drawer.avatar.DrawerAvatarGenerationListener
|
||||
import com.owncloud.android.ui.activity.drawer.back.DrawerOnBackPressedCallback
|
||||
import com.owncloud.android.ui.activity.drawer.externallinks.DrawerExternalLinksMenu
|
||||
import com.owncloud.android.ui.activity.drawer.externallinks.ExternalLinkOpener
|
||||
import com.owncloud.android.ui.activity.drawer.externallinks.ExternalLinksSynchronizer
|
||||
import com.owncloud.android.ui.activity.drawer.fragment.DrawerFragmentFinder
|
||||
import com.owncloud.android.ui.activity.drawer.header.DrawerHeaderController
|
||||
import com.owncloud.android.ui.activity.drawer.navigation.DrawerDeepLinkHandler
|
||||
import com.owncloud.android.ui.activity.drawer.navigation.DrawerMenuFilter
|
||||
import com.owncloud.android.ui.activity.drawer.navigation.DrawerMenuItemClickHandler
|
||||
import com.owncloud.android.ui.activity.drawer.navigation.DrawerNavigator
|
||||
import com.owncloud.android.ui.activity.drawer.quota.DrawerQuotaController
|
||||
import com.owncloud.android.ui.events.AccountRemovedEvent
|
||||
import com.owncloud.android.ui.fragment.OCFileListFragment
|
||||
import com.owncloud.android.ui.navigation.NavigatorScreen
|
||||
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.greenrobot.eventbus.EventBus
|
||||
import org.greenrobot.eventbus.Subscribe
|
||||
import org.greenrobot.eventbus.ThreadMode
|
||||
import java.util.Optional
|
||||
import javax.inject.Inject
|
||||
import kotlin.jvm.optionals.getOrNull
|
||||
|
||||
abstract class DrawerActivity :
|
||||
ToolbarActivity(),
|
||||
AvatarGenerationListener by DrawerAvatarGenerationListener(),
|
||||
Injectable {
|
||||
|
||||
@Inject
|
||||
lateinit var playbackModel: PlaybackModel
|
||||
|
||||
@Inject
|
||||
lateinit var avatarGenerator: AvatarGenerator
|
||||
|
||||
@Inject
|
||||
lateinit var colorUtil: ColorUtil
|
||||
|
||||
@JvmField
|
||||
protected var mDrawerToggle: ActionBarDrawerToggle? = null
|
||||
|
||||
var bottomNavigationView: BottomNavigationView? = null
|
||||
private set
|
||||
|
||||
lateinit var ecosystemManager: EcosystemManager
|
||||
private set
|
||||
|
||||
internal var drawerNavigationView: NavigationView? = null
|
||||
private set
|
||||
|
||||
internal lateinit var externalLinksProvider: ExternalLinksProvider
|
||||
private set
|
||||
|
||||
private var drawerLayout: DrawerLayout? = null
|
||||
private var navigationViewHeader: View? = null
|
||||
private var pendingRunnable: Runnable? = null
|
||||
private lateinit var externalLinksSynchronizer: ExternalLinksSynchronizer
|
||||
|
||||
private val fragmentFinder = DrawerFragmentFinder(this)
|
||||
private val drawerNavigator = DrawerNavigator(this)
|
||||
private val externalLinkOpener = ExternalLinkOpener(this)
|
||||
private val externalLinksMenu by lazy { DrawerExternalLinksMenu(this, externalLinkOpener) }
|
||||
private val quotaController by lazy { DrawerQuotaController(this, externalLinkOpener) }
|
||||
private val headerController by lazy { DrawerHeaderController(this, drawerNavigator) }
|
||||
private val menuItemClickHandler by lazy { DrawerMenuItemClickHandler(this, drawerNavigator, externalLinksMenu) }
|
||||
private val deepLinkHandler by lazy { DrawerDeepLinkHandler(this, drawerNavigator, menuItemClickHandler) }
|
||||
|
||||
private val manageAccountsLauncher =
|
||||
registerForActivityResult(ActivityResultContracts.StartActivityForResult(), ::onManageAccountsResult)
|
||||
|
||||
protected open val menuItemId: Int
|
||||
get() = R.id.nav_all_files
|
||||
|
||||
open val isDrawerIndicatorAvailable: Boolean
|
||||
get() = true
|
||||
|
||||
val appPreferences: AppPreferences
|
||||
get() = preferences
|
||||
|
||||
val isDrawerOpen: Boolean
|
||||
get() = drawerLayout?.isDrawerOpen(GravityCompat.START) == true
|
||||
|
||||
val ocFileListFragment: OCFileListFragment?
|
||||
get() = fragmentFinder.ocFileListFragment
|
||||
|
||||
val isAlbumItemsFragment: Boolean
|
||||
get() = fragmentFinder.isAlbumItemsFragmentVisible
|
||||
|
||||
val isAlbumsFragment: Boolean
|
||||
get() = fragmentFinder.isAlbumsFragmentVisible
|
||||
|
||||
val isToolbarStyleSearch: Boolean
|
||||
get() = when (selectedMenuItemId) {
|
||||
Menu.NONE, R.id.nav_all_files, R.id.nav_personal_files -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
internal val isAssistantAvailable: Boolean
|
||||
get() = capabilities.getOrNull()?.assistant?.isTrue == true
|
||||
|
||||
private val selectedMenuItemId: Int
|
||||
get() = drawerNavigationView?.getSelectedMenuItemId() ?: R.id.nav_all_files
|
||||
|
||||
// region Lifecycle
|
||||
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
|
||||
super.onCreate(savedInstanceState, persistentState)
|
||||
onBackPressedDispatcher.addCallback(DrawerOnBackPressedCallback(this))
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
externalLinksProvider = ExternalLinksProvider(contentResolver)
|
||||
externalLinksSynchronizer =
|
||||
ExternalLinksSynchronizer(this, externalLinksProvider, ArbitraryDataProviderImpl(this))
|
||||
ecosystemManager = EcosystemManager(this)
|
||||
}
|
||||
|
||||
public override fun onRestoreInstanceState(savedInstanceState: Bundle) {
|
||||
super.onRestoreInstanceState(savedInstanceState)
|
||||
highlightNavigationViewItem(selectedMenuItemId)
|
||||
}
|
||||
|
||||
override fun onPostCreate(savedInstanceState: Bundle?) {
|
||||
super.onPostCreate(savedInstanceState)
|
||||
mDrawerToggle?.let { toggle ->
|
||||
toggle.syncState()
|
||||
if (isDrawerOpen) {
|
||||
toggle.isDrawerIndicatorEnabled = true
|
||||
}
|
||||
}
|
||||
externalLinksMenu.update()
|
||||
quotaController.updateQuotaLink()
|
||||
}
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
EventBus.getDefault().register(this)
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
if (preferences.lockTimestamp != 0L) {
|
||||
preferences.lockTimestamp = SystemClock.elapsedRealtime()
|
||||
}
|
||||
EventBus.getDefault().unregister(this)
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
externalLinksProvider.cleanup()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
mDrawerToggle?.onConfigurationChanged(newConfig)
|
||||
}
|
||||
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
when (requestCode) {
|
||||
PassCodeManager.PASSCODE_ACTIVITY -> data?.let(::onPassCodeResult)
|
||||
REQ_ALL_FILES_ACCESS, REQ_MEDIA_ACCESS -> checkStoragePermissionWarningBannerVisibility()
|
||||
}
|
||||
}
|
||||
|
||||
@Subscribe(threadMode = ThreadMode.MAIN)
|
||||
open fun onAccountRemovedEvent(event: AccountRemovedEvent) {
|
||||
restart()
|
||||
}
|
||||
// endregion
|
||||
|
||||
// region Drawer setup
|
||||
protected fun setupDrawer(id: Int) {
|
||||
drawerLayout = drawerLayout ?: findViewById(R.id.drawer_layout)
|
||||
drawerNavigationView = drawerNavigationView ?: findViewById(R.id.nav_view)
|
||||
drawerNavigationView?.let { setupDrawerNavigationView(it, id) }
|
||||
|
||||
setupDrawerToggle()
|
||||
supportActionBar?.setDisplayHomeAsUpEnabled(true)
|
||||
|
||||
bottomNavigationView = bottomNavigationView ?: findViewById(R.id.bottom_navigation)
|
||||
bottomNavigationView?.let { setupBottomNavigationView(it, id) }
|
||||
}
|
||||
|
||||
private fun setupDrawerNavigationView(navigationView: NavigationView, id: Int) {
|
||||
viewThemeUtils.files.colorNavigationView(navigationView)
|
||||
navigationViewHeader = navigationView.getHeaderView(0)
|
||||
updateHeader()
|
||||
|
||||
navigationView.setNavigationItemSelectedListener { menuItem ->
|
||||
drawerLayout?.closeDrawers()
|
||||
pendingRunnable = Runnable { menuItemClickHandler.onNavigationItemClicked(menuItem) }
|
||||
true
|
||||
}
|
||||
DrawerMenuFilter.filter(navigationView.menu, userAccountManager.user, capabilities.getOrNull(), resources)
|
||||
|
||||
quotaController.fetchAndDisplay()
|
||||
quotaController.setupViews(navigationView)
|
||||
highlightNavigationViewItem(id)
|
||||
}
|
||||
|
||||
private fun setupBottomNavigationView(bottomNavigation: BottomNavigationView, id: Int) {
|
||||
viewThemeUtils.platform.colorBottomNavigationView(bottomNavigation)
|
||||
showAssistantInBottomNavigation(bottomNavigation)
|
||||
bottomNavigation.setOnItemSelectedListener(menuItemClickHandler::onBottomNavigationItemSelected)
|
||||
highlightNavigationViewItem(id)
|
||||
}
|
||||
|
||||
@SuppressFBWarnings("RV")
|
||||
private fun showAssistantInBottomNavigation(bottomNavigation: BottomNavigationView) {
|
||||
bottomNavigation.menu.findItem(R.id.nav_assistant)?.isVisible = isAssistantAvailable
|
||||
}
|
||||
|
||||
private fun setupDrawerToggle() {
|
||||
val drawerLayout = drawerLayout ?: return
|
||||
val toggle = object : ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open, R.string.drawer_close) {
|
||||
override fun onDrawerClosed(drawerView: View) {
|
||||
super.onDrawerClosed(drawerView)
|
||||
runPendingNavigation()
|
||||
closeDrawer()
|
||||
}
|
||||
}
|
||||
mDrawerToggle = toggle
|
||||
|
||||
drawerLayout.addDrawerListener(toggle)
|
||||
toggle.isDrawerIndicatorEnabled = true
|
||||
toggle.isDrawerSlideAnimationEnabled = true
|
||||
ResourcesCompat.getDrawable(resources, R.drawable.ic_arrow_back, null)?.let { backArrow ->
|
||||
viewThemeUtils.platform.tintToolbarArrowDrawable(this, toggle, backArrow)
|
||||
}
|
||||
}
|
||||
|
||||
private fun runPendingNavigation() {
|
||||
val runnable = pendingRunnable ?: return
|
||||
Handler(Looper.getMainLooper()).post(runnable)
|
||||
pendingRunnable = null
|
||||
}
|
||||
|
||||
fun updateHeader() {
|
||||
val header = navigationViewHeader ?: return
|
||||
headerController.update(header)
|
||||
}
|
||||
// endregion
|
||||
|
||||
// region Navigation
|
||||
fun highlightNavigationViewItem(menuItemId: Int) {
|
||||
highlightNavigationView(drawerNavigationView, bottomNavigationView, menuItemId)
|
||||
SystemBarBackgroundCallbacks.apply(this, viewThemeUtils)
|
||||
Log_OC.d(TAG, "New menu item is: $menuItemId")
|
||||
}
|
||||
|
||||
fun pushFragment(screen: NavigatorScreen) = drawerNavigator.pushFragment(screen)
|
||||
|
||||
fun startPhotoSearch() = drawerNavigator.startPhotoSearch()
|
||||
|
||||
open fun showFiles(onDeviceOnly: Boolean, onlyPersonalFiles: Boolean) =
|
||||
drawerNavigator.showFiles(onDeviceOnly, onlyPersonalFiles)
|
||||
|
||||
fun replaceAlbumFragment() = drawerNavigator.replaceAlbumFragment()
|
||||
|
||||
fun <T : Fragment> getFragment(tag: String?, clazz: Class<T>): Optional<T> = fragmentFinder.getFragment(tag, clazz)
|
||||
|
||||
fun showBottomNavigationBar(show: Boolean) {
|
||||
bottomNavigationView.setVisibleIf(show)
|
||||
}
|
||||
|
||||
protected fun handleDeepLink(uri: Uri) = deepLinkHandler.handle(uri)
|
||||
|
||||
private fun restart() {
|
||||
drawerNavigator.restartFileDisplayActivity()
|
||||
fetchExternalLinks(false)
|
||||
}
|
||||
// endregion
|
||||
|
||||
// region Drawer state
|
||||
fun toggleDrawer() {
|
||||
if (isDrawerOpen) {
|
||||
closeDrawer()
|
||||
} else {
|
||||
openDrawer()
|
||||
}
|
||||
}
|
||||
|
||||
fun closeDrawer() {
|
||||
drawerLayout?.closeDrawer(GravityCompat.START)
|
||||
}
|
||||
|
||||
fun openDrawer() {
|
||||
val drawerLayout = drawerLayout ?: return
|
||||
drawerLayout.openDrawer(GravityCompat.START)
|
||||
externalLinksMenu.update()
|
||||
quotaController.updateQuotaLink()
|
||||
}
|
||||
|
||||
fun setDrawerLockMode(lockMode: Int) {
|
||||
drawerLayout?.setDrawerLockMode(lockMode)
|
||||
}
|
||||
|
||||
fun setDrawerIndicatorEnabled(enable: Boolean) {
|
||||
mDrawerToggle?.isDrawerIndicatorEnabled = enable
|
||||
}
|
||||
|
||||
fun addDrawerListener(listener: DrawerLayout.DrawerListener?) {
|
||||
val drawerLayout = drawerLayout
|
||||
if (drawerLayout == null) {
|
||||
Log_OC.e(TAG, "Drawer layout not ready to add drawer listener")
|
||||
return
|
||||
}
|
||||
listener?.let(drawerLayout::addDrawerListener)
|
||||
}
|
||||
|
||||
override fun updateActionBarTitleAndHomeButton(chosenFile: OCFile?) {
|
||||
super.updateActionBarTitleAndHomeButton(chosenFile)
|
||||
mDrawerToggle?.isDrawerIndicatorEnabled = chosenFile != null && isRoot(chosenFile)
|
||||
}
|
||||
// endregion
|
||||
|
||||
// region Accounts
|
||||
fun showManageAccountsDialog() {
|
||||
ChooseAccountDialogFragment.newInstance(userAccountManager.user)
|
||||
.show(supportFragmentManager, CHOOSE_ACCOUNT_DIALOG_TAG)
|
||||
}
|
||||
|
||||
fun openManageAccounts() {
|
||||
manageAccountsLauncher.launch(Intent(applicationContext, ManageAccountsActivity::class.java))
|
||||
}
|
||||
|
||||
fun openAddAccount() {
|
||||
stopMediaPlayerAndHidePip()
|
||||
if (!MDMConfig.showIntro(this)) {
|
||||
startAccountCreation()
|
||||
return
|
||||
}
|
||||
|
||||
val intent = Intent(applicationContext, FirstRunActivity::class.java)
|
||||
.putExtra(FirstRunActivity.EXTRA_ALLOW_CLOSE, true)
|
||||
startActivity(intent)
|
||||
}
|
||||
|
||||
protected fun stopMediaPlayerAndHidePip() {
|
||||
playbackModel.release()
|
||||
}
|
||||
|
||||
fun accountClicked(user: User?) {
|
||||
val accountManager = userAccountManager
|
||||
if (accountManager.user.nameEquals(user) || !accountManager.setCurrentOwnCloudAccount(user)) return
|
||||
fetchExternalLinks(true)
|
||||
restart()
|
||||
}
|
||||
|
||||
fun fetchExternalLinks(force: Boolean) {
|
||||
if (!MDMConfig.externalSiteSupport(this)) return
|
||||
|
||||
val user = userAccountManager.user
|
||||
if (user.isAnonymous) {
|
||||
Log_OC.d(TAG, "Trying to execute a sync operation with a storage manager for an anonymous account")
|
||||
return
|
||||
}
|
||||
|
||||
lifecycleScope.launch {
|
||||
withContext(Dispatchers.IO) { externalLinksSynchronizer.sync(user, force) }
|
||||
externalLinksMenu.update()
|
||||
}
|
||||
}
|
||||
|
||||
private fun onManageAccountsResult(result: ActivityResult) {
|
||||
if (result.resultCode != RESULT_OK) return
|
||||
val data = result.data ?: return
|
||||
if (!data.getBooleanExtra(ManageAccountsActivity.KEY_ACCOUNT_LIST_CHANGED, false)) return
|
||||
if (!data.getBooleanExtra(ManageAccountsActivity.KEY_CURRENT_ACCOUNT_CHANGED, false)) return
|
||||
|
||||
setAccount(userAccountManager.currentAccount, false)
|
||||
restart()
|
||||
}
|
||||
|
||||
private fun onPassCodeResult(data: Intent) {
|
||||
val result = data.getIntExtra(
|
||||
RequestCredentialsActivity.KEY_CHECK_RESULT,
|
||||
RequestCredentialsActivity.KEY_CHECK_RESULT_FALSE
|
||||
)
|
||||
if (result != RequestCredentialsActivity.KEY_CHECK_RESULT_CANCEL) return
|
||||
|
||||
Log_OC.d(TAG, "PassCodeManager cancelled")
|
||||
preferences.lockTimestamp = 0
|
||||
finish()
|
||||
}
|
||||
|
||||
private fun checkStoragePermissionWarningBannerVisibility() {
|
||||
(this as? UploadFilesActivity)?.setupStoragePermissionWarningBanner()
|
||||
}
|
||||
// endregion
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DrawerActivity"
|
||||
private const val CHOOSE_ACCOUNT_DIALOG_TAG = "fragment_chose_account"
|
||||
|
||||
const val REQ_ALL_FILES_ACCESS = 3001
|
||||
const val REQ_MEDIA_ACCESS = 3000
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.avatar
|
||||
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.view.MenuItem
|
||||
import android.widget.ImageView
|
||||
import com.google.android.material.button.MaterialButton
|
||||
import com.nextcloud.utils.avatar.AvatarGenerationListener
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
|
||||
class DrawerAvatarGenerationListener : AvatarGenerationListener {
|
||||
|
||||
override fun avatarGenerated(avatarDrawable: Drawable?, callContext: Any?) {
|
||||
when (callContext) {
|
||||
is MenuItem -> {
|
||||
val newIcon = callContext.setIcon(avatarDrawable)
|
||||
Log_OC.d(TAG, "avatarGenerated new icon: $newIcon")
|
||||
}
|
||||
|
||||
is ImageView -> callContext.setImageDrawable(avatarDrawable)
|
||||
|
||||
is MaterialButton -> callContext.icon = avatarDrawable
|
||||
}
|
||||
}
|
||||
|
||||
override fun shouldCallGeneratedCallback(tag: String?, callContext: Any?): Boolean {
|
||||
val contextTag: Any? = when (callContext) {
|
||||
is MenuItem -> callContext.title
|
||||
is ImageView -> callContext.tag
|
||||
is MaterialButton -> callContext.tag
|
||||
else -> return false
|
||||
}
|
||||
return contextTag.toString() == tag
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DrawerAvatarGenerationListener"
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.back
|
||||
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.fragment.FileDetailsSharingProcessFragment
|
||||
|
||||
class DrawerOnBackPressedCallback(private val activity: DrawerActivity) : OnBackPressedCallback(true) {
|
||||
|
||||
override fun handleOnBackPressed() {
|
||||
if (activity.isDrawerOpen) {
|
||||
activity.closeDrawer()
|
||||
return
|
||||
}
|
||||
|
||||
val fragment = activity.supportFragmentManager.findFragmentByTag(FileDetailsSharingProcessFragment.TAG)
|
||||
if (fragment is FileDetailsSharingProcessFragment) {
|
||||
fragment.onBackPressed()
|
||||
return
|
||||
}
|
||||
|
||||
isEnabled = false
|
||||
activity.onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.externallinks
|
||||
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.view.MenuItem
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.google.android.material.navigation.NavigationView
|
||||
import com.nextcloud.utils.GlideHelper
|
||||
import com.nextcloud.utils.mdm.MDMConfig
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.lib.common.ExternalLink
|
||||
import com.owncloud.android.lib.common.ExternalLinkType
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.utils.DrawableUtil
|
||||
|
||||
class DrawerExternalLinksMenu(
|
||||
private val activity: DrawerActivity,
|
||||
private val externalLinkOpener: ExternalLinkOpener
|
||||
) {
|
||||
|
||||
fun update() {
|
||||
val navigationView = activity.drawerNavigationView ?: return
|
||||
if (!MDMConfig.externalSiteSupport(activity)) return
|
||||
|
||||
navigationView.menu.removeGroup(R.id.drawer_menu_external_links)
|
||||
|
||||
val greyColor = ContextCompat.getColor(activity, R.color.drawer_menu_icon)
|
||||
activity.externalLinksProvider.getExternalLink(ExternalLinkType.LINK) { externalLinks ->
|
||||
externalLinks.forEach { addMenuItem(navigationView, it, greyColor) }
|
||||
}
|
||||
}
|
||||
|
||||
fun onExternalLinkClicked(menuItem: MenuItem) {
|
||||
val linkId = menuItem.itemId - MENU_ITEM_EXTERNAL_LINK
|
||||
activity.externalLinksProvider.getExternalLink(ExternalLinkType.LINK) { externalLinks ->
|
||||
val link = externalLinks.firstOrNull { it.id == linkId }
|
||||
if (link == null) {
|
||||
Log_OC.w(TAG, "No external link found for menu item: " + menuItem.title)
|
||||
} else {
|
||||
externalLinkOpener.open(link)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun addMenuItem(navigationView: NavigationView, link: ExternalLink, tintColor: Int) {
|
||||
val menuItemId = navigationView.menu
|
||||
.add(
|
||||
R.id.drawer_menu_external_links,
|
||||
MENU_ITEM_EXTERNAL_LINK + link.id,
|
||||
MENU_ORDER_EXTERNAL_LINKS,
|
||||
link.name
|
||||
)
|
||||
.setCheckable(true)
|
||||
.itemId
|
||||
|
||||
GlideHelper.loadIntoTarget(
|
||||
activity,
|
||||
activity.userAccountManager.currentOwnCloudAccount,
|
||||
link.iconUrl,
|
||||
ExternalLinkMenuIconTarget { setMenuItemIcon(navigationView, menuItemId, it, tintColor) },
|
||||
R.drawable.ic_link
|
||||
)
|
||||
}
|
||||
|
||||
private fun setMenuItemIcon(navigationView: NavigationView, menuItemId: Int, drawable: Drawable?, tintColor: Int) {
|
||||
val menuItem = navigationView.menu.findItem(menuItemId) ?: return
|
||||
if (drawable == null) {
|
||||
menuItem.setIcon(R.drawable.ic_link)
|
||||
return
|
||||
}
|
||||
|
||||
val resizedDrawable = DrawableUtil.getResizedDrawable(activity, drawable, ICON_SIZE_PX)
|
||||
menuItem.icon = activity.viewThemeUtils.platform.colorDrawable(resizedDrawable, tintColor)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DrawerExternalLinksMenu"
|
||||
private const val MENU_ORDER_EXTERNAL_LINKS = 3
|
||||
private const val MENU_ITEM_EXTERNAL_LINK = 111
|
||||
private const val ICON_SIZE_PX = 32
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.externallinks
|
||||
|
||||
import android.graphics.drawable.Drawable
|
||||
import com.bumptech.glide.request.target.CustomTarget
|
||||
import com.bumptech.glide.request.transition.Transition
|
||||
|
||||
class ExternalLinkMenuIconTarget(private val onIconLoaded: (Drawable?) -> Unit) : CustomTarget<Drawable>() {
|
||||
|
||||
override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
|
||||
onIconLoaded(resource)
|
||||
}
|
||||
|
||||
override fun onLoadFailed(errorDrawable: Drawable?) {
|
||||
onIconLoaded(errorDrawable)
|
||||
}
|
||||
|
||||
override fun onLoadCleared(placeholder: Drawable?) = Unit
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.externallinks
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import com.nextcloud.client.utils.IntentUtil
|
||||
import com.owncloud.android.lib.common.ExternalLink
|
||||
import com.owncloud.android.ui.activity.ExternalSiteWebView
|
||||
|
||||
class ExternalLinkOpener(private val activity: Activity) {
|
||||
|
||||
fun open(link: ExternalLink) {
|
||||
if (link.redirect) {
|
||||
IntentUtil.startLinkIntent(activity, link.url)
|
||||
return
|
||||
}
|
||||
openInWebView(link)
|
||||
}
|
||||
|
||||
fun openInWebView(link: ExternalLink) {
|
||||
val intent = Intent(activity.applicationContext, ExternalSiteWebView::class.java)
|
||||
.putExtra(ExternalSiteWebView.EXTRA_TITLE, link.name)
|
||||
.putExtra(ExternalSiteWebView.EXTRA_URL, link.url)
|
||||
.putExtra(ExternalSiteWebView.EXTRA_SHOW_SIDEBAR, true)
|
||||
activity.startActivity(intent)
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.externallinks
|
||||
|
||||
import androidx.annotation.WorkerThread
|
||||
import com.nextcloud.client.account.User
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProvider
|
||||
import com.owncloud.android.datamodel.ExternalLinksProvider
|
||||
import com.owncloud.android.lib.common.ExternalLink
|
||||
import com.owncloud.android.lib.common.accounts.ExternalLinksOperation
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.operations.GetCapabilitiesOperation
|
||||
import com.owncloud.android.ui.activity.BaseActivity
|
||||
import com.owncloud.android.ui.activity.FileActivity
|
||||
import com.owncloud.android.utils.FilesSyncHelper
|
||||
import com.owncloud.android.utils.theme.CapabilityUtils
|
||||
import kotlin.jvm.optionals.getOrNull
|
||||
|
||||
class ExternalLinksSynchronizer(
|
||||
private val activity: BaseActivity,
|
||||
private val externalLinksProvider: ExternalLinksProvider,
|
||||
private val appOpenedCountProvider: ArbitraryDataProvider
|
||||
) {
|
||||
|
||||
@WorkerThread
|
||||
fun sync(user: User, force: Boolean) {
|
||||
refreshCapabilities()
|
||||
syncExternalLinks(user, force)
|
||||
}
|
||||
|
||||
private fun refreshCapabilities() {
|
||||
val capability = activity.capabilities.getOrNull() ?: return
|
||||
if (capability.accountName?.isEmpty() == true) return
|
||||
val storageManager = activity.storageManager ?: return
|
||||
GetCapabilitiesOperation(storageManager).execute(activity.baseContext)
|
||||
}
|
||||
|
||||
private fun syncExternalLinks(user: User, force: Boolean) {
|
||||
val isExternalLinksEnabled =
|
||||
activity.storageManager != null && CapabilityUtils.getCapability(user, activity).externalLinks.isTrue
|
||||
if (!isExternalLinksEnabled) {
|
||||
externalLinksProvider.deleteAllExternalLinks()
|
||||
Log_OC.d(TAG, "links disabled")
|
||||
return
|
||||
}
|
||||
|
||||
val appOpenedCount =
|
||||
appOpenedCountProvider.getIntegerValue(FilesSyncHelper.GLOBAL, FileActivity.APP_OPENED_COUNT)
|
||||
val shouldUpdate = force ||
|
||||
appOpenedCount == APP_OPENED_COUNT_NOT_SET ||
|
||||
appOpenedCount > APP_OPENED_COUNT_UPDATE_THRESHOLD
|
||||
if (!shouldUpdate) {
|
||||
storeAppOpenedCount(appOpenedCount + 1)
|
||||
return
|
||||
}
|
||||
|
||||
if (force) {
|
||||
Log_OC.d(TAG, "force update")
|
||||
}
|
||||
storeAppOpenedCount(0)
|
||||
|
||||
Log_OC.d(TAG, "update via api")
|
||||
val result = ExternalLinksOperation().execute(user, activity)
|
||||
if (!result.isSuccess) return
|
||||
val externalLinks = result.data ?: return
|
||||
|
||||
externalLinksProvider.deleteAllExternalLinks()
|
||||
externalLinks.filterIsInstance<ExternalLink>().forEach(externalLinksProvider::storeExternalLink)
|
||||
}
|
||||
|
||||
private fun storeAppOpenedCount(count: Int) {
|
||||
appOpenedCountProvider.storeOrUpdateKeyValue(FilesSyncHelper.GLOBAL, FileActivity.APP_OPENED_COUNT, "$count")
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ExternalLinks"
|
||||
private const val APP_OPENED_COUNT_NOT_SET = -1
|
||||
private const val APP_OPENED_COUNT_UPDATE_THRESHOLD = 10
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.fragment
|
||||
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.fragment.app.FragmentManager
|
||||
import com.nextcloud.utils.extensions.lastFragment
|
||||
import com.owncloud.android.ui.activity.FileDisplayActivity
|
||||
import com.owncloud.android.ui.fragment.OCFileListFragment
|
||||
import com.owncloud.android.ui.fragment.albums.AlbumItemsFragment
|
||||
import com.owncloud.android.ui.fragment.albums.AlbumsFragment
|
||||
import java.util.Optional
|
||||
|
||||
class DrawerFragmentFinder(private val activity: AppCompatActivity) {
|
||||
|
||||
private val fragmentManager: FragmentManager
|
||||
get() = activity.supportFragmentManager
|
||||
|
||||
val ocFileListFragment: OCFileListFragment?
|
||||
get() = activity.lastFragment() as? OCFileListFragment
|
||||
?: fragmentManager.findFragmentByTag(FileDisplayActivity.TAG_LIST_OF_FILES) as? OCFileListFragment
|
||||
|
||||
val isAlbumsFragmentVisible: Boolean
|
||||
get() = isFragmentVisible<AlbumsFragment>(AlbumsFragment.TAG)
|
||||
|
||||
val isAlbumItemsFragmentVisible: Boolean
|
||||
get() = isFragmentVisible<AlbumItemsFragment>(AlbumItemsFragment.TAG)
|
||||
|
||||
fun <T : Fragment> getFragment(tag: String?, clazz: Class<T>): Optional<T> =
|
||||
Optional.ofNullable(fragmentManager.findFragmentByTag(tag))
|
||||
.filter(clazz::isInstance)
|
||||
.map(clazz::cast)
|
||||
|
||||
private inline fun <reified T : Fragment> isFragmentVisible(tag: String): Boolean =
|
||||
(fragmentManager.findFragmentByTag(tag) as? T)?.isVisible == true
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.header
|
||||
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.view.View
|
||||
import android.webkit.URLUtil
|
||||
import android.widget.ImageView
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.constraintlayout.widget.ConstraintLayout
|
||||
import com.nextcloud.utils.GlideHelper
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.drawer.navigation.DrawerNavigator
|
||||
import kotlin.jvm.optionals.getOrNull
|
||||
|
||||
class DrawerHeaderController(private val activity: DrawerActivity, navigator: DrawerNavigator) {
|
||||
|
||||
private val brandingColors = ServerBrandingColors(activity)
|
||||
private val ecosystemAppsBanner = EcosystemAppsBanner(activity, navigator, brandingColors)
|
||||
|
||||
fun update(header: View) {
|
||||
val isClientBranded = activity.resources.getBoolean(R.bool.is_branded_client)
|
||||
if (!isClientBranded) {
|
||||
showServerBranding(header)
|
||||
}
|
||||
|
||||
val banner = header.findViewById<ConstraintLayout>(R.id.drawer_ecosystem_apps)
|
||||
if (isClientBranded || !activity.appPreferences.isShowEcosystemApps) {
|
||||
banner.visibility = View.GONE
|
||||
} else {
|
||||
ecosystemAppsBanner.show(banner)
|
||||
}
|
||||
}
|
||||
|
||||
private fun showServerBranding(header: View) {
|
||||
val account = activity.account ?: return
|
||||
val capability = activity.capabilities.getOrNull() ?: return
|
||||
if (capability.serverBackground == null) return
|
||||
|
||||
val primaryColor = brandingColors.getPrimaryColor(account)
|
||||
header.findViewById<LinearLayout>(R.id.drawer_header_view).setBackgroundColor(primaryColor)
|
||||
|
||||
val serverLogoURL = capability.serverLogo
|
||||
if (serverLogoURL.isNullOrEmpty() || !URLUtil.isValidUrl(serverLogoURL)) return
|
||||
|
||||
GlideHelper.loadIntoTarget(
|
||||
activity,
|
||||
activity.userAccountManager.currentOwnCloudAccount,
|
||||
serverLogoURL,
|
||||
ServerLogoTarget(activity.resources, primaryColor) { setHeaderLogo(header, it, capability.serverName) },
|
||||
R.drawable.background
|
||||
)
|
||||
}
|
||||
|
||||
private fun setHeaderLogo(header: View, drawable: Drawable, serverName: String?) {
|
||||
header.findViewById<ImageView>(R.id.drawer_header_logo).run {
|
||||
setImageDrawable(drawable)
|
||||
adjustViewBounds = true
|
||||
}
|
||||
|
||||
if (serverName.isNullOrEmpty()) return
|
||||
header.findViewById<TextView>(R.id.drawer_header_server_name).run {
|
||||
visibility = View.VISIBLE
|
||||
text = serverName
|
||||
setTextColor(brandingColors.textColor)
|
||||
}
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.header
|
||||
|
||||
import android.content.res.ColorStateList
|
||||
import android.graphics.Color
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.view.View
|
||||
import android.widget.ImageView
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.constraintlayout.widget.ConstraintLayout
|
||||
import androidx.core.view.isVisible
|
||||
import com.nextcloud.android.common.core.utils.ecosystem.EcosystemApp
|
||||
import com.nextcloud.utils.LinkHelper
|
||||
import com.nextcloud.utils.view.ScreenMetrics
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.drawer.navigation.DrawerNavigator
|
||||
import hct.Hct
|
||||
import kotlin.jvm.optionals.getOrNull
|
||||
|
||||
class EcosystemAppsBanner(
|
||||
private val activity: DrawerActivity,
|
||||
private val navigator: DrawerNavigator,
|
||||
private val brandingColors: ServerBrandingColors
|
||||
) {
|
||||
|
||||
private val iconColor: Int
|
||||
get() {
|
||||
val account = activity.account ?: return activity.getColor(R.color.grey_800_transparent)
|
||||
val isServerPrimaryColorDark =
|
||||
Hct.fromInt(brandingColors.getPrimaryColor(account)).tone < LIGHT_TONE_THRESHOLD
|
||||
return if (isServerPrimaryColorDark) Color.WHITE else activity.getColor(R.color.grey_800_transparent)
|
||||
}
|
||||
|
||||
fun show(banner: ConstraintLayout) {
|
||||
val notesView = banner.findViewById<LinearLayout>(R.id.drawer_ecosystem_notes)
|
||||
val talkView = banner.findViewById<LinearLayout>(R.id.drawer_ecosystem_talk)
|
||||
val moreView = banner.findViewById<LinearLayout>(R.id.drawer_ecosystem_more)
|
||||
val assistantView = banner.findViewById<LinearLayout>(R.id.drawer_ecosystem_assistant)
|
||||
|
||||
activity.user.getOrNull()?.accountName?.let { accountName ->
|
||||
notesView.setOnClickListener { activity.ecosystemManager.openApp(EcosystemApp.NOTES, accountName) }
|
||||
talkView.setOnClickListener { activity.ecosystemManager.openApp(EcosystemApp.TALK, accountName) }
|
||||
}
|
||||
moreView.setOnClickListener { LinkHelper.openAppStore(APP_STORE_QUERY, true, activity) }
|
||||
assistantView.setOnClickListener { navigator.startAssistantScreen() }
|
||||
assistantView.isVisible = activity.isAssistantAvailable
|
||||
|
||||
val color = iconColor
|
||||
listOf(notesView, talkView, moreView, assistantView).forEach { tintAppView(it, color) }
|
||||
|
||||
banner.visibility = View.VISIBLE
|
||||
}
|
||||
|
||||
private fun tintAppView(appView: LinearLayout, color: Int) {
|
||||
val imageView = appView.getChildAt(0) as ImageView
|
||||
imageView.imageTintList = ColorStateList.valueOf(color)
|
||||
(imageView.background as GradientDrawable).setStroke(ScreenMetrics.dpToPx(1f, activity), color)
|
||||
(appView.getChildAt(1) as TextView).setTextColor(color)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val APP_STORE_QUERY = "Nextcloud"
|
||||
private const val LIGHT_TONE_THRESHOLD = 80.0
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.header
|
||||
|
||||
import android.accounts.Account
|
||||
import android.graphics.Color
|
||||
import com.nextcloud.android.common.ui.util.PlatformThemeUtil
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.utils.theme.CapabilityUtils
|
||||
|
||||
class ServerBrandingColors(private val activity: DrawerActivity) {
|
||||
|
||||
val textColor: Int
|
||||
get() {
|
||||
val serverTextColor = CapabilityUtils.getCapability(activity).serverTextColor
|
||||
val fallbackColor = if (PlatformThemeUtil.isDarkMode(activity)) Color.WHITE else Color.BLACK
|
||||
return activity.colorUtil.getNullSafeColor(serverTextColor, fallbackColor)
|
||||
}
|
||||
|
||||
fun getPrimaryColor(account: Account): Int {
|
||||
val serverColor = CapabilityUtils.getCapability(account, activity).serverColor
|
||||
return activity.colorUtil.getNullSafeColor(serverColor, activity.getColor(R.color.primary))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.header
|
||||
|
||||
import android.content.res.Resources
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.drawable.BitmapDrawable
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.graphics.drawable.LayerDrawable
|
||||
import android.graphics.drawable.PictureDrawable
|
||||
import androidx.core.graphics.createBitmap
|
||||
import androidx.core.graphics.drawable.toDrawable
|
||||
import com.bumptech.glide.request.target.CustomTarget
|
||||
import com.bumptech.glide.request.transition.Transition
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.utils.BitmapUtils
|
||||
import kotlin.math.max
|
||||
|
||||
class ServerLogoTarget(
|
||||
private val resources: Resources,
|
||||
private val primaryColor: Int,
|
||||
private val onLogoReady: (LayerDrawable) -> Unit
|
||||
) : CustomTarget<Drawable>() {
|
||||
|
||||
override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
|
||||
val bitmap = resource.toLogoBitmap() ?: return
|
||||
val layers = arrayOf(primaryColor.toDrawable(), bitmap.scaledToLogoSize().toDrawable(resources))
|
||||
onLogoReady(LayerDrawable(layers))
|
||||
}
|
||||
|
||||
override fun onLoadCleared(placeholder: Drawable?) = Unit
|
||||
|
||||
private fun Drawable.toLogoBitmap(): Bitmap? = when (this) {
|
||||
is PictureDrawable -> createBitmap(intrinsicWidth, intrinsicHeight).also { Canvas(it).drawPicture(picture) }
|
||||
|
||||
is BitmapDrawable -> bitmap
|
||||
|
||||
else -> {
|
||||
Log_OC.e(TAG, "Unsupported drawable type: " + javaClass.name)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun Bitmap.scaledToLogoSize(): Bitmap {
|
||||
val maxDimension = max(width, height)
|
||||
if (maxDimension <= MAX_LOGO_SIZE_PX) return this
|
||||
return BitmapUtils.scaleBitmap(this, MAX_LOGO_SIZE_PX.toFloat(), width, height, maxDimension)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ServerLogoTarget"
|
||||
private const val MAX_LOGO_SIZE_PX = 1000
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.navigation
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.view.View
|
||||
import androidx.annotation.IdRes
|
||||
import androidx.core.net.toUri
|
||||
import com.nextcloud.client.files.DeepLinkConstants
|
||||
import com.nextcloud.utils.LinkHelper
|
||||
import com.nextcloud.utils.SnackbarUtil
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.navigation.NavigatorScreen
|
||||
|
||||
class DrawerDeepLinkHandler(
|
||||
private val activity: DrawerActivity,
|
||||
private val navigator: DrawerNavigator,
|
||||
private val menuItemClickHandler: DrawerMenuItemClickHandler
|
||||
) {
|
||||
|
||||
fun handle(uri: Uri) {
|
||||
val path = uri.lastPathSegment ?: return
|
||||
val deepLinkType = DeepLinkConstants.fromPath(path)
|
||||
if (deepLinkType == null) {
|
||||
SnackbarUtil.show(activity, activity.getString(R.string.invalid_url))
|
||||
return
|
||||
}
|
||||
|
||||
when (deepLinkType) {
|
||||
DeepLinkConstants.OPEN_AUTO_UPLOAD -> navigator.pushFragment(NavigatorScreen.AutoUpload)
|
||||
DeepLinkConstants.OPEN_EXTERNAL_URL -> openExternalUrl(uri)
|
||||
DeepLinkConstants.ACTION_CREATE_NEW -> activity.findViewById<View>(R.id.fab_main)?.callOnClick()
|
||||
DeepLinkConstants.ACTION_APP_UPDATE -> LinkHelper.openAppStore(activity.packageName, false, activity)
|
||||
DeepLinkConstants.OPEN_NOTIFICATIONS -> navigator.pushFragment(NavigatorScreen.Notifications)
|
||||
else -> openNavigationItem(deepLinkType.navId)
|
||||
}
|
||||
}
|
||||
|
||||
private fun openExternalUrl(uri: Uri) {
|
||||
val url = uri.getQueryParameter(URL_QUERY_PARAMETER) ?: return
|
||||
activity.startActivity(Intent(Intent.ACTION_VIEW, url.toUri()))
|
||||
}
|
||||
|
||||
private fun openNavigationItem(@IdRes menuItemId: Int) {
|
||||
val menuItem = activity.drawerNavigationView?.menu?.findItem(menuItemId) ?: return
|
||||
menuItemClickHandler.onNavigationItemClicked(menuItem)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val URL_QUERY_PARAMETER = "url"
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.navigation
|
||||
|
||||
import android.content.res.Resources
|
||||
import android.view.Menu
|
||||
import com.nextcloud.client.account.User
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.lib.resources.status.OCCapability
|
||||
import com.owncloud.android.utils.DrawerMenuUtil
|
||||
|
||||
object DrawerMenuFilter {
|
||||
|
||||
fun filter(menu: Menu, user: User, capability: OCCapability?, resources: Resources) {
|
||||
capability?.let {
|
||||
DrawerMenuUtil.filterTrashbinMenuItem(menu, it)
|
||||
DrawerMenuUtil.filterActivityMenuItem(menu, it)
|
||||
DrawerMenuUtil.filterGroupfoldersMenuItem(menu, it)
|
||||
DrawerMenuUtil.filterAssistantMenuItem(menu, it, resources)
|
||||
}
|
||||
|
||||
DrawerMenuUtil.filterSearchMenuItems(menu, user)
|
||||
DrawerMenuUtil.setupHomeMenuItem(menu, resources)
|
||||
DrawerMenuUtil.removeMenuItem(menu, R.id.nav_community, !resources.getBoolean(R.bool.participate_enabled))
|
||||
DrawerMenuUtil.removeMenuItem(menu, R.id.nav_shared, !resources.getBoolean(R.bool.shared_enabled))
|
||||
DrawerMenuUtil.removeMenuItem(menu, R.id.nav_logout, !resources.getBoolean(R.bool.show_drawer_logout))
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.navigation
|
||||
|
||||
import android.view.MenuItem
|
||||
import com.nextcloud.ui.composeActivity.ComposeActivity
|
||||
import com.nextcloud.utils.extensions.navigateToAllFiles
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.drawer.externallinks.DrawerExternalLinksMenu
|
||||
import com.owncloud.android.ui.events.ChangeMenuEvent
|
||||
import com.owncloud.android.ui.navigation.NavigatorScreen
|
||||
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
|
||||
import org.greenrobot.eventbus.EventBus
|
||||
|
||||
class DrawerMenuItemClickHandler(
|
||||
private val activity: DrawerActivity,
|
||||
private val navigator: DrawerNavigator,
|
||||
private val externalLinksMenu: DrawerExternalLinksMenu
|
||||
) {
|
||||
|
||||
fun onNavigationItemClicked(menuItem: MenuItem) {
|
||||
val itemId = menuItem.itemId
|
||||
when (itemId) {
|
||||
R.id.nav_all_files, R.id.nav_personal_files -> navigator.openAllFiles(itemId == R.id.nav_personal_files)
|
||||
R.id.nav_favorites -> navigator.openFavoritesTab()
|
||||
R.id.nav_gallery -> navigator.openMediaTab()
|
||||
R.id.nav_album -> navigator.openAlbums()
|
||||
R.id.nav_on_device -> navigator.showOnDeviceFiles()
|
||||
in navigatorScreensByMenuItemId -> navigatorScreensByMenuItemId[itemId]?.let(navigator::openNavigatorScreen)
|
||||
R.id.nav_settings -> navigator.openSettings()
|
||||
R.id.nav_logout -> navigator.openAccountRemovalDialog(menuItem)
|
||||
R.id.nav_shared -> navigator.openSharedTab()
|
||||
R.id.nav_recent_files -> navigator.openRecentFiles()
|
||||
R.id.nav_assistant -> navigator.openAssistant()
|
||||
R.id.nav_groupfolders -> navigator.openGroupfolders()
|
||||
else -> onOtherNavigationItemClicked(menuItem)
|
||||
}
|
||||
|
||||
activity.ocFileListFragment?.resetFileDepth()
|
||||
activity.highlightNavigationViewItem(itemId)
|
||||
}
|
||||
|
||||
@SuppressFBWarnings("RV")
|
||||
fun onBottomNavigationItemSelected(menuItem: MenuItem): Boolean {
|
||||
val itemId = menuItem.itemId
|
||||
activity.ocFileListFragment?.exitSelectionMode()
|
||||
navigator.resetOnlyPersonalAndOnDevice()
|
||||
|
||||
when (itemId) {
|
||||
R.id.nav_all_files -> {
|
||||
activity.navigateToAllFiles()
|
||||
EventBus.getDefault().post(ChangeMenuEvent())
|
||||
}
|
||||
|
||||
R.id.nav_favorites -> navigator.openFavoritesTab()
|
||||
|
||||
R.id.nav_assistant -> if (activity !is ComposeActivity) navigator.startAssistantScreen()
|
||||
|
||||
R.id.nav_gallery -> navigator.openMediaTab()
|
||||
|
||||
R.id.nav_album -> navigator.replaceAlbumFragment()
|
||||
}
|
||||
|
||||
activity.supportActionBar?.setIcon(null)
|
||||
activity.ocFileListFragment?.resetFileDepth()
|
||||
activity.highlightNavigationViewItem(itemId)
|
||||
return false
|
||||
}
|
||||
|
||||
private fun onOtherNavigationItemClicked(menuItem: MenuItem) {
|
||||
if (menuItem.groupId == R.id.drawer_menu_external_links) {
|
||||
externalLinksMenu.onExternalLinkClicked(menuItem)
|
||||
return
|
||||
}
|
||||
Log_OC.w(TAG, "Unknown drawer menu item clicked: " + menuItem.title)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DrawerMenuItemClickHandler"
|
||||
|
||||
private val navigatorScreensByMenuItemId: Map<Int, NavigatorScreen> by lazy {
|
||||
mapOf(
|
||||
R.id.nav_uploads to NavigatorScreen.UploadList,
|
||||
R.id.nav_trashbin to NavigatorScreen.Trashbin,
|
||||
R.id.nav_activity to NavigatorScreen.Activities,
|
||||
R.id.nav_community to NavigatorScreen.Community
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.navigation
|
||||
|
||||
import android.content.Intent
|
||||
import android.view.MenuItem
|
||||
import androidx.fragment.app.commit
|
||||
import com.nextcloud.ui.composeActivity.ComposeActivity
|
||||
import com.nextcloud.ui.composeActivity.ComposeDestination
|
||||
import com.nextcloud.utils.extensions.navigateToAllFiles
|
||||
import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.lib.resources.files.SearchRemoteOperation
|
||||
import com.owncloud.android.ui.activity.FileDisplayActivity
|
||||
import com.owncloud.android.ui.activity.SettingsActivity
|
||||
import com.owncloud.android.ui.activity.UserInfoActivity
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.events.ChangeMenuEvent
|
||||
import com.owncloud.android.ui.events.SearchEvent
|
||||
import com.owncloud.android.ui.fragment.GalleryFragment
|
||||
import com.owncloud.android.ui.fragment.OCFileListFragment
|
||||
import com.owncloud.android.ui.fragment.albums.AlbumsFragment
|
||||
import com.owncloud.android.ui.navigation.NavigatorActivity
|
||||
import com.owncloud.android.ui.navigation.NavigatorScreen
|
||||
import com.owncloud.android.ui.navigation.model.ActionBarStyle
|
||||
import org.greenrobot.eventbus.EventBus
|
||||
import kotlin.jvm.optionals.getOrNull
|
||||
|
||||
class DrawerNavigator(private val activity: DrawerActivity) {
|
||||
|
||||
fun pushFragment(screen: NavigatorScreen) {
|
||||
if (activity is NavigatorActivity) {
|
||||
activity.push(screen)
|
||||
return
|
||||
}
|
||||
activity.startActivity(NavigatorActivity.intent(activity, screen))
|
||||
}
|
||||
|
||||
fun startPhotoSearch() {
|
||||
MainApp.showOnlyFilesOnDevice(false)
|
||||
launchActivityForSearch(SearchEvent(PHOTO_SEARCH_MIME_TYPE, SearchRemoteOperation.SearchType.PHOTO_SEARCH))
|
||||
}
|
||||
|
||||
fun showFiles(onDeviceOnly: Boolean, onlyPersonalFiles: Boolean) {
|
||||
MainApp.showOnlyFilesOnDevice(onDeviceOnly)
|
||||
MainApp.showOnlyPersonalFiles(onlyPersonalFiles)
|
||||
activity.startActivity(fileDisplayActivityIntent(FileDisplayActivity.ALL_FILES))
|
||||
}
|
||||
|
||||
fun showOnDeviceFiles() {
|
||||
MainApp.showOnlyFilesOnDevice(true)
|
||||
MainApp.showOnlyPersonalFiles(false)
|
||||
activity.startActivity(fileDisplayActivityIntent(FileDisplayActivity.ON_DEVICE))
|
||||
}
|
||||
|
||||
fun replaceAlbumFragment() {
|
||||
if (activity.isAlbumsFragment) return
|
||||
activity.supportFragmentManager.commit {
|
||||
addToBackStack(null)
|
||||
replace(R.id.left_fragment_container, AlbumsFragment.newInstance(false), AlbumsFragment.TAG)
|
||||
}
|
||||
}
|
||||
|
||||
fun restartFileDisplayActivity() {
|
||||
activity.startActivity(fileDisplayActivityIntent(FileDisplayActivity.RESTART))
|
||||
}
|
||||
|
||||
fun openAllFiles(onlyPersonal: Boolean) {
|
||||
activity.closeDrawer()
|
||||
activity.navigateToAllFiles(onlyPersonal)
|
||||
EventBus.getDefault().post(ChangeMenuEvent())
|
||||
}
|
||||
|
||||
fun openFavoritesTab() {
|
||||
resetOnlyPersonalAndOnDevice()
|
||||
activity.showActionBar(ActionBarStyle.Plain)
|
||||
launchActivityForSearch(SearchEvent("", SearchRemoteOperation.SearchType.FAVORITE_SEARCH))
|
||||
}
|
||||
|
||||
fun openMediaTab() {
|
||||
GalleryFragment.clearSavedViewState()
|
||||
resetOnlyPersonalAndOnDevice()
|
||||
activity.showActionBar(ActionBarStyle.Plain)
|
||||
startPhotoSearch()
|
||||
}
|
||||
|
||||
fun openAlbums() {
|
||||
if (activity is FileDisplayActivity) {
|
||||
replaceAlbumFragment()
|
||||
} else {
|
||||
activity.startActivity(fileDisplayActivityIntent(FileDisplayActivity.ALBUMS))
|
||||
}
|
||||
}
|
||||
|
||||
fun openNavigatorScreen(screen: NavigatorScreen) {
|
||||
resetOnlyPersonalAndOnDevice()
|
||||
pushFragment(screen)
|
||||
}
|
||||
|
||||
fun openSettings() {
|
||||
resetOnlyPersonalAndOnDevice()
|
||||
activity.startActivity(Intent(activity, SettingsActivity::class.java))
|
||||
}
|
||||
|
||||
fun openAccountRemovalDialog(menuItem: MenuItem) {
|
||||
resetOnlyPersonalAndOnDevice()
|
||||
val uncheckedMenuItem = menuItem.setChecked(false)
|
||||
Log_OC.d(TAG, "onNavigationItemClicked nav_logout setChecked $uncheckedMenuItem")
|
||||
activity.user.getOrNull()?.let {
|
||||
UserInfoActivity.openAccountRemovalDialog(it, activity.supportFragmentManager)
|
||||
}
|
||||
}
|
||||
|
||||
fun openSharedTab() {
|
||||
resetOnlyPersonalAndOnDevice()
|
||||
launchActivityForSearch(SearchEvent("", SearchRemoteOperation.SearchType.SHARED_FILTER))
|
||||
}
|
||||
|
||||
fun openRecentFiles() {
|
||||
resetOnlyPersonalAndOnDevice()
|
||||
launchActivityForSearch(SearchEvent("", SearchRemoteOperation.SearchType.RECENTLY_MODIFIED_SEARCH))
|
||||
}
|
||||
|
||||
fun openAssistant() {
|
||||
resetOnlyPersonalAndOnDevice()
|
||||
startAssistantScreen()
|
||||
}
|
||||
|
||||
fun openGroupfolders() {
|
||||
resetOnlyPersonalAndOnDevice()
|
||||
activity.startActivity(fileDisplayActivityIntent(FileDisplayActivity.LIST_GROUPFOLDERS))
|
||||
}
|
||||
|
||||
fun startAssistantScreen() {
|
||||
val intent = Intent(activity.applicationContext, ComposeActivity::class.java)
|
||||
.putExtra(ComposeActivity.DESTINATION, ComposeDestination.getAssistantScreen(activity))
|
||||
activity.startActivity(intent)
|
||||
}
|
||||
|
||||
fun resetOnlyPersonalAndOnDevice() {
|
||||
MainApp.showOnlyFilesOnDevice(false)
|
||||
MainApp.showOnlyPersonalFiles(false)
|
||||
}
|
||||
|
||||
private fun launchActivityForSearch(searchEvent: SearchEvent) {
|
||||
val intent = fileDisplayActivityIntent(Intent.ACTION_SEARCH)
|
||||
.putExtra(OCFileListFragment.SEARCH_EVENT, searchEvent)
|
||||
activity.startActivity(intent)
|
||||
}
|
||||
|
||||
private fun fileDisplayActivityIntent(action: String): Intent =
|
||||
Intent(activity.applicationContext, FileDisplayActivity::class.java).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
this.action = action
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DrawerNavigator"
|
||||
private const val PHOTO_SEARCH_MIME_TYPE = "image/%"
|
||||
}
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.quota
|
||||
|
||||
import android.view.View
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.annotation.IdRes
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.google.android.material.navigation.NavigationView
|
||||
import com.google.android.material.progressindicator.LinearProgressIndicator
|
||||
import com.nextcloud.android.common.ui.theme.utils.ColorRole
|
||||
import com.nextcloud.utils.GlideHelper
|
||||
import com.nextcloud.utils.HumanReadableFormatter
|
||||
import com.nextcloud.utils.mdm.MDMConfig
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.lib.common.ExternalLink
|
||||
import com.owncloud.android.lib.common.ExternalLinkType
|
||||
import com.owncloud.android.lib.common.Quota
|
||||
import com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.drawer.externallinks.ExternalLinkOpener
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class DrawerQuotaController(private val activity: DrawerActivity, private val externalLinkOpener: ExternalLinkOpener) {
|
||||
private val quotaFetcher = UserQuotaFetcher(activity)
|
||||
|
||||
private var quotaView: LinearLayout? = null
|
||||
private var quotaProgressBar: LinearProgressIndicator? = null
|
||||
private var quotaTextPercentage: TextView? = null
|
||||
private var quotaTextLink: TextView? = null
|
||||
|
||||
private val Quota.isDisplayable: Boolean
|
||||
get() = quota > 0 ||
|
||||
quota == GetUserInfoRemoteOperation.SPACE_UNLIMITED ||
|
||||
quota == GetUserInfoRemoteOperation.QUOTA_LIMIT_INFO_NOT_AVAILABLE
|
||||
|
||||
fun setupViews(navigationView: NavigationView) {
|
||||
quotaView = findQuotaViewById(navigationView, R.id.drawer_quota)
|
||||
quotaProgressBar = findQuotaViewById(navigationView, R.id.drawer_quota_ProgressBar)
|
||||
quotaTextPercentage = findQuotaViewById(navigationView, R.id.drawer_quota_percentage)
|
||||
quotaTextLink = findQuotaViewById(navigationView, R.id.drawer_quota_link)
|
||||
|
||||
quotaProgressBar?.let {
|
||||
activity.viewThemeUtils.material.colorProgressBar(it, ColorRole.PRIMARY)
|
||||
it.trackStopIndicatorSize = 0
|
||||
}
|
||||
quotaView?.let { activity.viewThemeUtils.platform.colorViewBackground(it) }
|
||||
}
|
||||
|
||||
fun fetchAndDisplay() {
|
||||
activity.lifecycleScope.launch {
|
||||
val quota = quotaFetcher.fetch() ?: return@launch
|
||||
if (quota.isDisplayable) {
|
||||
showQuotaInformation(quota)
|
||||
} else {
|
||||
quotaView?.isVisible = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun updateQuotaLink() {
|
||||
val quotaTextLink = quotaTextLink ?: return
|
||||
if (!MDMConfig.externalSiteSupport(activity)) {
|
||||
quotaTextLink.visibility = View.GONE
|
||||
return
|
||||
}
|
||||
|
||||
activity.externalLinksProvider.getExternalLink(ExternalLinkType.QUOTA) { quotas ->
|
||||
val firstQuota = quotas.firstOrNull()
|
||||
if (firstQuota == null) {
|
||||
quotaTextLink.visibility = View.GONE
|
||||
} else {
|
||||
showQuotaLink(quotaTextLink, firstQuota)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun <T : View> findQuotaViewById(navigationView: NavigationView, @IdRes id: Int): T? =
|
||||
navigationView.getHeaderView(0)?.findViewById(id) ?: activity.findViewById(id)
|
||||
|
||||
private fun showQuotaInformation(quota: Quota) {
|
||||
quotaTextPercentage?.text = if (quota.quota == GetUserInfoRemoteOperation.SPACE_UNLIMITED) {
|
||||
activity.getString(R.string.drawer_quota_unlimited, HumanReadableFormatter.formatBytes(quota.used))
|
||||
} else {
|
||||
activity.getString(
|
||||
R.string.drawer_quota,
|
||||
HumanReadableFormatter.formatBytes(quota.used),
|
||||
HumanReadableFormatter.formatBytes(quota.total)
|
||||
)
|
||||
}
|
||||
|
||||
val relative = ceil(quota.relative).toInt()
|
||||
quotaProgressBar?.let { progressBar ->
|
||||
progressBar.progress = relative
|
||||
if (relative < RELATIVE_THRESHOLD_WARNING) {
|
||||
activity.viewThemeUtils.material.colorProgressBar(progressBar, ColorRole.PRIMARY)
|
||||
} else {
|
||||
activity.viewThemeUtils.material.colorProgressBar(
|
||||
progressBar,
|
||||
activity.resources.getColor(R.color.infolevel_warning, null)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
updateQuotaLink()
|
||||
quotaView?.isVisible = true
|
||||
}
|
||||
|
||||
private fun showQuotaLink(quotaTextLink: TextView, quota: ExternalLink) {
|
||||
quotaTextLink.text = quota.name
|
||||
quotaTextLink.isClickable = true
|
||||
quotaTextLink.visibility = View.VISIBLE
|
||||
quotaTextLink.setOnClickListener { externalLinkOpener.openInWebView(quota) }
|
||||
|
||||
val iconSize = (LINK_ICON_SIZE_DP * activity.resources.displayMetrics.density).roundToInt()
|
||||
GlideHelper.loadIntoTarget(
|
||||
activity,
|
||||
activity.userAccountManager.currentOwnCloudAccount,
|
||||
quota.iconUrl,
|
||||
QuotaLinkIconTarget(iconSize, quotaTextLink),
|
||||
R.drawable.ic_link
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val RELATIVE_THRESHOLD_WARNING = 80
|
||||
private const val LINK_ICON_SIZE_DP = 24
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.quota
|
||||
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.widget.TextView
|
||||
import com.bumptech.glide.request.target.CustomTarget
|
||||
import com.bumptech.glide.request.transition.Transition
|
||||
|
||||
class QuotaLinkIconTarget(private val iconSize: Int, private val quotaTextLink: TextView) :
|
||||
CustomTarget<Drawable>() {
|
||||
|
||||
override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
|
||||
setIcon(resource)
|
||||
}
|
||||
|
||||
override fun onLoadCleared(placeholder: Drawable?) = Unit
|
||||
|
||||
override fun onLoadFailed(errorDrawable: Drawable?) {
|
||||
super.onLoadFailed(errorDrawable)
|
||||
errorDrawable?.let(::setIcon)
|
||||
}
|
||||
|
||||
private fun setIcon(drawable: Drawable) {
|
||||
val icon = drawable.current.apply { setBounds(0, 0, iconSize, iconSize) }
|
||||
quotaTextLink.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.activity.drawer.quota
|
||||
|
||||
import com.owncloud.android.lib.common.Quota
|
||||
import com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation
|
||||
import com.owncloud.android.ui.activity.BaseActivity
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class UserQuotaFetcher(private val activity: BaseActivity) {
|
||||
|
||||
suspend fun fetch(): Quota? = withContext(Dispatchers.IO) {
|
||||
if (activity.userAccountManager.user.isAnonymous) return@withContext null
|
||||
val client = activity.clientRepository.getNextcloudClient() ?: return@withContext null
|
||||
val result = GetUserInfoRemoteOperation().execute(client)
|
||||
if (result.isSuccess) result.resultData?.quota else null
|
||||
}
|
||||
}
|
||||
@@ -387,7 +387,8 @@ class GalleryAdapter(
|
||||
directory: OCFile,
|
||||
storageManager: FileDataStorageManager,
|
||||
onlyOnDevice: Boolean,
|
||||
mLimitToMimeType: String
|
||||
mLimitToMimeType: String,
|
||||
onSwapped: () -> Unit
|
||||
) = Unit
|
||||
|
||||
override fun setHighlightedItem(file: OCFile) = Unit
|
||||
|
||||
+2
-1
@@ -21,7 +21,8 @@ interface CommonOCFileListAdapterInterface {
|
||||
directory: OCFile,
|
||||
storageManager: FileDataStorageManager,
|
||||
onlyOnDevice: Boolean,
|
||||
mLimitToMimeType: String
|
||||
mLimitToMimeType: String,
|
||||
onSwapped: () -> Unit = {}
|
||||
)
|
||||
|
||||
fun setHighlightedItem(file: OCFile)
|
||||
|
||||
@@ -91,7 +91,7 @@ class OCFileListAdapter(
|
||||
transferServiceGetter: ComponentsGetter,
|
||||
ocFileListFragmentInterface: OCFileListFragmentInterface,
|
||||
private val hideItemOptions: Boolean,
|
||||
private var gridView: Boolean,
|
||||
gridView: Boolean,
|
||||
viewThemeUtils: ViewThemeUtils,
|
||||
private val thumbnailGenerator: ThumbnailGenerator,
|
||||
avatarGenerator: AvatarGenerator
|
||||
@@ -208,7 +208,7 @@ class OCFileListAdapter(
|
||||
|
||||
OCFileListViewType.HEADER -> OCFileListHeaderViewHolder(ListHeaderBinding.inflate(inflater, parent, false))
|
||||
|
||||
OCFileListViewType.ITEM, OCFileListViewType.IMAGE -> if (gridView) {
|
||||
OCFileListViewType.ITEM, OCFileListViewType.IMAGE -> if (ocFileListDelegate.gridView) {
|
||||
OCFileListGridItemViewHolder(GridItemBinding.inflate(inflater, parent, false))
|
||||
} else {
|
||||
OCFileListItemViewHolder(ListItemBinding.inflate(inflater, parent, false))
|
||||
@@ -279,7 +279,8 @@ class OCFileListAdapter(
|
||||
directory: OCFile,
|
||||
storageManager: FileDataStorageManager,
|
||||
onlyOnDevice: Boolean,
|
||||
mLimitToMimeType: String
|
||||
mLimitToMimeType: String,
|
||||
onSwapped: () -> Unit
|
||||
) {
|
||||
this.onlyOnDevice = onlyOnDevice
|
||||
|
||||
@@ -300,7 +301,7 @@ class OCFileListAdapter(
|
||||
preferences,
|
||||
accountUserId
|
||||
) { newList, _ ->
|
||||
updateAdapter(newList, directory)
|
||||
updateAdapter(newList, directory, onSwapped)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -388,7 +389,7 @@ class OCFileListAdapter(
|
||||
)
|
||||
}
|
||||
|
||||
fun updateAdapter(newFiles: List<OCFile>, directory: OCFile?) {
|
||||
fun updateAdapter(newFiles: List<OCFile>, directory: OCFile?, onUpdated: () -> Unit = {}) {
|
||||
Log_OC.d(TAG, "updating the adapter")
|
||||
|
||||
allFiles.clear()
|
||||
@@ -408,8 +409,10 @@ class OCFileListAdapter(
|
||||
if (isSameDirectoryRefresh) {
|
||||
differ.submitAndRebind(files)
|
||||
} else {
|
||||
differ.replace(files)
|
||||
differ.replaceWithoutAnimation(files)
|
||||
}
|
||||
|
||||
onUpdated()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -570,7 +573,7 @@ class OCFileListAdapter(
|
||||
}
|
||||
|
||||
fun setGridView(bool: Boolean) {
|
||||
gridView = bool
|
||||
ocFileListDelegate.gridView = bool
|
||||
}
|
||||
|
||||
fun setShowMetadata(bool: Boolean) {
|
||||
@@ -639,7 +642,7 @@ class OCFileListAdapter(
|
||||
holder.fileFeaturesLayout?.setVisibleIf(holder.hasVisibleFeatureIndicators)
|
||||
}
|
||||
|
||||
private fun shouldShowItemOptions(): Boolean = !(isMultiSelect() || gridView || hideItemOptions)
|
||||
private fun shouldShowItemOptions(): Boolean = !(isMultiSelect() || ocFileListDelegate.gridView || hideItemOptions)
|
||||
|
||||
private fun bindMoreOptionsVisibility(holder: ListViewHolder) {
|
||||
val showMoreOptions = !isMultiSelect() && !OCFileListFragment.isMultipleFileSelectedForCopyOrMove
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
package com.owncloud.android.ui.adapter.filelist.data
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import androidx.core.view.doOnNextLayout
|
||||
import androidx.recyclerview.widget.AsyncDifferConfig
|
||||
import androidx.recyclerview.widget.AsyncListDiffer
|
||||
import androidx.recyclerview.widget.ListUpdateCallback
|
||||
@@ -94,6 +95,11 @@ class OCFileListDiffer(
|
||||
adapter.notifyDataSetChanged()
|
||||
}
|
||||
|
||||
fun replaceWithoutAnimation(newFiles: List<OCFile>) {
|
||||
suppressItemAnimationsUntilNextLayout()
|
||||
replace(newFiles)
|
||||
}
|
||||
|
||||
fun sortForCurrentView(
|
||||
files: MutableList<OCFile>,
|
||||
searchType: SearchType?,
|
||||
@@ -141,6 +147,13 @@ class OCFileListDiffer(
|
||||
recyclerView = null
|
||||
}
|
||||
|
||||
private fun suppressItemAnimationsUntilNextLayout() {
|
||||
val recyclerView = recyclerView ?: return
|
||||
val itemAnimator = recyclerView.itemAnimator ?: return
|
||||
recyclerView.itemAnimator = null
|
||||
recyclerView.doOnNextLayout { recyclerView.itemAnimator = itemAnimator }
|
||||
}
|
||||
|
||||
private fun keepTopVisibleWhile(adapterPosition: Int, notify: () -> Unit) {
|
||||
val wasAtTop = adapterPosition == 0 && recyclerView?.canScrollVertically(-1) == false
|
||||
notify()
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ import com.owncloud.android.databinding.ListHeaderBinding
|
||||
import com.owncloud.android.databinding.ListHeaderOpenInBinding
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.lib.resources.status.OCCapability
|
||||
import com.owncloud.android.ui.activity.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.adapter.filelist.recommended.RecommendedFilesAdapter
|
||||
import com.owncloud.android.ui.interfaces.OCFileListFragmentInterface
|
||||
import com.owncloud.android.ui.preview.text.PreviewTextFragment
|
||||
|
||||
+1
-1
@@ -63,7 +63,7 @@ class OCFileListDelegate(
|
||||
private val user: User,
|
||||
private val storageManager: FileDataStorageManager,
|
||||
private val hideItemOptions: Boolean,
|
||||
private val gridView: Boolean,
|
||||
var gridView: Boolean,
|
||||
private val transferServiceGetter: ComponentsGetter,
|
||||
private val showMetadata: Boolean,
|
||||
private var showShareAvatar: Boolean,
|
||||
|
||||
+2
-2
@@ -14,8 +14,8 @@ import com.nextcloud.utils.extensions.openMediaPermissions
|
||||
import com.nextcloud.utils.extensions.setVisibleIf
|
||||
import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.databinding.StoragePermissionWarningBannerBinding
|
||||
import com.owncloud.android.ui.activity.DrawerActivity.REQ_ALL_FILES_ACCESS
|
||||
import com.owncloud.android.ui.activity.DrawerActivity.REQ_MEDIA_ACCESS
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity.Companion.REQ_ALL_FILES_ACCESS
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity.Companion.REQ_MEDIA_ACCESS
|
||||
import com.owncloud.android.utils.PermissionUtil
|
||||
|
||||
fun StoragePermissionWarningBannerBinding.setup(activity: Activity, descriptionId: Int) {
|
||||
|
||||
@@ -42,7 +42,7 @@ import com.owncloud.android.datamodel.UploadsStorageManager
|
||||
import com.owncloud.android.db.OCUpload
|
||||
import com.owncloud.android.db.UploadResult
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.ui.activity.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.adapter.progressListener.UploadProgressListener
|
||||
import com.owncloud.android.ui.adapter.uploadList.helper.UploadListAdapterHelper
|
||||
import com.owncloud.android.ui.adapter.uploadList.helper.UploadListItemOnClick
|
||||
@@ -76,6 +76,7 @@ class UploadListAdapter(
|
||||
) : SectionedRecyclerViewAdapter<SectionedViewHolder>() {
|
||||
|
||||
private val uploadListSections = UploadListSection.sections()
|
||||
private var latestLoadId = 0
|
||||
private val showUser: Boolean = accountManager.getAccounts().size > 1
|
||||
private val uploadHelper = FileUploadHelper.instance()
|
||||
private var uploadProgressListener: UploadProgressListener? = null
|
||||
@@ -559,6 +560,7 @@ class UploadListAdapter(
|
||||
|
||||
val accountName = optionalUser.get().accountName
|
||||
val capabilities = optionalCapabilities.get()
|
||||
val loadId = ++latestLoadId
|
||||
|
||||
activity.lifecycleScope.launch(Dispatchers.IO) {
|
||||
val succeededUploads = uploadHelper.getUploadsByStatus(
|
||||
@@ -578,6 +580,11 @@ class UploadListAdapter(
|
||||
}
|
||||
|
||||
withContext(Dispatchers.Main) {
|
||||
if (loadId != latestLoadId) {
|
||||
onCompleted.run()
|
||||
return@withContext
|
||||
}
|
||||
|
||||
for (i in uploadListSections.indices) {
|
||||
uploadListSections[i] = updatedSections[i]
|
||||
}
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.db.OCUpload
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.ui.activity.ConflictsResolveActivity
|
||||
import com.owncloud.android.ui.activity.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.drawer.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.FileDisplayActivity
|
||||
import com.owncloud.android.ui.preview.media.PreviewMediaFragment
|
||||
import com.owncloud.android.utils.MimeType
|
||||
|
||||
@@ -62,8 +62,6 @@ import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.databinding.ListFragmentBinding
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.lib.resources.files.SearchRemoteOperation
|
||||
import com.owncloud.android.lib.resources.status.OwnCloudVersion
|
||||
import com.owncloud.android.ui.EmptyRecyclerView
|
||||
import com.owncloud.android.ui.activity.FileDisplayActivity
|
||||
import com.owncloud.android.ui.activity.FolderPickerActivity
|
||||
@@ -71,9 +69,7 @@ import com.owncloud.android.ui.activity.OnEnforceableRefreshListener
|
||||
import com.owncloud.android.ui.activity.UploadFilesActivity
|
||||
import com.owncloud.android.ui.adapter.localFileList.LocalFileListAdapter
|
||||
import com.owncloud.android.ui.adapter.filelist.OCFileListAdapter
|
||||
import com.owncloud.android.ui.events.SearchEvent
|
||||
import com.owncloud.android.utils.theme.ViewThemeUtils
|
||||
import org.greenrobot.eventbus.EventBus
|
||||
import javax.inject.Inject
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
@@ -199,7 +195,7 @@ open class ExtendedListFragment :
|
||||
if (activity is FileDisplayActivity) {
|
||||
val fragment = activity.leftFragment
|
||||
if (fragment is OCFileListFragment) {
|
||||
fragment.setFabVisible(!hasFocus)
|
||||
if (hasFocus) fragment.setFabState(FabState.HIDDEN) else fragment.updateFabState()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,18 +256,7 @@ open class ExtendedListFragment :
|
||||
} else {
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
if (adapter is OCFileListAdapter) {
|
||||
if (accountManager
|
||||
.user
|
||||
.server
|
||||
.version
|
||||
.isNewerOrEqual(OwnCloudVersion.nextcloud_20)
|
||||
) {
|
||||
activity.performUnifiedSearch(query, listOfHiddenFiles)
|
||||
} else {
|
||||
EventBus.getDefault().post(
|
||||
SearchEvent(query, SearchRemoteOperation.SearchType.FILE_SEARCH)
|
||||
)
|
||||
}
|
||||
activity.performUnifiedSearch(query, listOfHiddenFiles)
|
||||
} else if (adapter is LocalFileListAdapter) {
|
||||
adapter.filter(query)
|
||||
}
|
||||
|
||||
Loaded 100 of 165 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user