Compare commits
131
Commits
patchMethod
..
ff
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c32af9ffa | ||
|
|
e72fc522bd | ||
|
|
4e359c778d | ||
|
|
1c7a39e407 | ||
|
|
f2c313768c | ||
|
|
661048d53c | ||
|
|
589b9d7d9f | ||
|
|
ae2846d928 | ||
|
|
bf2ea03d2f | ||
|
|
e9dc26070b | ||
|
|
0a42dc7952 | ||
|
|
27c97bc773 | ||
|
|
66b26040ef | ||
|
|
49890e77df | ||
|
|
d4b4254710 | ||
|
|
612e5e1a83 | ||
|
|
cbedadcabe | ||
|
|
f67862cba8 | ||
|
|
27a2e88e41 | ||
|
|
4c5ee6e104 | ||
|
|
16195c57a7 | ||
|
|
a9b5dc86dc | ||
|
|
682dd708c0 | ||
|
|
4eaecf72c9 | ||
|
|
6635afa01a | ||
|
|
549b455c49 | ||
|
|
7ecd74b7de | ||
|
|
3565c27ee2 | ||
|
|
4af7b86b5b | ||
|
|
378dbbf752 | ||
|
|
55f3275e84 | ||
|
|
3ab1163d8e | ||
|
|
6dcf4f1029 | ||
|
|
92aae7f31d | ||
|
|
1889cd7fe1 | ||
|
|
62353b1067 | ||
|
|
35d10fce29 | ||
|
|
00cc8194db | ||
|
|
89848fd104 | ||
|
|
dd405080a3 | ||
|
|
b0522e1103 | ||
|
|
2848589c5f | ||
|
|
69b9452eae | ||
|
|
d0ac88bc59 | ||
|
|
676d10c436 | ||
|
|
2e710fad05 | ||
|
|
869f64cdef | ||
|
|
857802d505 | ||
|
|
c62ffddd75 | ||
|
|
9e4ea8fa3a | ||
|
|
57867bcef0 | ||
|
|
42daa4029d | ||
|
|
73942bd401 | ||
|
|
b4e52b0b2d | ||
|
|
0e6f073363 | ||
|
|
4e3abe0b7b | ||
|
|
e387317280 | ||
|
|
9ce1ee8747 | ||
|
|
9602b409f3 | ||
|
|
2391368ab0 | ||
|
|
4e7699dd9f | ||
|
|
1965ad192f | ||
|
|
2493285d76 | ||
|
|
6ede6d617b | ||
|
|
3296f9945f | ||
|
|
08ef1b3982 | ||
|
|
78a17b7fca | ||
|
|
c136c2e7b0 | ||
|
|
3006898c07 | ||
|
|
08548923ff | ||
|
|
549fd05eaa | ||
|
|
567eefa484 | ||
|
|
ea25524542 | ||
|
|
6921155e35 | ||
|
|
978c574ead | ||
|
|
33feff4c79 | ||
|
|
d608d9c903 | ||
|
|
fa54e8aa13 | ||
|
|
667ab2949d | ||
|
|
6e728c53f9 | ||
|
|
7f10f801b4 | ||
|
|
261490a2cc | ||
|
|
69217bd118 | ||
|
|
13bacfe59a | ||
|
|
a5c2b2f875 | ||
|
|
8d4bfeff9f | ||
|
|
90ebd53227 | ||
|
|
04bd74ac09 | ||
|
|
104d1e6663 | ||
|
|
04aec3f7c8 | ||
|
|
f5814b9822 | ||
|
|
0710c82101 | ||
|
|
e8b0d378f3 | ||
|
|
cd4c43ce82 | ||
|
|
d384dc5a43 | ||
|
|
f7c1f921bb | ||
|
|
d31db26d00 | ||
|
|
dff8ee60a3 | ||
|
|
9be50ef142 | ||
|
|
3a8bbd0ebb | ||
|
|
0dbaf81dbb | ||
|
|
d9d0f88bce | ||
|
|
0f7ce1e33f | ||
|
|
4c80d1c5c3 | ||
|
|
ed4b7addff | ||
|
|
300b499a10 | ||
|
|
6fa1ed5c3d | ||
|
|
dfddbf0e07 | ||
|
|
24053b5bd9 | ||
|
|
bc3b4218a1 | ||
|
|
9a2a313b8f | ||
|
|
fdbe3822c5 | ||
|
|
b5a3e6be29 | ||
|
|
a5c7b87bf1 | ||
|
|
e89141a714 | ||
|
|
dc3b8c6918 | ||
|
|
54dd53c6ff | ||
|
|
96f6cc3a43 | ||
|
|
9d0740294c | ||
|
|
4fe9328b4c | ||
|
|
349c1bc919 | ||
|
|
e69f2976a0 | ||
|
|
dd87b213d7 | ||
|
|
96debdd3a5 | ||
|
|
bdc9bb1829 | ||
|
|
07c09e1e99 | ||
|
|
5fd2e2942c | ||
|
|
2bb71c8b89 | ||
|
|
64f79d8462 | ||
|
|
7a1ac3b3bf | ||
|
|
a9a00f0619 |
No files matched your search
+2
-2
@@ -148,7 +148,7 @@ steps:
|
||||
commands:
|
||||
- emulator -avd android -no-snapshot -gpu swiftshader_indirect -no-window -no-audio -skin 500x833 &
|
||||
- sed -i s'#<bool name="is_beta">false</bool>#<bool name="is_beta">true</bool>#'g app/src/main/res/values/setup.xml
|
||||
- sed -i s'#showOnlyFailingTestsInReports = ciBuild#showOnlyFailingTestsInReports = false#' build.gradle
|
||||
- sed -i s'#showOnlyFailingTestsInReports = ciBuild#showOnlyFailingTestsInReports = false#' build.gradle.kts
|
||||
- scripts/wait_for_emulator.sh
|
||||
- scripts/runAllScreenshotCombinations noCI false
|
||||
- scripts/screenshotSummary.sh
|
||||
@@ -185,6 +185,6 @@ name: GIT_TOKEN
|
||||
data: XIoa9IYq+xQ+N5iln8dlpWv0jV6ROr7HuE24ioUr4uQ8m8SjyH0yognWYLYLqnbTKrFWlFZiEMQTH/sZiWjRFvV1iL0=
|
||||
---
|
||||
kind: signature
|
||||
hmac: ea9432c9317fa6ca12a282bb117c9f3268ddb29b208dbd772795ba19cf395082
|
||||
hmac: b4568fe767026f67cca8c416c20cc522fd1d06941c836ca7eb4955682855d237
|
||||
|
||||
...
|
||||
@@ -73,6 +73,7 @@ jobs:
|
||||
{
|
||||
echo "org.gradle.jvmargs=-Xmx5g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g"
|
||||
echo "org.gradle.configureondemand=true"
|
||||
echo "org.gradle.configuration-cache=false"
|
||||
echo "kapt.incremental.apt=true"
|
||||
} > "$HOME/.gradle/gradle.properties"
|
||||
scripts/analysis/analysis-wrapper.sh "${{ steps.get-vars.outputs.branch }}" "${{ secrets.LOG_USERNAME }}" "${{ secrets.LOG_PASSWORD }}" "$GITHUB_RUN_NUMBER" "${{ steps.get-vars.outputs.pr }}"
|
||||
@@ -20,7 +20,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
task: [ detekt, spotlessKotlinCheck ]
|
||||
task: [ detekt, spotlessKotlinCheck, lint ]
|
||||
steps:
|
||||
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
- name: Set up JDK 17
|
||||
|
||||
@@ -43,7 +43,7 @@ jobs:
|
||||
with:
|
||||
swap-size-gb: 10
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@4e94bd11f71e507f7f87df81788dff88d1dacbfb # v4.31.0
|
||||
uses: github/codeql-action/init@0499de31b99561a6d14a36a5f662c2a54f91beee # v4.31.2
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
- name: Set up JDK 17
|
||||
@@ -57,4 +57,4 @@ jobs:
|
||||
echo "org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError" > "$HOME/.gradle/gradle.properties"
|
||||
./gradlew assembleDebug
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@4e94bd11f71e507f7f87df81788dff88d1dacbfb # v4.31.0
|
||||
uses: github/codeql-action/analyze@0499de31b99561a6d14a36a5f662c2a54f91beee # v4.31.2
|
||||
@@ -48,8 +48,8 @@ jobs:
|
||||
mkdir -p "$HOME/.gradle"
|
||||
echo "org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" > "$HOME/.gradle/gradle.properties"
|
||||
echo "org.gradle.caching=true; org.gradle.parallel=true; org.gradle.configureondemand=true; kapt.incremental.apt=true" >> "$HOME/.gradle/gradle.properties"
|
||||
sed -i "/qa/,/\}/ s/versionCode .*/versionCode ${{github.event.number}} /" "app/build.gradle"
|
||||
sed -i "/qa/,/\}/ s/versionName .*/versionName \"${{github.event.number}}\"/" "app/build.gradle"
|
||||
sed -i "/qa/,/\}/ s/versionCode.*/versionCode = ${{ github.event.number }}/" app/build.gradle.kts
|
||||
sed -i "/qa/,/\}/ s/versionName.*/versionName = \"${{ github.event.number }}\"/" app/build.gradle.kts
|
||||
./gradlew assembleQaDebug
|
||||
$(find /usr/local/lib/android/sdk/build-tools/*/apksigner | sort | tail -n1) sign --ks-pass pass:"$KS_PASS" --key-pass pass:"$KEY_PASS" --ks-key-alias key0 --ks ".github/workflows/QA_keystore.jks" app/build/outputs/apk/qa/debug/*qa-debug*.apk
|
||||
.github/workflows/uploadArtifact.sh "$LOG_USERNAME" "$LOG_PASSWORD" "${{github.event.number}}" "${{github.event.number}}" "$GITHUB_TOKEN"
|
||||
@@ -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@4e94bd11f71e507f7f87df81788dff88d1dacbfb # v4.31.0
|
||||
uses: github/codeql-action/upload-sarif@0499de31b99561a6d14a36a5f662c2a54f91beee # v4.31.2
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
@@ -1,4 +1,4 @@
|
||||
# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-FileCopyrightText: 2022-2025 Nextcloud GmbH and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
|
||||
name: Unit tests
|
||||
@@ -20,36 +20,45 @@ concurrency:
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 17
|
||||
- name: Delete old comments
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
if: ${{ always() }}
|
||||
run: scripts/deleteOldComments.sh "test" "Unit" ${{github.event.number}}
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||
- name: Run unit tests with coverage
|
||||
run: ./gradlew jacocoTestGplayDebugUnitTest
|
||||
- name: Upload failing results
|
||||
if: ${{ failure() }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: scripts/uploadReport.sh "${{ secrets.LOG_USERNAME }}" "${{ secrets.LOG_PASSWORD }}" ${{github.event.number}} "test" "Unit" ${{github.event.number}}
|
||||
- name: Upload coverage to codecov
|
||||
uses: codecov/codecov-action@5a1091511ad55cbe89839c7260b706298ca349f7 # v5.5.1
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
flags: unit
|
||||
fail_ci_if_error: true
|
||||
- name: Upload jacoco artifacts
|
||||
if: ${{ failure() }}
|
||||
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||
with:
|
||||
name: test-results
|
||||
path: app/build/reports/tests/testGplayDebugUnitTest/
|
||||
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 17
|
||||
|
||||
- name: Delete old comments
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
if: ${{ always() }}
|
||||
run: scripts/deleteOldComments.sh "test" "Unit" ${{github.event.number}}
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||
|
||||
- name: Run unit tests with coverage
|
||||
run: ./gradlew jacocoTestGplayDebugUnitTest
|
||||
|
||||
- name: Upload failing results
|
||||
if: ${{ failure() }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: scripts/uploadReport.sh "${{ secrets.LOG_USERNAME }}" "${{ secrets.LOG_PASSWORD }}" ${{github.event.number}} "test" "Unit" ${{github.event.number}}
|
||||
|
||||
- name: Upload coverage to codecov
|
||||
uses: codecov/codecov-action@5a1091511ad55cbe89839c7260b706298ca349f7 # v5.5.1
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
flags: unit
|
||||
fail_ci_if_error: true
|
||||
files: app/build/reports/jacoco/jacocoTestGplayDebugUnitTestReport/jacoco.xml
|
||||
|
||||
- name: Upload jacoco artifacts
|
||||
if: ${{ failure() }}
|
||||
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||
with:
|
||||
name: test-results
|
||||
path: app/build/reports/jacoco/jacocoTestGplayDebugUnitTestReport/html/
|
||||
@@ -1,592 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
* SPDX-FileCopyrightText: 2024 Alper Ozturk <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2024 Tobias Kaminsky <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2024 Andy Scherzinger <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2022 Álvaro Brey Vilas <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
import com.github.spotbugs.snom.Confidence
|
||||
import com.github.spotbugs.snom.Effort
|
||||
import com.github.spotbugs.snom.SpotBugsTask
|
||||
import org.gradle.internal.jvm.Jvm
|
||||
|
||||
buildscript {
|
||||
dependencies {
|
||||
classpath "com.android.tools.build:gradle:$androidPluginVersion"
|
||||
classpath libs.spotbugs.gradle.plugin
|
||||
classpath libs.kotlin.gradle.plugin
|
||||
classpath libs.detekt.gradle.plugin
|
||||
classpath libs.commons.httpclient.commons.httpclient // remove after entire switch to lib v2
|
||||
classpath libs.shot
|
||||
classpath "org.jacoco:org.jacoco.core:$jacoco_version"
|
||||
classpath "org.jacoco:org.jacoco.report:$jacoco_version"
|
||||
classpath "org.jacoco:org.jacoco.agent:$jacoco_version"
|
||||
}
|
||||
}
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
alias(libs.plugins.spotless)
|
||||
alias(libs.plugins.kapt)
|
||||
alias(libs.plugins.ksp) apply false
|
||||
alias(libs.plugins.kotlin.serialization)
|
||||
}
|
||||
|
||||
apply plugin: "com.android.application"
|
||||
|
||||
apply plugin: "kotlin-android"
|
||||
apply plugin: "kotlin-parcelize"
|
||||
apply plugin: "checkstyle"
|
||||
apply plugin: "pmd"
|
||||
apply from: "$rootProject.projectDir/jacoco.gradle"
|
||||
apply plugin: "com.github.spotbugs"
|
||||
apply plugin: "io.gitlab.arturbosch.detekt"
|
||||
|
||||
// needed to make renovate run without shot, as shot requires Android SDK
|
||||
// https://github.com/pedrovgs/Shot/issues/300
|
||||
if (shotTest) {
|
||||
apply plugin: "shot"
|
||||
}
|
||||
apply plugin: "com.google.devtools.ksp"
|
||||
|
||||
|
||||
println "Gradle uses Java ${Jvm.current()}"
|
||||
|
||||
configurations {
|
||||
configureEach {
|
||||
exclude group: "org.jetbrains", module: "annotations-java5" // via prism4j, already using annotations explicitly
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
configurations.configureEach {
|
||||
resolutionStrategy.eachDependency {
|
||||
if (requested.group == "org.checkerframework" && requested.name != "checker-compat-qual") {
|
||||
useVersion(checkerVersion)
|
||||
because("https://github.com/google/ExoPlayer/issues/10007")
|
||||
}
|
||||
|
||||
if (requested.group == "commons-logging" && requested.name == "commons-logging") {
|
||||
useTarget("org.slf4j:jcl-over-slf4j:1.7.36")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// semantic versioning for version code
|
||||
def versionMajor = 3
|
||||
def versionMinor = 35
|
||||
def versionPatch = 0
|
||||
def versionBuild = 0 // 0-50=Alpha / 51-98=RC / 90-99=stable
|
||||
|
||||
|
||||
def ndkEnv = new HashMap<String, String>()
|
||||
file("$project.rootDir/ndk.env").readLines().each() {
|
||||
def (key, value) = it.tokenize("=")
|
||||
ndkEnv.put(key, value)
|
||||
}
|
||||
|
||||
def perfAnalysis = project.hasProperty("perfAnalysis")
|
||||
|
||||
def getConfigProperties() {
|
||||
def props = new Properties()
|
||||
def file = rootProject.file(".gradle/config.properties")
|
||||
if (file.exists()) {
|
||||
props.load(new FileInputStream(file))
|
||||
}
|
||||
return props
|
||||
}
|
||||
|
||||
def configProps = getConfigProperties()
|
||||
|
||||
android {
|
||||
// install this NDK version and Cmake to produce smaller APKs. Build will still work if not installed
|
||||
ndkVersion = "${ndkEnv.get("NDK_VERSION")}"
|
||||
|
||||
|
||||
namespace = "com.owncloud.android"
|
||||
testNamespace = "${namespace}.test"
|
||||
|
||||
androidResources {
|
||||
generateLocaleConfig = true
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.nextcloud.client"
|
||||
minSdk = 27
|
||||
targetSdk = 36
|
||||
compileSdk = 36
|
||||
|
||||
buildConfigField "boolean", "CI", ciBuild.toString()
|
||||
buildConfigField "boolean", "RUNTIME_PERF_ANALYSIS", perfAnalysis.toString()
|
||||
|
||||
javaCompileOptions {
|
||||
annotationProcessorOptions {
|
||||
arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
|
||||
}
|
||||
}
|
||||
|
||||
// arguments to be passed to functional tests
|
||||
if (shotTest) {
|
||||
testInstrumentationRunner "com.karumi.shot.ShotTestRunner"
|
||||
} else {
|
||||
testInstrumentationRunner "com.nextcloud.client.TestRunner"
|
||||
}
|
||||
testInstrumentationRunnerArgument "TEST_SERVER_URL", "${NC_TEST_SERVER_BASEURL}"
|
||||
testInstrumentationRunnerArgument "TEST_SERVER_USERNAME", "${NC_TEST_SERVER_USERNAME}"
|
||||
testInstrumentationRunnerArgument "TEST_SERVER_PASSWORD", "${NC_TEST_SERVER_PASSWORD}"
|
||||
testInstrumentationRunnerArguments disableAnalytics: "true"
|
||||
|
||||
versionCode versionMajor * 10000000 + versionMinor * 10000 + versionPatch * 100 + versionBuild
|
||||
|
||||
if (versionBuild > 89) {
|
||||
versionName "${versionMajor}.${versionMinor}.${versionPatch}"
|
||||
} else if (versionBuild > 50) {
|
||||
versionName "${versionMajor}.${versionMinor}.${versionPatch} RC" + (versionBuild - 50)
|
||||
} else {
|
||||
versionName "${versionMajor}.${versionMinor}.${versionPatch} Alpha" + (versionBuild + 1)
|
||||
}
|
||||
|
||||
// adapt structure from Eclipse to Gradle/Android Studio expectations;
|
||||
// see http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Configuring-the-Structure
|
||||
|
||||
flavorDimensions += "default"
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
buildConfigField "String", "NC_TEST_SERVER_DATA_STRING", "\"\""
|
||||
}
|
||||
|
||||
debug {
|
||||
testCoverageEnabled = project.hasProperty("coverage")
|
||||
resConfigs "xxxhdpi"
|
||||
|
||||
buildConfigField "String", "NC_TEST_SERVER_DATA_STRING", "\"nc://login/user:${configProps['NC_TEST_SERVER_USERNAME']}&password:${configProps['NC_TEST_SERVER_PASSWORD']}&server:${configProps['NC_TEST_SERVER_BASEURL']}\""
|
||||
}
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
buildConfig = true
|
||||
}
|
||||
|
||||
productFlavors {
|
||||
// used for f-droid
|
||||
generic {
|
||||
applicationId "com.nextcloud.client"
|
||||
dimension "default"
|
||||
}
|
||||
|
||||
gplay {
|
||||
applicationId "com.nextcloud.client"
|
||||
dimension "default"
|
||||
}
|
||||
|
||||
huawei {
|
||||
applicationId "com.nextcloud.client"
|
||||
dimension "default"
|
||||
}
|
||||
|
||||
versionDev {
|
||||
applicationId "com.nextcloud.android.beta"
|
||||
dimension "default"
|
||||
versionCode 20220322
|
||||
versionName "20220322"
|
||||
}
|
||||
|
||||
qa {
|
||||
applicationId "com.nextcloud.android.qa"
|
||||
dimension "default"
|
||||
versionCode 1
|
||||
versionName "1"
|
||||
}
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests.returnDefaultValues = true
|
||||
animationsDisabled = true
|
||||
}
|
||||
}
|
||||
|
||||
// adapt structure from Eclipse to Gradle/Android Studio expectations;
|
||||
// see http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Configuring-the-Structure
|
||||
packagingOptions {
|
||||
resources {
|
||||
excludes += "META-INF/LICENSE*"
|
||||
excludes += "META-INF/versions/9/OSGI-INF/MANIFEST*"
|
||||
pickFirst "MANIFEST.MF" // workaround for duplicated manifest on some dependencies
|
||||
}
|
||||
}
|
||||
|
||||
tasks.register("checkstyle", Checkstyle) {
|
||||
configFile = file("${rootProject.projectDir}/checkstyle.xml")
|
||||
configProperties.checkstyleSuppressionsPath = file("${project.rootDir}/config/quality/checkstyle/suppressions.xml").absolutePath
|
||||
source "src"
|
||||
include "**/*.java"
|
||||
exclude "**/gen/**"
|
||||
classpath = files()
|
||||
}
|
||||
|
||||
tasks.register("pmd", Pmd) {
|
||||
ruleSetFiles = files("${project.rootDir}/ruleset.xml")
|
||||
ignoreFailures = true // should continue checking
|
||||
ruleSets = []
|
||||
|
||||
source "src"
|
||||
include "**/*.java"
|
||||
exclude "**/gen/**"
|
||||
|
||||
reports {
|
||||
xml {
|
||||
destination = layout.buildDirectory.file("reports/pmd/pmd.xml").get().asFile
|
||||
}
|
||||
html {
|
||||
destination = layout.buildDirectory.file("reports/pmd/pmd.html").get().asFile
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
check.dependsOn "checkstyle", "spotbugsGplayDebug", "pmd", "lint", "spotlessKotlinCheck", "detekt"
|
||||
|
||||
buildFeatures {
|
||||
dataBinding = true
|
||||
viewBinding = true
|
||||
aidl = true
|
||||
compose = true
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_17
|
||||
targetCompatibility JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = "17"
|
||||
}
|
||||
|
||||
lint {
|
||||
abortOnError = false
|
||||
checkGeneratedSources = true
|
||||
disable "MissingTranslation", "GradleDependency", "VectorPath", "IconMissingDensityFolder", "IconDensities", "GoogleAppIndexingWarning", "MissingDefaultResource", "InvalidPeriodicWorkRequestInterval", "StringFormatInvalid", "MissingQuantity"
|
||||
htmlOutput = layout.buildDirectory.file("reports/lint/lint.html").get().asFile
|
||||
htmlReport = true
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
// Adds exported schema location as test app assets.
|
||||
androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
|
||||
}
|
||||
|
||||
kapt {
|
||||
useBuildCache = true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// region Nextcloud library
|
||||
implementation("com.github.nextcloud:android-library:$androidLibraryVersion") {
|
||||
exclude group: "org.ogce", module: "xpp3" // unused in Android and brings wrong Junit version
|
||||
}
|
||||
// endregion
|
||||
|
||||
// region Splash Screen
|
||||
implementation libs.splashscreen
|
||||
// endregion
|
||||
|
||||
// region Jetpack Compose
|
||||
implementation(platform(libs.compose.bom))
|
||||
implementation(libs.material.icons.core)
|
||||
implementation(libs.compose.ui)
|
||||
implementation(libs.compose.ui.graphics)
|
||||
implementation(libs.compose.material3)
|
||||
debugImplementation(libs.compose.ui.tooling)
|
||||
implementation(libs.compose.ui.tooling.preview)
|
||||
// endregion
|
||||
|
||||
// region Media3
|
||||
implementation libs.media3.ui
|
||||
implementation libs.media3.session
|
||||
implementation libs.media3.exoplayer
|
||||
implementation libs.media3.datasource
|
||||
// endregion
|
||||
|
||||
// region Room
|
||||
implementation libs.room.runtime
|
||||
ksp "androidx.room:room-compiler:$roomVersion"
|
||||
androidTestImplementation libs.room.testing
|
||||
// endregion
|
||||
|
||||
// region Espresso
|
||||
androidTestImplementation libs.espresso.core
|
||||
androidTestImplementation libs.espresso.contrib
|
||||
androidTestImplementation libs.espresso.web
|
||||
androidTestImplementation libs.espresso.accessibility
|
||||
androidTestImplementation libs.espresso.intents
|
||||
androidTestImplementation libs.espresso.idling.resource
|
||||
// endregion
|
||||
|
||||
// region Glide
|
||||
implementation libs.glide
|
||||
ksp libs.ksp
|
||||
// endregion
|
||||
|
||||
// region UI
|
||||
implementation libs.appcompat
|
||||
implementation libs.webkit
|
||||
implementation libs.cardview
|
||||
implementation libs.exifinterface
|
||||
implementation libs.fragment.ktx
|
||||
// endregion
|
||||
|
||||
// region Worker
|
||||
implementation libs.work.runtime
|
||||
implementation libs.work.runtime.ktx
|
||||
// endregion
|
||||
|
||||
// region Lifecycle
|
||||
implementation libs.lifecycle.viewmodel.ktx
|
||||
implementation libs.lifecycle.service
|
||||
implementation(libs.lifecycle.runtime.ktx)
|
||||
// endregion
|
||||
|
||||
// region JUnit
|
||||
androidTestImplementation libs.junit
|
||||
androidTestImplementation libs.rules
|
||||
androidTestImplementation libs.runner
|
||||
androidTestUtil libs.orchestrator
|
||||
androidTestImplementation libs.core.ktx
|
||||
androidTestImplementation libs.core.testing
|
||||
// endregion
|
||||
|
||||
// region other libraries
|
||||
compileOnly libs.org.jbundle.util.osgi.wrapped.org.apache.http.client
|
||||
implementation libs.commons.httpclient.commons.httpclient // remove after entire switch to lib v2
|
||||
implementation libs.jackrabbit.webdav // remove after entire switch to lib v2
|
||||
implementation libs.constraintlayout
|
||||
implementation libs.legacy.support.v4
|
||||
implementation libs.material
|
||||
implementation libs.disklrucache
|
||||
implementation libs.juniversalchardet // need this version for Android <7
|
||||
compileOnly libs.annotations
|
||||
implementation libs.commons.io
|
||||
implementation libs.eventbus
|
||||
implementation libs.ez.vcard
|
||||
implementation libs.nnio
|
||||
implementation libs.bcpkix.jdk18on
|
||||
implementation libs.gson
|
||||
implementation libs.sectioned.recyclerview
|
||||
implementation libs.photoview
|
||||
implementation libs.android.gif.drawable
|
||||
implementation libs.qrcodescanner // "com.github.blikoon:QRCodeScanner:0.1.2"
|
||||
implementation libs.flexbox
|
||||
implementation libs.androidsvg
|
||||
implementation libs.annotation
|
||||
implementation libs.emoji.google
|
||||
// endregion
|
||||
|
||||
// region AppScan, document scanner not available on FDroid (generic) due to OpenCV binaries
|
||||
gplayImplementation project(":appscan")
|
||||
huaweiImplementation project(":appscan")
|
||||
qaImplementation project(":appscan")
|
||||
// endregion
|
||||
|
||||
// region SpotBugs
|
||||
spotbugsPlugins libs.findsecbugs.plugin
|
||||
spotbugsPlugins libs.fb.contrib
|
||||
// endregion
|
||||
|
||||
// region Dagger
|
||||
implementation libs.dagger
|
||||
implementation libs.dagger.android
|
||||
implementation libs.dagger.android.support
|
||||
kapt "com.google.dagger:dagger-compiler:$daggerVersion"
|
||||
kapt "com.google.dagger:dagger-android-processor:$daggerVersion"
|
||||
// endregion
|
||||
|
||||
// region Crypto
|
||||
implementation libs.conscrypt.android
|
||||
// endregion
|
||||
|
||||
// region Library
|
||||
implementation libs.library
|
||||
// endregion
|
||||
|
||||
// region Shimmer
|
||||
implementation libs.loaderviewlibrary
|
||||
// endregion
|
||||
|
||||
// region Markdown rendering
|
||||
implementation libs.core
|
||||
implementation libs.ext.strikethrough
|
||||
implementation libs.ext.tables
|
||||
implementation libs.ext.tasklist
|
||||
implementation libs.html
|
||||
implementation libs.syntax.highlight
|
||||
implementation libs.prism4j
|
||||
kapt "io.noties:prism4j-bundler:$prismVersion"
|
||||
// endregion
|
||||
|
||||
// region Image cropping / rotation
|
||||
implementation libs.android.image.cropper
|
||||
// endregion
|
||||
|
||||
// region Maps
|
||||
implementation libs.osmdroid.android
|
||||
// endregion
|
||||
|
||||
// region iCal4j
|
||||
implementation(libs.ical4j) {
|
||||
["org.apache.commons", "commons-logging"].each {
|
||||
exclude group: "$it"
|
||||
}
|
||||
}
|
||||
// endregion
|
||||
|
||||
// region LeakCanary
|
||||
if (perfAnalysis) {
|
||||
debugImplementation "com.squareup.leakcanary:leakcanary-android:2.14"
|
||||
}
|
||||
// endregion
|
||||
|
||||
// region Local Unit Test
|
||||
testImplementation libs.junit.junit
|
||||
testImplementation libs.mockito.core
|
||||
testImplementation libs.test.core
|
||||
testImplementation libs.json
|
||||
testImplementation libs.mockito.kotlin
|
||||
testImplementation libs.core.testing
|
||||
testImplementation "io.mockk:mockk:$mockkVersion"
|
||||
testImplementation libs.mockk.android
|
||||
// endregion
|
||||
|
||||
// region Mocking support
|
||||
androidTestImplementation libs.dexopener // required to allow mocking on API 27 and older
|
||||
androidTestImplementation libs.mockito.kotlin
|
||||
androidTestImplementation libs.mockito.core
|
||||
androidTestImplementation(libs.mockito.android)
|
||||
androidTestImplementation libs.mockk.android
|
||||
androidTestImplementation libs.screenshot.core
|
||||
// endregion
|
||||
|
||||
// region UIAutomator
|
||||
// UIAutomator - for cross-app UI tests, and to grant screen is turned on in Espresso tests
|
||||
// androidTestImplementation "androidx.test.uiautomator:uiautomator:2.2.0"
|
||||
// fix conflict in dependencies; see http://g.co/androidstudio/app-test-app-conflict for details
|
||||
// androidTestImplementation "com.android.support:support-annotations:${supportLibraryVersion}"
|
||||
androidTestImplementation libs.screengrab
|
||||
// endregion
|
||||
|
||||
// region Kotlin
|
||||
implementation libs.kotlin.stdlib
|
||||
// endregion
|
||||
|
||||
// region Stateless
|
||||
implementation libs.stateless4j
|
||||
// endregion
|
||||
|
||||
// region Google Play dependencies, upon each update first test: new registration, receive push
|
||||
gplayImplementation libs.firebase.messaging
|
||||
gplayImplementation libs.play.services.base
|
||||
gplayImplementation libs.review.ktx
|
||||
// endregion
|
||||
|
||||
// region UI
|
||||
implementation libs.ui
|
||||
// endregion
|
||||
|
||||
// region Image loading
|
||||
implementation libs.coil
|
||||
// endregion
|
||||
|
||||
// kotlinx.serialization
|
||||
implementation(libs.kotlinx.serialization.json)
|
||||
}
|
||||
|
||||
|
||||
configurations.configureEach {
|
||||
resolutionStrategy {
|
||||
force "org.objenesis:objenesis:3.4"
|
||||
eachDependency { details ->
|
||||
if ("org.jacoco" == details.requested.group) {
|
||||
details.useVersion "$jacoco_version"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Run the compiler as a separate process
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
options.fork = true
|
||||
|
||||
// Enable Incremental Compilation
|
||||
options.incremental = true
|
||||
}
|
||||
|
||||
tasks.withType(Test).configureEach {
|
||||
// Run tests in parallel
|
||||
maxParallelForks = Runtime.runtime.availableProcessors().intdiv(2) ?: 1
|
||||
|
||||
// increased logging for tests
|
||||
testLogging {
|
||||
events "passed", "skipped", "failed"
|
||||
}
|
||||
}
|
||||
|
||||
android.applicationVariants.configureEach { variant ->
|
||||
variant.outputs.configureEach { output -> outputFileName = "${output.baseName}-${variant.versionCode}.apk"
|
||||
}
|
||||
}
|
||||
|
||||
spotless {
|
||||
kotlin {
|
||||
target "**/*.kt"
|
||||
ktlint()
|
||||
}
|
||||
}
|
||||
|
||||
detekt {
|
||||
config.setFrom("detekt.yml")
|
||||
}
|
||||
|
||||
if (shotTest) {
|
||||
shot {
|
||||
showOnlyFailingTestsInReports = ciBuild
|
||||
// CI environment renders some shadows slightly different from local VMs
|
||||
// Add a 0.5% tolerance to account for that
|
||||
tolerance = ciBuild ? 0.1 : 0
|
||||
}
|
||||
}
|
||||
|
||||
jacoco {
|
||||
toolVersion = "$jacoco_version"
|
||||
}
|
||||
|
||||
spotbugs {
|
||||
ignoreFailures = true // should continue checking
|
||||
effort = Effort.MAX
|
||||
reportLevel = Confidence.valueOf("MEDIUM")
|
||||
}
|
||||
|
||||
tasks.withType(SpotBugsTask){task ->
|
||||
String variantNameCap = task.name.replace("spotbugs", "")
|
||||
String variantName = variantNameCap.substring(0, 1).toLowerCase() + variantNameCap.substring(1)
|
||||
dependsOn "compile${variantNameCap}Sources"
|
||||
|
||||
classes = fileTree(layout.buildDirectory.get().asFile.toString()+"/intermediates/javac/${variantName}/compile${variantNameCap}JavaWithJavac/classes/")
|
||||
excludeFilter = file("${project.rootDir}/scripts/analysis/spotbugs-filter.xml")
|
||||
reports {
|
||||
xml {
|
||||
required = true
|
||||
}
|
||||
html {
|
||||
required = true
|
||||
outputLocation = layout.buildDirectory.file("reports/spotbugs/spotbugs.html").get().asFile
|
||||
stylesheet = "fancy.xsl"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ksp {
|
||||
arg("room.schemaLocation", "$projectDir/schemas")
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Jimly Asshiddiqy <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
@file:Suppress("UnstableApiUsage", "DEPRECATION")
|
||||
|
||||
import com.android.build.gradle.internal.api.ApkVariantOutputImpl
|
||||
import com.github.spotbugs.snom.Confidence
|
||||
import com.github.spotbugs.snom.Effort
|
||||
import com.github.spotbugs.snom.SpotBugsTask
|
||||
import com.karumi.shot.ShotExtension
|
||||
import org.gradle.internal.jvm.Jvm
|
||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||
import java.io.FileInputStream
|
||||
import java.util.Properties
|
||||
|
||||
val shotTest = System.getenv("SHOT_TEST") == "true"
|
||||
val ciBuild = System.getenv("CI") == "true"
|
||||
val perfAnalysis = project.hasProperty("perfAnalysis")
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
alias(libs.plugins.spotless)
|
||||
alias(libs.plugins.kapt)
|
||||
alias(libs.plugins.ksp)
|
||||
alias(libs.plugins.kotlin.serialization)
|
||||
alias(libs.plugins.kotlin.parcelize)
|
||||
alias(libs.plugins.jetbrains.kotlin.android)
|
||||
alias(libs.plugins.spotbugs)
|
||||
alias(libs.plugins.detekt)
|
||||
// needed to make renovate run without shot, as shot requires Android SDK
|
||||
// https://github.com/pedrovgs/Shot/issues/300
|
||||
if (System.getenv("SHOT_TEST") == "true") alias(libs.plugins.shot)
|
||||
id("checkstyle")
|
||||
id("pmd")
|
||||
}
|
||||
apply(from = "${rootProject.projectDir}/jacoco.gradle.kts")
|
||||
|
||||
println("Gradle uses Java ${Jvm.current()}")
|
||||
|
||||
configurations.configureEach {
|
||||
// via prism4j, already using annotations explicitly
|
||||
exclude(group = "org.jetbrains", module = "annotations-java5")
|
||||
|
||||
resolutionStrategy {
|
||||
force(libs.objenesis)
|
||||
|
||||
eachDependency {
|
||||
if (requested.group == "org.checkerframework" && requested.name != "checker-compat-qual") {
|
||||
useVersion(libs.versions.checker.get())
|
||||
because("https://github.com/google/ExoPlayer/issues/10007")
|
||||
} else if (requested.group == "org.jacoco") {
|
||||
useVersion(libs.versions.jacoco.get())
|
||||
} else if (requested.group == "commons-logging" && requested.name == "commons-logging") {
|
||||
useTarget(libs.slfj)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// semantic versioning for version code
|
||||
val versionMajor = 3
|
||||
val versionMinor = 35
|
||||
val versionPatch = 0
|
||||
val versionBuild = 0 // 0-50=Alpha / 51-98=RC / 90-99=stable
|
||||
|
||||
val ndkEnv = buildMap {
|
||||
file("${project.rootDir}/ndk.env").readLines().forEach {
|
||||
val (key, value) = it.split("=")
|
||||
put(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
val configProps = Properties().apply {
|
||||
val file = rootProject.file(".gradle/config.properties")
|
||||
if (file.exists()) load(FileInputStream(file))
|
||||
}
|
||||
|
||||
val ncTestServerUsername = configProps["NC_TEST_SERVER_USERNAME"]
|
||||
val ncTestServerPassword = configProps["NC_TEST_SERVER_PASSWORD"]
|
||||
val ncTestServerBaseUrl = configProps["NC_TEST_SERVER_BASEURL"]
|
||||
|
||||
android {
|
||||
// install this NDK version and Cmake to produce smaller APKs. Build will still work if not installed
|
||||
ndkVersion = "${ndkEnv["NDK_VERSION"]}"
|
||||
|
||||
namespace = "com.owncloud.android"
|
||||
testNamespace = "${namespace}.test"
|
||||
|
||||
androidResources.generateLocaleConfig = true
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.nextcloud.client"
|
||||
minSdk = 27
|
||||
targetSdk = 36
|
||||
compileSdk = 36
|
||||
|
||||
buildConfigField("boolean", "CI", ciBuild.toString())
|
||||
buildConfigField("boolean", "RUNTIME_PERF_ANALYSIS", perfAnalysis.toString())
|
||||
|
||||
javaCompileOptions.annotationProcessorOptions {
|
||||
arguments += mapOf("room.schemaLocation" to "$projectDir/schemas")
|
||||
}
|
||||
|
||||
// arguments to be passed to functional tests
|
||||
testInstrumentationRunner = if (shotTest) "com.karumi.shot.ShotTestRunner"
|
||||
else "com.nextcloud.client.TestRunner"
|
||||
|
||||
testInstrumentationRunnerArguments += mapOf(
|
||||
"TEST_SERVER_URL" to ncTestServerBaseUrl.toString(),
|
||||
"TEST_SERVER_USERNAME" to ncTestServerUsername.toString(),
|
||||
"TEST_SERVER_PASSWORD" to ncTestServerPassword.toString()
|
||||
)
|
||||
testInstrumentationRunnerArguments["disableAnalytics"] = "true"
|
||||
|
||||
versionCode = versionMajor * 10000000 + versionMinor * 10000 + versionPatch * 100 + versionBuild
|
||||
versionName = when {
|
||||
versionBuild > 89 -> "${versionMajor}.${versionMinor}.${versionPatch}"
|
||||
versionBuild > 50 -> "${versionMajor}.${versionMinor}.${versionPatch} RC" + (versionBuild - 50)
|
||||
else -> "${versionMajor}.${versionMinor}.${versionPatch} Alpha" + (versionBuild + 1)
|
||||
}
|
||||
|
||||
// adapt structure from Eclipse to Gradle/Android Studio expectations;
|
||||
// see http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Configuring-the-Structure
|
||||
|
||||
flavorDimensions += "default"
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
buildConfigField("String", "NC_TEST_SERVER_DATA_STRING", "\"\"")
|
||||
}
|
||||
|
||||
debug {
|
||||
enableUnitTestCoverage = project.hasProperty("coverage")
|
||||
resConfigs("xxxhdpi")
|
||||
|
||||
buildConfigField(
|
||||
"String",
|
||||
"NC_TEST_SERVER_DATA_STRING",
|
||||
"\"nc://login/user:${ncTestServerUsername}&password:${ncTestServerPassword}&server:${ncTestServerBaseUrl}\""
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
productFlavors {
|
||||
// used for f-droid
|
||||
register("generic") {
|
||||
applicationId = "com.nextcloud.client"
|
||||
dimension = "default"
|
||||
}
|
||||
|
||||
register("gplay") {
|
||||
applicationId = "com.nextcloud.client"
|
||||
dimension = "default"
|
||||
}
|
||||
|
||||
register("huawei") {
|
||||
applicationId = "com.nextcloud.client"
|
||||
dimension = "default"
|
||||
}
|
||||
|
||||
register("versionDev") {
|
||||
applicationId = "com.nextcloud.android.beta"
|
||||
dimension = "default"
|
||||
versionCode = 20220322
|
||||
versionName = "20220322"
|
||||
}
|
||||
|
||||
register("qa") {
|
||||
applicationId = "com.nextcloud.android.qa"
|
||||
dimension = "default"
|
||||
versionCode = 1
|
||||
versionName = "1"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
applicationVariants.configureEach {
|
||||
outputs.configureEach {
|
||||
if (this is ApkVariantOutputImpl) this.outputFileName = "${this.baseName}-${this.versionCode}.apk"
|
||||
}
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests.isReturnDefaultValues = true
|
||||
animationsDisabled = true
|
||||
}
|
||||
|
||||
// adapt structure from Eclipse to Gradle/Android Studio expectations;
|
||||
// see http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Configuring-the-Structure
|
||||
packaging.resources {
|
||||
excludes.addAll(listOf("META-INF/LICENSE*", "META-INF/versions/9/OSGI-INF/MANIFEST*"))
|
||||
pickFirsts.add("MANIFEST.MF") // workaround for duplicated manifest on some dependencies
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
buildConfig = true
|
||||
dataBinding = true
|
||||
viewBinding = true
|
||||
aidl = true
|
||||
compose = true
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
lint {
|
||||
abortOnError = true
|
||||
warningsAsErrors = true
|
||||
checkGeneratedSources = true
|
||||
disable.addAll(
|
||||
listOf(
|
||||
"MissingTranslation",
|
||||
"GradleDependency",
|
||||
"VectorPath",
|
||||
"IconMissingDensityFolder",
|
||||
"IconDensities",
|
||||
"GoogleAppIndexingWarning",
|
||||
"MissingDefaultResource",
|
||||
"InvalidPeriodicWorkRequestInterval",
|
||||
"StringFormatInvalid",
|
||||
"MissingQuantity",
|
||||
"IconXmlAndPng",
|
||||
"SelectedPhotoAccess",
|
||||
"UnsafeIntentLaunch"
|
||||
)
|
||||
)
|
||||
htmlOutput = layout.buildDirectory.file("reports/lint/lint.html").get().asFile
|
||||
htmlReport = true
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
// Adds exported schema location as test app assets.
|
||||
getByName("androidTest") {
|
||||
assets.srcDirs(files("$projectDir/schemas"))
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
kapt.useBuildCache = true
|
||||
|
||||
ksp.arg("room.schemaLocation", "$projectDir/schemas")
|
||||
|
||||
kotlin.compilerOptions.jvmTarget.set(JvmTarget.JVM_17)
|
||||
|
||||
spotless.kotlin {
|
||||
target("**/*.kt")
|
||||
ktlint()
|
||||
}
|
||||
|
||||
detekt.config.setFrom("detekt.yml")
|
||||
|
||||
if (shotTest) configure<ShotExtension> {
|
||||
showOnlyFailingTestsInReports = ciBuild
|
||||
// CI environment renders some shadows slightly different from local VMs
|
||||
// Add a 0.5% tolerance to account for that
|
||||
tolerance = if (ciBuild) 0.1 else 0.0
|
||||
}
|
||||
|
||||
|
||||
spotbugs {
|
||||
ignoreFailures = true // should continue checking
|
||||
effort = Effort.MAX
|
||||
reportLevel = Confidence.valueOf("MEDIUM")
|
||||
}
|
||||
|
||||
tasks.register<Checkstyle>("checkstyle") {
|
||||
configFile = file("${rootProject.projectDir}/checkstyle.xml")
|
||||
setConfigProperties(
|
||||
"checkstyleSuppressionsPath" to file("${rootProject.rootDir}/suppressions.xml").absolutePath
|
||||
)
|
||||
source("src")
|
||||
include("**/*.java")
|
||||
exclude("**/gen/**")
|
||||
classpath = files()
|
||||
}
|
||||
|
||||
tasks.register<Pmd>("pmd") {
|
||||
ruleSetFiles = files("${rootProject.rootDir}/ruleset.xml")
|
||||
ignoreFailures = true // should continue checking
|
||||
ruleSets = emptyList()
|
||||
|
||||
source("src")
|
||||
include("**/*.java")
|
||||
exclude("**/gen/**")
|
||||
|
||||
reports {
|
||||
xml.outputLocation.set(layout.buildDirectory.file("reports/pmd/pmd.xml").get().asFile)
|
||||
html.outputLocation.set(layout.buildDirectory.file("reports/pmd/pmd.html").get().asFile)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType<SpotBugsTask>().configureEach {
|
||||
val variantNameCap = name.replace("spotbugs", "")
|
||||
val variantName = variantNameCap.substring(0, 1).lowercase() + variantNameCap.substring(1)
|
||||
dependsOn("compile${variantNameCap}Sources")
|
||||
|
||||
classes = fileTree(
|
||||
layout.buildDirectory.get().asFile.toString() +
|
||||
"/intermediates/javac/${variantName}/compile${variantNameCap}JavaWithJavac/classes/"
|
||||
)
|
||||
excludeFilter.set(file("${project.rootDir}/scripts/analysis/spotbugs-filter.xml"))
|
||||
|
||||
reports.create("xml") {
|
||||
required.set(true)
|
||||
}
|
||||
reports.create("html") {
|
||||
required.set(true)
|
||||
outputLocation.set(layout.buildDirectory.file("reports/spotbugs/spotbugs.html"))
|
||||
setStylesheet("fancy.xsl")
|
||||
}
|
||||
}
|
||||
|
||||
// Run the compiler as a separate process
|
||||
tasks.withType<JavaCompile>().configureEach {
|
||||
options.isFork = true
|
||||
|
||||
// Enable Incremental Compilation
|
||||
options.isIncremental = true
|
||||
}
|
||||
|
||||
tasks.withType<Test>().configureEach {
|
||||
// Run tests in parallel
|
||||
maxParallelForks = Runtime.getRuntime().availableProcessors().div(2)
|
||||
|
||||
// increased logging for tests
|
||||
testLogging.events("passed", "skipped", "failed")
|
||||
}
|
||||
|
||||
tasks.named("check").configure {
|
||||
dependsOn("checkstyle", "spotbugsGplayDebug", "pmd", "lint", "spotlessKotlinCheck", "detekt")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// region Nextcloud library
|
||||
implementation(libs.android.library) {
|
||||
exclude(group = "org.ogce", module = "xpp3") // unused in Android and brings wrong Junit version
|
||||
}
|
||||
// endregion
|
||||
|
||||
// region Splash Screen
|
||||
implementation(libs.splashscreen)
|
||||
// endregion
|
||||
|
||||
// region Jetpack Compose
|
||||
implementation(platform(libs.compose.bom))
|
||||
implementation(libs.material.icons.core)
|
||||
implementation(libs.compose.ui)
|
||||
implementation(libs.compose.ui.graphics)
|
||||
implementation(libs.compose.material3)
|
||||
implementation(libs.compose.ui.tooling.preview)
|
||||
debugImplementation(libs.compose.ui.tooling)
|
||||
// endregion
|
||||
|
||||
// region Media3
|
||||
implementation(libs.bundles.media3)
|
||||
// endregion
|
||||
|
||||
// region Room
|
||||
implementation(libs.room.runtime)
|
||||
ksp(libs.room.compiler)
|
||||
androidTestImplementation(libs.room.testing)
|
||||
// endregion
|
||||
|
||||
// region Espresso
|
||||
androidTestImplementation(libs.bundles.espresso)
|
||||
// endregion
|
||||
|
||||
// region Glide
|
||||
implementation(libs.glide)
|
||||
ksp(libs.ksp)
|
||||
// endregion
|
||||
|
||||
// region UI
|
||||
implementation(libs.bundles.ui)
|
||||
// endregion
|
||||
|
||||
// region Worker
|
||||
implementation(libs.work.runtime)
|
||||
implementation(libs.work.runtime.ktx)
|
||||
// endregion
|
||||
|
||||
// region Lifecycle
|
||||
implementation(libs.lifecycle.viewmodel.ktx)
|
||||
implementation(libs.lifecycle.service)
|
||||
implementation(libs.lifecycle.runtime.ktx)
|
||||
// endregion
|
||||
|
||||
// region JUnit
|
||||
androidTestImplementation(libs.junit)
|
||||
androidTestImplementation(libs.rules)
|
||||
androidTestImplementation(libs.runner)
|
||||
androidTestUtil(libs.orchestrator)
|
||||
androidTestImplementation(libs.core.ktx)
|
||||
androidTestImplementation(libs.core.testing)
|
||||
// endregion
|
||||
|
||||
// region other libraries
|
||||
compileOnly(libs.org.jbundle.util.osgi.wrapped.org.apache.http.client)
|
||||
implementation(libs.commons.httpclient.commons.httpclient) // remove after entire switch to lib v2
|
||||
implementation(libs.jackrabbit.webdav) // remove after entire switch to lib v2
|
||||
implementation(libs.constraintlayout)
|
||||
implementation(libs.legacy.support.v4)
|
||||
implementation(libs.material)
|
||||
implementation(libs.disklrucache)
|
||||
implementation(libs.juniversalchardet) // need this version for Android <7
|
||||
compileOnly(libs.annotations)
|
||||
implementation(libs.commons.io)
|
||||
implementation(libs.eventbus)
|
||||
implementation(libs.ez.vcard)
|
||||
implementation(libs.nnio)
|
||||
implementation(libs.bcpkix.jdk18on)
|
||||
implementation(libs.gson)
|
||||
implementation(libs.sectioned.recyclerview)
|
||||
implementation(libs.photoview)
|
||||
implementation(libs.android.gif.drawable)
|
||||
implementation(libs.qrcodescanner) // "com.github.blikoon:QRCodeScanner:0.1.2"
|
||||
implementation(libs.flexbox)
|
||||
implementation(libs.androidsvg)
|
||||
implementation(libs.annotation)
|
||||
implementation(libs.emoji.google)
|
||||
// endregion
|
||||
|
||||
// region AppScan, document scanner not available on FDroid (generic) due to OpenCV binaries
|
||||
"gplayImplementation"(project(":appscan"))
|
||||
"huaweiImplementation"(project(":appscan"))
|
||||
"qaImplementation"(project(":appscan"))
|
||||
// endregion
|
||||
|
||||
// region SpotBugs
|
||||
spotbugsPlugins(libs.findsecbugs.plugin)
|
||||
spotbugsPlugins(libs.fb.contrib)
|
||||
// endregion
|
||||
|
||||
// region Dagger
|
||||
implementation(libs.dagger)
|
||||
implementation(libs.dagger.android)
|
||||
implementation(libs.dagger.android.support)
|
||||
ksp(libs.dagger.compiler)
|
||||
ksp(libs.dagger.processor)
|
||||
// endregion
|
||||
|
||||
// region Crypto
|
||||
implementation(libs.conscrypt.android)
|
||||
// endregion
|
||||
|
||||
// region Library
|
||||
implementation(libs.library)
|
||||
// endregion
|
||||
|
||||
// region Shimmer
|
||||
implementation(libs.loaderviewlibrary)
|
||||
// endregion
|
||||
|
||||
// region Markdown rendering
|
||||
implementation(libs.bundles.markdown.rendering)
|
||||
kapt(libs.prism4j.bundler)
|
||||
// endregion
|
||||
|
||||
// region Image cropping / rotation
|
||||
implementation(libs.android.image.cropper)
|
||||
// endregion
|
||||
|
||||
// region Maps
|
||||
implementation(libs.osmdroid.android)
|
||||
// endregion
|
||||
|
||||
// region iCal4j
|
||||
implementation(libs.ical4j) {
|
||||
listOf("org.apache.commons", "commons-logging").forEach { groupName -> exclude(group = groupName) }
|
||||
}
|
||||
// endregion
|
||||
|
||||
// region LeakCanary
|
||||
if (perfAnalysis) debugImplementation(libs.leakcanary)
|
||||
// endregion
|
||||
|
||||
// region Local Unit Test
|
||||
testImplementation(libs.bundles.unit.test)
|
||||
// endregion
|
||||
|
||||
// region Mocking support
|
||||
androidTestImplementation(libs.bundles.mocking)
|
||||
// endregion
|
||||
|
||||
// region UIAutomator
|
||||
// UIAutomator - for cross-app UI tests, and to grant screen is turned on in Espresso tests
|
||||
// androidTestImplementation("androidx.test.uiautomator:uiautomator:2.2.0"
|
||||
// fix conflict in dependencies; see http://g.co/androidstudio/app-test-app-conflict for details
|
||||
// androidTestImplementation("com.android.support:support-annotations:${supportLibraryVersion}"
|
||||
androidTestImplementation(libs.screengrab)
|
||||
// endregion
|
||||
|
||||
// region Kotlin
|
||||
implementation(libs.kotlin.stdlib)
|
||||
// endregion
|
||||
|
||||
// region Stateless
|
||||
implementation(libs.stateless4j)
|
||||
// endregion
|
||||
|
||||
// region Google Play dependencies, upon each update first test: new registration, receive push
|
||||
"gplayImplementation"(libs.bundles.gplay)
|
||||
// endregion
|
||||
|
||||
// region UI
|
||||
implementation(libs.ui)
|
||||
// endregion
|
||||
|
||||
// region Image loading
|
||||
implementation(libs.coil)
|
||||
// endregion
|
||||
|
||||
// kotlinx.serialization
|
||||
implementation(libs.kotlinx.serialization.json)
|
||||
}
|
||||
@@ -39,6 +39,10 @@
|
||||
<ignore path="**/values-**/strings.xml" />
|
||||
</issue>
|
||||
|
||||
<issue id="PluralsCandidate">
|
||||
<ignore path="**/values-**/strings.xml" />
|
||||
</issue>
|
||||
|
||||
<issue id="ExtraTranslation">
|
||||
<ignore path="**/strings.xml"/>
|
||||
<ignore path="**/values-b+en+001/strings.xml"/>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -7,7 +7,7 @@
|
||||
*/
|
||||
package com.nextcloud.client.assistant
|
||||
|
||||
import com.nextcloud.client.assistant.repository.AssistantRepository
|
||||
import com.nextcloud.client.assistant.repository.remote.AssistantRemoteRepositoryImpl
|
||||
import com.owncloud.android.AbstractOnServerIT
|
||||
import com.owncloud.android.lib.resources.assistant.v2.model.TaskTypeData
|
||||
import com.owncloud.android.lib.resources.status.NextcloudVersion
|
||||
@@ -18,11 +18,11 @@ import org.junit.Test
|
||||
@Suppress("MagicNumber")
|
||||
class AssistantRepositoryTests : AbstractOnServerIT() {
|
||||
|
||||
private var sut: AssistantRepository? = null
|
||||
private var sut: AssistantRemoteRepositoryImpl? = null
|
||||
|
||||
@Before
|
||||
fun setup() {
|
||||
sut = AssistantRepository(nextcloudClient, capability)
|
||||
sut = AssistantRemoteRepositoryImpl(nextcloudClient, capability)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.nextcloud.extensions
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import com.nextcloud.utils.decodeSampledBitmapFromFile
|
||||
import com.nextcloud.utils.extensions.toFile
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.io.OutputStream
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import kotlin.io.path.ExperimentalPathApi
|
||||
import kotlin.io.path.absolutePathString
|
||||
import kotlin.io.path.deleteRecursively
|
||||
import kotlin.io.path.exists
|
||||
|
||||
@Suppress("MagicNumber")
|
||||
class BitmapDecodeTests {
|
||||
|
||||
private lateinit var tempDir: Path
|
||||
|
||||
@Before
|
||||
fun setup() {
|
||||
tempDir = Files.createTempDirectory("auto_upload_test_")
|
||||
assertTrue("Temp directory should exist", tempDir.exists())
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalPathApi::class)
|
||||
@After
|
||||
fun cleanup() {
|
||||
if (tempDir.exists()) {
|
||||
tempDir.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
private fun createTempImageFile(width: Int = 100, height: Int = 100): Path {
|
||||
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
|
||||
val imagePath = tempDir.resolve("test_${System.currentTimeMillis()}.jpg")
|
||||
|
||||
Files.newOutputStream(imagePath).use { out: OutputStream ->
|
||||
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)
|
||||
}
|
||||
|
||||
assertTrue(imagePath.exists())
|
||||
return imagePath
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testToFileWhenPathIsValidShouldReturnExistingFile() {
|
||||
val path = createTempImageFile()
|
||||
val result = path.absolutePathString().toFile()
|
||||
assertNotNull(result)
|
||||
assertTrue(result!!.exists())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testToFileWhenPathIsEmptyShouldReturnNull() {
|
||||
val result = "".toFile()
|
||||
assertNull(result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testToFileWhenFileDoesNotExistShouldReturnNull() {
|
||||
val nonExistentPath = tempDir.resolve("does_not_exist.jpg")
|
||||
val result = nonExistentPath.absolutePathString().toFile()
|
||||
assertNull(result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDecodeSampledBitmapFromFileWhenValidPathShouldReturnBitmap() {
|
||||
val path = createTempImageFile(400, 400)
|
||||
val bitmap = decodeSampledBitmapFromFile(path.absolutePathString(), 100, 100)
|
||||
assertNotNull(bitmap)
|
||||
assertTrue(bitmap!!.width <= 400)
|
||||
assertTrue(bitmap.height <= 400)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDecodeSampledBitmapFromFileWhenInvalidPathShouldReturnNull() {
|
||||
val invalidPath = tempDir.resolve("invalid_path.jpg").absolutePathString()
|
||||
val bitmap = decodeSampledBitmapFromFile(invalidPath, 100, 100)
|
||||
assertNull(bitmap)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDecodeSampledBitmapFromFileWhenImageIsLargeShouldDownsampleBitmap() {
|
||||
val path = createTempImageFile(2000, 2000)
|
||||
val bitmap = decodeSampledBitmapFromFile(path.absolutePathString(), 100, 100)
|
||||
assertNotNull(bitmap)
|
||||
assertTrue("Bitmap should be smaller than original", bitmap!!.width < 2000 && bitmap.height < 2000)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDecodeSampledBitmapFromFileWhenImageIsSmallerThanRequestedShouldKeepOriginalSize() {
|
||||
val path = createTempImageFile(100, 100)
|
||||
val bitmap = decodeSampledBitmapFromFile(path.absolutePathString(), 200, 200)
|
||||
assertNotNull(bitmap)
|
||||
assertEquals(100, bitmap!!.width)
|
||||
assertEquals(100, bitmap.height)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ package com.nextcloud.utils
|
||||
import com.nextcloud.utils.autoRename.AutoRename
|
||||
import com.owncloud.android.AbstractOnServerIT
|
||||
import com.owncloud.android.datamodel.e2e.v2.decrypted.DecryptedFile
|
||||
import com.owncloud.android.lib.resources.status.CapabilityBooleanType
|
||||
import com.owncloud.android.lib.resources.status.NextcloudVersion
|
||||
import com.owncloud.android.lib.resources.status.OCCapability
|
||||
import org.junit.Before
|
||||
@@ -27,6 +28,7 @@ class AutoRenameTests : AbstractOnServerIT() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_30)
|
||||
|
||||
capability = capability.apply {
|
||||
isWCFEnabled = CapabilityBooleanType.TRUE
|
||||
forbiddenFilenameExtensionJson = listOf(
|
||||
"""[" ",".",".part",".part"]""",
|
||||
"""[".",".part",".part"," "]""",
|
||||
@@ -238,4 +240,14 @@ class AutoRenameTests : AbstractOnServerIT() {
|
||||
val expectedFilename = "Foo.Bar.Baz"
|
||||
assert(result == expectedFilename) { "Expected $expectedFilename but got $result" }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun skipAutoRenameWhenWCFDisabled() {
|
||||
capability = capability.apply {
|
||||
isWCFEnabled = CapabilityBooleanType.FALSE
|
||||
}
|
||||
val filename = " readme.txt "
|
||||
val result = AutoRename.rename(filename, capability, isFolderPath = true)
|
||||
assert(result == filename) { "Expected $filename but got $result" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.nextcloud.utils
|
||||
|
||||
import com.nextcloud.utils.extensions.checkWCFRestrictions
|
||||
import com.owncloud.android.lib.resources.status.CapabilityBooleanType
|
||||
import com.owncloud.android.lib.resources.status.NextcloudVersion
|
||||
import com.owncloud.android.lib.resources.status.OCCapability
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
@Suppress("MagicNumber")
|
||||
class CheckWCFRestrictionsTests {
|
||||
|
||||
private fun createCapability(
|
||||
version: NextcloudVersion,
|
||||
isWCFEnabled: CapabilityBooleanType = CapabilityBooleanType.UNKNOWN
|
||||
): OCCapability = OCCapability().apply {
|
||||
this.versionMayor = version.majorVersionNumber
|
||||
this.isWCFEnabled = isWCFEnabled
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testReturnsFalseForVersionsOlderThan30() {
|
||||
val capability = createCapability(NextcloudVersion.nextcloud_29)
|
||||
assertFalse(capability.checkWCFRestrictions())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testReturnsTrueForVersion30WhenWCFAlwaysEnabled() {
|
||||
val capability = createCapability(NextcloudVersion.nextcloud_30)
|
||||
assertTrue(capability.checkWCFRestrictions())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testReturnsTrueForVersion31WhenWCFAlwaysEnabled() {
|
||||
val capability = createCapability(NextcloudVersion.nextcloud_31)
|
||||
assertTrue(capability.checkWCFRestrictions())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testReturnsTrueForVersion32WhenWCFEnabled() {
|
||||
val capability = createCapability(NextcloudVersion.nextcloud_32, CapabilityBooleanType.TRUE)
|
||||
assertTrue(capability.checkWCFRestrictions())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testReturnsFalseForVersion32WhenWCFDisabled() {
|
||||
val capability = createCapability(NextcloudVersion.nextcloud_32, CapabilityBooleanType.FALSE)
|
||||
assertFalse(capability.checkWCFRestrictions())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testReturnsFalseForVersion32WhenWCFIsUnknown() {
|
||||
val capability = createCapability(NextcloudVersion.nextcloud_32)
|
||||
assertFalse(capability.checkWCFRestrictions())
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ package com.nextcloud.utils
|
||||
import com.nextcloud.utils.fileNameValidator.FileNameValidator
|
||||
import com.owncloud.android.AbstractOnServerIT
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.lib.resources.status.CapabilityBooleanType
|
||||
import com.owncloud.android.lib.resources.status.NextcloudVersion
|
||||
import com.owncloud.android.lib.resources.status.OCCapability
|
||||
import org.junit.Assert.assertEquals
|
||||
@@ -27,6 +28,7 @@ class FileNameValidatorTests : AbstractOnServerIT() {
|
||||
@Before
|
||||
fun setup() {
|
||||
capability = capability.apply {
|
||||
isWCFEnabled = CapabilityBooleanType.TRUE
|
||||
forbiddenFilenamesJson = """[".htaccess",".htaccess"]"""
|
||||
forbiddenFilenameBaseNamesJson = """
|
||||
["con", "prn", "aux", "nul", "com0", "com1", "com2", "com3", "com4",
|
||||
@@ -228,4 +230,14 @@ class FileNameValidatorTests : AbstractOnServerIT() {
|
||||
val result = FileNameValidator.checkFolderAndFilePaths(folderPath, listOf(), capability, targetContext)
|
||||
assertFalse(result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun skipValidationWhenWCFDisabled() {
|
||||
capability = capability.apply {
|
||||
isWCFEnabled = CapabilityBooleanType.FALSE
|
||||
}
|
||||
val filename = "abc.txt"
|
||||
val result = FileNameValidator.checkFileName(filename, capability, targetContext)
|
||||
assertNull(result)
|
||||
}
|
||||
}
|
||||
@@ -324,7 +324,7 @@ abstract class FileUploaderIT : AbstractOnServerIT() {
|
||||
user,
|
||||
null,
|
||||
ocUpload2,
|
||||
NameCollisionPolicy.CANCEL,
|
||||
NameCollisionPolicy.SKIP,
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
@@ -373,7 +373,7 @@ abstract class FileUploaderIT : AbstractOnServerIT() {
|
||||
user,
|
||||
arrayOf(ocFile2),
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
NameCollisionPolicy.CANCEL
|
||||
NameCollisionPolicy.SKIP
|
||||
)
|
||||
|
||||
shortSleep()
|
||||
@@ -400,7 +400,7 @@ abstract class FileUploaderIT : AbstractOnServerIT() {
|
||||
user,
|
||||
null,
|
||||
ocUpload,
|
||||
NameCollisionPolicy.CANCEL,
|
||||
NameCollisionPolicy.SKIP,
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
@@ -426,7 +426,7 @@ abstract class FileUploaderIT : AbstractOnServerIT() {
|
||||
user,
|
||||
null,
|
||||
ocUpload2,
|
||||
NameCollisionPolicy.CANCEL,
|
||||
NameCollisionPolicy.SKIP,
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
@@ -477,7 +477,7 @@ abstract class FileUploaderIT : AbstractOnServerIT() {
|
||||
user,
|
||||
arrayOf(ocFile2),
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
NameCollisionPolicy.CANCEL
|
||||
NameCollisionPolicy.SKIP
|
||||
)
|
||||
|
||||
shortSleep()
|
||||
|
||||
@@ -32,6 +32,14 @@ class CapabilityUtilsIT : AbstractIT() {
|
||||
assertTrue(test(OwnCloudVersion.nextcloud_20))
|
||||
}
|
||||
|
||||
private fun test(version: OwnCloudVersion): Boolean =
|
||||
CapabilityUtils.checkOutdatedWarning(targetContext.resources, version, false)
|
||||
@Test
|
||||
fun checkOutdatedWarningWithSubscription() {
|
||||
assertFalse(test(NextcloudVersion.nextcloud_31))
|
||||
assertFalse(test(NextcloudVersion.nextcloud_30))
|
||||
|
||||
assertFalse(test(OwnCloudVersion.nextcloud_20, true))
|
||||
}
|
||||
|
||||
private fun test(version: OwnCloudVersion, hasValidSubscription: Boolean = false): Boolean =
|
||||
CapabilityUtils.checkOutdatedWarning(targetContext.resources, version, false, hasValidSubscription)
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
<?xml version="1.0" encoding="utf-8"?><!--
|
||||
~ Nextcloud - Android Client
|
||||
~
|
||||
~ SPDX-FileCopyrightText: 2024 TSI-mc <surinder.kumar@t-systems.com>
|
||||
@@ -53,8 +52,10 @@
|
||||
must request the FOREGROUND_SERVICE permission
|
||||
-->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <!-- Runtime permissions introduced in Android 13 (API level 33) -->
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" /> <!-- Needed for Android 14 (API level 34) -->
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES"
|
||||
tools:ignore="PhotoAndVideoPolicy,SelectedPhotoAccess" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO"
|
||||
tools:ignore="PhotoAndVideoPolicy,SelectedPhotoAccess" /> <!-- Needed for Android 14 (API level 34) -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<!--
|
||||
@@ -112,6 +113,7 @@
|
||||
android:name=".MainApp"
|
||||
android:allowBackup="false"
|
||||
android:dataExtractionRules="@xml/backup_rules"
|
||||
android:enableOnBackInvokedCallback="true"
|
||||
android:fullBackupContent="@xml/backup_config"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:installLocation="internalOnly"
|
||||
@@ -121,13 +123,13 @@
|
||||
android:requestLegacyExternalStorage="true"
|
||||
android:roundIcon="@mipmap/ic_launcher"
|
||||
android:supportsRtl="true"
|
||||
android:enableOnBackInvokedCallback="true"
|
||||
android:theme="@style/Theme.ownCloud.Toolbar"
|
||||
android:usesCleartextTraffic="true"
|
||||
tools:ignore="UnusedAttribute"
|
||||
tools:replace="android:allowBackup">
|
||||
|
||||
<meta-data android:name="android.content.APP_RESTRICTIONS"
|
||||
<meta-data
|
||||
android:name="android.content.APP_RESTRICTIONS"
|
||||
android:resource="@xml/app_config" />
|
||||
|
||||
<activity
|
||||
@@ -159,7 +161,9 @@
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
|
||||
<data android:scheme="http" />
|
||||
<data android:host="*" />
|
||||
<data
|
||||
android:host="*"
|
||||
tools:ignore="AppLinkUrlError" />
|
||||
<data android:pathPattern="/f/..*" />
|
||||
</intent-filter>
|
||||
<intent-filter android:autoVerify="true">
|
||||
@@ -169,7 +173,9 @@
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
|
||||
<data android:scheme="http" />
|
||||
<data android:host="*" />
|
||||
<data
|
||||
android:host="*"
|
||||
tools:ignore="AppLinkUrlError" />
|
||||
<data android:pathPattern="/..*/f/..*" />
|
||||
</intent-filter>
|
||||
<intent-filter android:autoVerify="true">
|
||||
@@ -179,7 +185,9 @@
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
|
||||
<data android:scheme="http" />
|
||||
<data android:host="*" />
|
||||
<data
|
||||
android:host="*"
|
||||
tools:ignore="AppLinkUrlError" />
|
||||
<data android:pathPattern="/..*/..*/f/..*" />
|
||||
</intent-filter>
|
||||
<intent-filter android:autoVerify="true">
|
||||
@@ -189,7 +197,9 @@
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
|
||||
<data android:scheme="http" />
|
||||
<data android:host="*" />
|
||||
<data
|
||||
android:host="*"
|
||||
tools:ignore="AppLinkUrlError" />
|
||||
<data android:pathPattern="/..*/..*/..*/f/..*" />
|
||||
</intent-filter>
|
||||
<intent-filter android:autoVerify="true">
|
||||
@@ -199,7 +209,9 @@
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
|
||||
<data android:scheme="https" />
|
||||
<data android:host="*" />
|
||||
<data
|
||||
android:host="*"
|
||||
tools:ignore="AppLinkUrlError" />
|
||||
<data android:pathPattern="/f/..*" />
|
||||
</intent-filter>
|
||||
<intent-filter android:autoVerify="true">
|
||||
@@ -209,7 +221,9 @@
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
|
||||
<data android:scheme="https" />
|
||||
<data android:host="*" />
|
||||
<data
|
||||
android:host="*"
|
||||
tools:ignore="AppLinkUrlError" />
|
||||
<data android:pathPattern="/..*/f/..*" />
|
||||
</intent-filter>
|
||||
<intent-filter android:autoVerify="true">
|
||||
@@ -219,7 +233,9 @@
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
|
||||
<data android:scheme="https" />
|
||||
<data android:host="*" />
|
||||
<data
|
||||
android:host="*"
|
||||
tools:ignore="AppLinkUrlError" />
|
||||
<data android:pathPattern="/..*/..*/f/..*" />
|
||||
</intent-filter>
|
||||
<intent-filter android:autoVerify="true">
|
||||
@@ -229,7 +245,9 @@
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
|
||||
<data android:scheme="https" />
|
||||
<data android:host="*" />
|
||||
<data
|
||||
android:host="*"
|
||||
tools:ignore="AppLinkUrlError" />
|
||||
<data android:pathPattern="/..*/..*/..*/f/..*" />
|
||||
<!-- path pattern to handle deep link -->
|
||||
<data android:pathPattern="/app/..*" />
|
||||
@@ -352,8 +370,8 @@
|
||||
</activity>
|
||||
<activity
|
||||
android:name=".ui.activity.SettingsActivity"
|
||||
android:exported="false"
|
||||
android:enableOnBackInvokedCallback="false"
|
||||
android:exported="false"
|
||||
android:theme="@style/PreferenceTheme" />
|
||||
<activity
|
||||
android:name=".ui.preview.PreviewImageActivity"
|
||||
@@ -367,11 +385,11 @@
|
||||
|
||||
<service
|
||||
android:name="com.nextcloud.client.media.BackgroundPlayerService"
|
||||
android:foregroundServiceType="mediaPlayback"
|
||||
android:exported="true"
|
||||
android:foregroundServiceType="mediaPlayback"
|
||||
tools:ignore="ExportedService">
|
||||
<intent-filter>
|
||||
<action android:name="androidx.media3.session.MediaSessionService"/>
|
||||
<action android:name="androidx.media3.session.MediaSessionService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
@@ -585,7 +603,9 @@
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<receiver android:name="com.nextcloud.client.jobs.folderDownload.FolderDownloadWorkerReceiver" android:exported="false" />
|
||||
<receiver
|
||||
android:name="com.nextcloud.client.jobs.folderDownload.FolderDownloadWorkerReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<activity
|
||||
android:name=".ui.activity.CopyToClipboardActivity"
|
||||
|
||||
@@ -9,12 +9,28 @@
|
||||
*/
|
||||
package com.nextcloud.android.sso;
|
||||
|
||||
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
|
||||
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
|
||||
import org.apache.commons.httpclient.methods.PostMethod;
|
||||
import org.apache.commons.httpclient.methods.RequestEntity;
|
||||
import org.apache.commons.httpclient.util.EncodingUtil;
|
||||
|
||||
import java.util.Vector;
|
||||
|
||||
public class PatchMethod extends PostMethod {
|
||||
|
||||
/**
|
||||
* The buffered request body consisting of <code>NameValuePair</code>s.
|
||||
*/
|
||||
private Vector params = new Vector();
|
||||
|
||||
/**
|
||||
* No-arg constructor.
|
||||
*/
|
||||
public PatchMethod() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor specifying a URI.
|
||||
*
|
||||
@@ -42,7 +58,11 @@ public class PatchMethod extends PostMethod {
|
||||
* @since 2.0beta1
|
||||
*/
|
||||
protected boolean hasRequestContent() {
|
||||
return super.hasRequestContent();
|
||||
if (!this.params.isEmpty()) {
|
||||
return true;
|
||||
} else {
|
||||
return super.hasRequestContent();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -51,6 +71,7 @@ public class PatchMethod extends PostMethod {
|
||||
* @since 2.0beta1
|
||||
*/
|
||||
protected void clearRequestBody() {
|
||||
this.params.clear();
|
||||
super.clearRequestBody();
|
||||
}
|
||||
|
||||
@@ -61,6 +82,19 @@ public class PatchMethod extends PostMethod {
|
||||
* @since 3.0
|
||||
*/
|
||||
protected RequestEntity generateRequestEntity() {
|
||||
return super.generateRequestEntity();
|
||||
if (!this.params.isEmpty()) {
|
||||
// Use a ByteArrayRequestEntity instead of a StringRequestEntity.
|
||||
// This is to avoid potential encoding issues. Form url encoded strings
|
||||
// are ASCII by definition but the content type may not be. Treating the content
|
||||
// as bytes allows us to keep the current charset without worrying about how
|
||||
// this charset will effect the encoding of the form url encoded string.
|
||||
String content = EncodingUtil.formUrlEncode(getParameters(), getRequestCharSet());
|
||||
return new ByteArrayRequestEntity(
|
||||
EncodingUtil.getAsciiBytes(content),
|
||||
FORM_URL_ENCODED_CONTENT_TYPE
|
||||
);
|
||||
} else {
|
||||
return super.generateRequestEntity();
|
||||
}
|
||||
}
|
||||
}
|
||||
+142
-128
@@ -8,40 +8,55 @@
|
||||
package com.nextcloud.client.assistant
|
||||
|
||||
import android.app.Activity
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FabPosition
|
||||
import androidx.compose.material3.FloatingActionButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.pulltorefresh.PullToRefreshState
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.pulltorefresh.pullToRefresh
|
||||
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.ColorFilter
|
||||
import androidx.compose.ui.res.colorResource
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.tooling.preview.Preview
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.nextcloud.client.assistant.component.AddTaskAlertDialog
|
||||
import com.nextcloud.client.assistant.component.CenterText
|
||||
import com.nextcloud.client.assistant.extensions.getInputTitle
|
||||
import com.nextcloud.client.assistant.model.ScreenOverlayState
|
||||
import com.nextcloud.client.assistant.model.ScreenState
|
||||
import com.nextcloud.client.assistant.repository.AssistantMockRepository
|
||||
import com.nextcloud.client.assistant.repository.local.MockAssistantLocalRepository
|
||||
import com.nextcloud.client.assistant.repository.remote.MockAssistantRemoteRepository
|
||||
import com.nextcloud.client.assistant.task.TaskView
|
||||
import com.nextcloud.client.assistant.taskTypes.TaskTypesRow
|
||||
import com.nextcloud.ui.composeActivity.ComposeActivity
|
||||
@@ -51,10 +66,11 @@ import com.owncloud.android.R
|
||||
import com.owncloud.android.lib.resources.assistant.v2.model.Task
|
||||
import com.owncloud.android.lib.resources.assistant.v2.model.TaskTypeData
|
||||
import com.owncloud.android.lib.resources.status.OCCapability
|
||||
import com.owncloud.android.utils.DisplayUtils
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
private const val PULL_TO_REFRESH_DELAY = 1500L
|
||||
|
||||
@Suppress("LongMethod")
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
@@ -68,94 +84,98 @@ fun AssistantScreen(viewModel: AssistantViewModel, capability: OCCapability, act
|
||||
val taskTypes by viewModel.taskTypes.collectAsState()
|
||||
val scope = rememberCoroutineScope()
|
||||
val pullRefreshState = rememberPullToRefreshState()
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
|
||||
@Suppress("MagicNumber")
|
||||
Box(
|
||||
LaunchedEffect(messageId) {
|
||||
messageId?.let {
|
||||
snackbarHostState.showSnackbar(activity.getString(it))
|
||||
viewModel.updateSnackbarMessage(null)
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
viewModel.startTaskListPolling()
|
||||
}
|
||||
|
||||
DisposableEffect(Unit) {
|
||||
onDispose {
|
||||
viewModel.stopTaskListPolling()
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
modifier = Modifier.pullToRefresh(
|
||||
screenState == ScreenState.Refreshing,
|
||||
false,
|
||||
pullRefreshState,
|
||||
onRefresh = {
|
||||
scope.launch {
|
||||
delay(1500)
|
||||
delay(PULL_TO_REFRESH_DELAY)
|
||||
viewModel.fetchTaskList()
|
||||
}
|
||||
}
|
||||
)
|
||||
) {
|
||||
ShowScreenState(screenState, selectedTaskType, taskTypes, viewModel, filteredTaskList, capability)
|
||||
|
||||
ShowLinearProgressIndicator(screenState, pullRefreshState)
|
||||
|
||||
AddFloatingActionButton(
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomEnd)
|
||||
.padding(16.dp),
|
||||
selectedTaskType,
|
||||
viewModel
|
||||
)
|
||||
}
|
||||
|
||||
showSnackBarMessage(messageId, activity, viewModel)
|
||||
ShowOverlayState(screenOverlayState, activity, viewModel)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ShowScreenState(
|
||||
screenState: ScreenState?,
|
||||
selectedTaskType: TaskTypeData?,
|
||||
taskTypes: List<TaskTypeData>?,
|
||||
viewModel: AssistantViewModel,
|
||||
filteredTaskList: List<Task>?,
|
||||
capability: OCCapability
|
||||
) {
|
||||
when (screenState) {
|
||||
ScreenState.Refreshing -> {
|
||||
CenterText(text = stringResource(id = R.string.assistant_screen_loading))
|
||||
),
|
||||
topBar = {
|
||||
taskTypes?.let {
|
||||
TaskTypesRow(selectedTaskType, data = it) { task ->
|
||||
viewModel.selectTaskType(task)
|
||||
}
|
||||
}
|
||||
},
|
||||
floatingActionButton = {
|
||||
if (!taskTypes.isNullOrEmpty()) {
|
||||
AddTaskButton(
|
||||
selectedTaskType,
|
||||
viewModel
|
||||
)
|
||||
}
|
||||
},
|
||||
floatingActionButtonPosition = FabPosition.EndOverlay,
|
||||
snackbarHost = {
|
||||
SnackbarHost(snackbarHostState)
|
||||
}
|
||||
) { paddingValues ->
|
||||
when (screenState) {
|
||||
is ScreenState.EmptyContent -> {
|
||||
val state = (screenState as ScreenState.EmptyContent)
|
||||
EmptyContent(
|
||||
paddingValues,
|
||||
state.iconId,
|
||||
state.descriptionId
|
||||
)
|
||||
}
|
||||
|
||||
ScreenState.EmptyContent -> {
|
||||
EmptyTaskList(selectedTaskType, taskTypes, viewModel)
|
||||
}
|
||||
ScreenState.Content -> {
|
||||
AssistantContent(
|
||||
paddingValues,
|
||||
filteredTaskList ?: listOf(),
|
||||
viewModel,
|
||||
capability
|
||||
)
|
||||
}
|
||||
|
||||
ScreenState.Content -> {
|
||||
AssistantContent(
|
||||
filteredTaskList ?: listOf(),
|
||||
taskTypes,
|
||||
selectedTaskType,
|
||||
viewModel,
|
||||
capability
|
||||
else -> EmptyContent(
|
||||
paddingValues,
|
||||
R.drawable.spinner_inner,
|
||||
R.string.assistant_screen_loading
|
||||
)
|
||||
}
|
||||
|
||||
null -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun ShowLinearProgressIndicator(screenState: ScreenState?, pullToRefreshState: PullToRefreshState) {
|
||||
if (screenState == ScreenState.Refreshing) {
|
||||
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||
} else {
|
||||
LinearProgressIndicator(
|
||||
progress = { pullToRefreshState.distanceFraction },
|
||||
progress = { pullRefreshState.distanceFraction },
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
|
||||
OverlayState(screenOverlayState, activity, viewModel)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AddFloatingActionButton(
|
||||
modifier: Modifier,
|
||||
selectedTaskType: TaskTypeData?,
|
||||
viewModel: AssistantViewModel
|
||||
) {
|
||||
private fun AddTaskButton(selectedTaskType: TaskTypeData?, viewModel: AssistantViewModel) {
|
||||
FloatingActionButton(
|
||||
modifier = modifier,
|
||||
onClick = {
|
||||
selectedTaskType?.let {
|
||||
val newState = ScreenOverlayState.AddTask(it, "")
|
||||
viewModel.updateScreenState(newState)
|
||||
viewModel.updateTaskListScreenState(newState)
|
||||
}
|
||||
}
|
||||
) {
|
||||
@@ -163,20 +183,9 @@ private fun AddFloatingActionButton(
|
||||
}
|
||||
}
|
||||
|
||||
private fun showSnackBarMessage(messageId: Int?, activity: Activity, viewModel: AssistantViewModel) {
|
||||
messageId?.let {
|
||||
DisplayUtils.showSnackMessage(
|
||||
activity,
|
||||
activity.getString(it)
|
||||
)
|
||||
|
||||
viewModel.updateSnackbarMessage(null)
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("LongMethod")
|
||||
@Composable
|
||||
private fun ShowOverlayState(state: ScreenOverlayState?, activity: Activity, viewModel: AssistantViewModel) {
|
||||
private fun OverlayState(state: ScreenOverlayState?, activity: Activity, viewModel: AssistantViewModel) {
|
||||
when (state) {
|
||||
is ScreenOverlayState.AddTask -> {
|
||||
AddTaskAlertDialog(
|
||||
@@ -189,7 +198,7 @@ private fun ShowOverlayState(state: ScreenOverlayState?, activity: Activity, vie
|
||||
}
|
||||
},
|
||||
dismiss = {
|
||||
viewModel.updateScreenState(null)
|
||||
viewModel.updateTaskListScreenState(null)
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -198,22 +207,22 @@ private fun ShowOverlayState(state: ScreenOverlayState?, activity: Activity, vie
|
||||
SimpleAlertDialog(
|
||||
title = stringResource(id = R.string.assistant_screen_delete_task_alert_dialog_title),
|
||||
description = stringResource(id = R.string.assistant_screen_delete_task_alert_dialog_description),
|
||||
dismiss = { viewModel.updateScreenState(null) },
|
||||
dismiss = { viewModel.updateTaskListScreenState(null) },
|
||||
onComplete = { viewModel.deleteTask(state.id) }
|
||||
)
|
||||
}
|
||||
|
||||
is ScreenOverlayState.TaskActions -> {
|
||||
val actions = state.getActions(activity, onEditCompleted = { addTask ->
|
||||
viewModel.updateScreenState(addTask)
|
||||
viewModel.updateTaskListScreenState(addTask)
|
||||
}, onDeleteCompleted = { deleteTask ->
|
||||
viewModel.updateScreenState(deleteTask)
|
||||
viewModel.updateTaskListScreenState(deleteTask)
|
||||
})
|
||||
|
||||
MoreActionsBottomSheet(
|
||||
title = state.task.getInputTitle(),
|
||||
actions = actions,
|
||||
dismiss = { viewModel.updateScreenState(null) }
|
||||
dismiss = { viewModel.updateTaskListScreenState(null) }
|
||||
)
|
||||
}
|
||||
|
||||
@@ -223,62 +232,59 @@ private fun ShowOverlayState(state: ScreenOverlayState?, activity: Activity, vie
|
||||
|
||||
@Composable
|
||||
private fun AssistantContent(
|
||||
paddingValues: PaddingValues,
|
||||
taskList: List<Task>,
|
||||
taskTypes: List<TaskTypeData>?,
|
||||
selectedTaskType: TaskTypeData?,
|
||||
viewModel: AssistantViewModel,
|
||||
capability: OCCapability
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
taskTypes?.let {
|
||||
TaskTypesRow(selectedTaskType, data = taskTypes) { task ->
|
||||
viewModel.selectTaskType(task)
|
||||
}
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(12.dp)
|
||||
) {
|
||||
items(taskList) { task ->
|
||||
TaskView(
|
||||
task,
|
||||
capability,
|
||||
showTaskActions = {
|
||||
val newState = ScreenOverlayState.TaskActions(task)
|
||||
viewModel.updateScreenState(newState)
|
||||
}
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(paddingValues)
|
||||
.padding(12.dp),
|
||||
verticalArrangement = Arrangement.Top,
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
items(taskList, key = { it.id }) { task ->
|
||||
TaskView(
|
||||
task,
|
||||
capability,
|
||||
showTaskActions = {
|
||||
val newState = ScreenOverlayState.TaskActions(task)
|
||||
viewModel.updateTaskListScreenState(newState)
|
||||
}
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EmptyTaskList(
|
||||
selectedTaskType: TaskTypeData?,
|
||||
taskTypes: List<TaskTypeData>?,
|
||||
viewModel: AssistantViewModel
|
||||
) {
|
||||
private fun EmptyContent(paddingValues: PaddingValues, iconId: Int?, descriptionId: Int) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp)
|
||||
.padding(paddingValues)
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.Center,
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
taskTypes?.let {
|
||||
TaskTypesRow(selectedTaskType, data = taskTypes) { task ->
|
||||
viewModel.selectTaskType(task)
|
||||
}
|
||||
iconId?.let {
|
||||
Image(
|
||||
painter = painterResource(id = iconId),
|
||||
modifier = Modifier.size(32.dp),
|
||||
colorFilter = ColorFilter.tint(color = colorResource(R.color.text_color)),
|
||||
contentDescription = "empty content icon"
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
CenterText(
|
||||
text = stringResource(
|
||||
id = R.string.assistant_screen_create_a_new_task_from_bottom_right_text
|
||||
)
|
||||
Text(
|
||||
text = stringResource(descriptionId),
|
||||
fontSize = 18.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
color = colorResource(R.color.text_color)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -287,11 +293,10 @@ private fun EmptyTaskList(
|
||||
@Composable
|
||||
@Preview
|
||||
private fun AssistantScreenPreview() {
|
||||
val mockRepository = AssistantMockRepository()
|
||||
MaterialTheme(
|
||||
content = {
|
||||
AssistantScreen(
|
||||
viewModel = AssistantViewModel(repository = mockRepository),
|
||||
viewModel = getMockViewModel(false),
|
||||
activity = ComposeActivity(),
|
||||
capability = OCCapability().apply {
|
||||
versionMayor = 30
|
||||
@@ -305,11 +310,10 @@ private fun AssistantScreenPreview() {
|
||||
@Composable
|
||||
@Preview
|
||||
private fun AssistantEmptyScreenPreview() {
|
||||
val mockRepository = AssistantMockRepository(giveEmptyTasks = true)
|
||||
MaterialTheme(
|
||||
content = {
|
||||
AssistantScreen(
|
||||
viewModel = AssistantViewModel(repository = mockRepository),
|
||||
viewModel = getMockViewModel(true),
|
||||
activity = ComposeActivity(),
|
||||
capability = OCCapability().apply {
|
||||
versionMayor = 30
|
||||
@@ -318,3 +322,13 @@ private fun AssistantEmptyScreenPreview() {
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private fun getMockViewModel(giveEmptyTasks: Boolean): AssistantViewModel {
|
||||
val mockLocalRepository = MockAssistantLocalRepository()
|
||||
val mockRemoteRepository = MockAssistantRemoteRepository(giveEmptyTasks)
|
||||
return AssistantViewModel(
|
||||
accountName = "test:localhost",
|
||||
remoteRepository = mockRemoteRepository,
|
||||
localRepository = mockLocalRepository
|
||||
)
|
||||
}
|
||||
@@ -11,18 +11,31 @@ import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.nextcloud.client.assistant.model.ScreenOverlayState
|
||||
import com.nextcloud.client.assistant.model.ScreenState
|
||||
import com.nextcloud.client.assistant.repository.AssistantRepositoryType
|
||||
import com.nextcloud.client.assistant.repository.local.AssistantLocalRepository
|
||||
import com.nextcloud.client.assistant.repository.remote.AssistantRemoteRepository
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.lib.resources.assistant.v2.model.Task
|
||||
import com.owncloud.android.lib.resources.assistant.v2.model.TaskTypeData
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class AssistantViewModel(private val repository: AssistantRepositoryType) : ViewModel() {
|
||||
class AssistantViewModel(
|
||||
private val accountName: String,
|
||||
private val remoteRepository: AssistantRemoteRepository,
|
||||
private val localRepository: AssistantLocalRepository
|
||||
) : ViewModel() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AssistantViewModel"
|
||||
private const val TASK_LIST_POLLING_INTERVAL_MS = 15_000L
|
||||
}
|
||||
|
||||
private val _screenState = MutableStateFlow<ScreenState?>(null)
|
||||
val screenState: StateFlow<ScreenState?> = _screenState
|
||||
@@ -44,14 +57,54 @@ class AssistantViewModel(private val repository: AssistantRepositoryType) : View
|
||||
private val _filteredTaskList = MutableStateFlow<List<Task>?>(null)
|
||||
val filteredTaskList: StateFlow<List<Task>?> = _filteredTaskList
|
||||
|
||||
private var taskPollingJob: Job? = null
|
||||
|
||||
init {
|
||||
fetchTaskTypes()
|
||||
}
|
||||
|
||||
// region task polling
|
||||
fun startTaskListPolling() {
|
||||
stopTaskListPolling()
|
||||
|
||||
taskPollingJob = viewModelScope.launch(Dispatchers.IO) {
|
||||
try {
|
||||
while (isActive) {
|
||||
Log_OC.d(TAG, "Polling task list...")
|
||||
fetchTaskListSuspending()
|
||||
delay(TASK_LIST_POLLING_INTERVAL_MS)
|
||||
}
|
||||
} finally {
|
||||
Log_OC.d(TAG, "Polling coroutine cancelled")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun stopTaskListPolling() {
|
||||
taskPollingJob?.cancel()
|
||||
taskPollingJob = null
|
||||
}
|
||||
// endregion
|
||||
|
||||
private suspend fun fetchTaskListSuspending() {
|
||||
val cachedTasks = localRepository.getCachedTasks(accountName)
|
||||
if (cachedTasks.isNotEmpty()) {
|
||||
_filteredTaskList.value = cachedTasks.sortedByDescending { it.id }
|
||||
}
|
||||
|
||||
val taskType = _selectedTaskType.value?.id ?: return
|
||||
val result = remoteRepository.getTaskList(taskType)
|
||||
if (result != null) {
|
||||
taskList = result
|
||||
_filteredTaskList.value = taskList?.sortedByDescending { it.id }
|
||||
localRepository.cacheTasks(result, accountName)
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("MagicNumber")
|
||||
fun createTask(input: String, taskType: TaskTypeData) {
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
val result = repository.createTask(input, taskType)
|
||||
val result = remoteRepository.createTask(input, taskType)
|
||||
|
||||
val messageId = if (result.isSuccess) {
|
||||
R.string.assistant_screen_task_create_success_message
|
||||
@@ -76,15 +129,11 @@ class AssistantViewModel(private val repository: AssistantRepositoryType) : View
|
||||
|
||||
private fun fetchTaskTypes() {
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
val taskTypesResult = repository.getTaskTypes()
|
||||
|
||||
if (taskTypesResult == null) {
|
||||
updateSnackbarMessage(R.string.assistant_screen_task_types_error_state_message)
|
||||
return@launch
|
||||
}
|
||||
|
||||
if (taskTypesResult.isEmpty()) {
|
||||
updateSnackbarMessage(R.string.assistant_screen_task_list_empty_message)
|
||||
val taskTypesResult = remoteRepository.getTaskTypes()
|
||||
if (taskTypesResult == null || taskTypesResult.isEmpty()) {
|
||||
_screenState.update {
|
||||
ScreenState.emptyTaskTypes()
|
||||
}
|
||||
return@launch
|
||||
}
|
||||
|
||||
@@ -98,12 +147,17 @@ class AssistantViewModel(private val repository: AssistantRepositoryType) : View
|
||||
|
||||
fun fetchTaskList() {
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
_screenState.update {
|
||||
ScreenState.Refreshing
|
||||
// Try cached data first
|
||||
val cachedTasks = localRepository.getCachedTasks(accountName)
|
||||
if (cachedTasks.isNotEmpty()) {
|
||||
_filteredTaskList.update {
|
||||
cachedTasks.sortedByDescending { it.id }
|
||||
}
|
||||
updateTaskListScreenState()
|
||||
}
|
||||
|
||||
val taskType = _selectedTaskType.value?.id ?: return@launch
|
||||
val result = repository.getTaskList(taskType)
|
||||
val result = remoteRepository.getTaskList(taskType)
|
||||
if (result != null) {
|
||||
taskList = result
|
||||
_filteredTaskList.update {
|
||||
@@ -111,19 +165,21 @@ class AssistantViewModel(private val repository: AssistantRepositoryType) : View
|
||||
task.id
|
||||
}
|
||||
}
|
||||
|
||||
localRepository.cacheTasks(result, accountName)
|
||||
updateSnackbarMessage(null)
|
||||
} else {
|
||||
updateSnackbarMessage(R.string.assistant_screen_task_list_error_state_message)
|
||||
}
|
||||
|
||||
updateScreenState()
|
||||
updateTaskListScreenState()
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateScreenState() {
|
||||
private fun updateTaskListScreenState() {
|
||||
_screenState.update {
|
||||
if (_filteredTaskList.value?.isEmpty() == true) {
|
||||
ScreenState.EmptyContent
|
||||
ScreenState.emptyTaskList()
|
||||
} else {
|
||||
ScreenState.Content
|
||||
}
|
||||
@@ -132,7 +188,7 @@ class AssistantViewModel(private val repository: AssistantRepositoryType) : View
|
||||
|
||||
fun deleteTask(id: Long) {
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
val result = repository.deleteTask(id)
|
||||
val result = remoteRepository.deleteTask(id)
|
||||
|
||||
val messageId = if (result.isSuccess) {
|
||||
R.string.assistant_screen_task_delete_success_message
|
||||
@@ -144,6 +200,7 @@ class AssistantViewModel(private val repository: AssistantRepositoryType) : View
|
||||
|
||||
if (result.isSuccess) {
|
||||
removeTaskFromList(id)
|
||||
localRepository.deleteTask(id, accountName)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -154,7 +211,7 @@ class AssistantViewModel(private val repository: AssistantRepositoryType) : View
|
||||
}
|
||||
}
|
||||
|
||||
fun updateScreenState(value: ScreenOverlayState?) {
|
||||
fun updateTaskListScreenState(value: ScreenOverlayState?) {
|
||||
_screenOverlayState.update {
|
||||
value
|
||||
}
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2024 Alper Ozturk <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.nextcloud.client.assistant.component
|
||||
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.colorResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.owncloud.android.R
|
||||
|
||||
@Composable
|
||||
fun CenterText(text: String) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
text = text,
|
||||
fontSize = 18.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
color = colorResource(R.color.text_color)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,24 @@
|
||||
|
||||
package com.nextcloud.client.assistant.model
|
||||
|
||||
enum class ScreenState {
|
||||
Refreshing,
|
||||
EmptyContent,
|
||||
Content
|
||||
import com.owncloud.android.R
|
||||
|
||||
sealed class ScreenState {
|
||||
data object Loading : ScreenState()
|
||||
|
||||
data object Content : ScreenState()
|
||||
|
||||
data class EmptyContent(val iconId: Int?, val descriptionId: Int) : ScreenState()
|
||||
|
||||
companion object {
|
||||
fun emptyTaskTypes(): ScreenState = EmptyContent(
|
||||
descriptionId = R.string.assistant_screen_task_list_empty_warning,
|
||||
iconId = null
|
||||
)
|
||||
|
||||
fun emptyTaskList(): ScreenState = EmptyContent(
|
||||
descriptionId = R.string.assistant_screen_create_a_new_task_from_bottom_right_text,
|
||||
iconId = null
|
||||
)
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.client.assistant.repository.local
|
||||
|
||||
import com.owncloud.android.lib.resources.assistant.v2.model.Task
|
||||
|
||||
interface AssistantLocalRepository {
|
||||
suspend fun cacheTasks(tasks: List<Task>, accountName: String)
|
||||
suspend fun getCachedTasks(accountName: String): List<Task>
|
||||
suspend fun insertTask(task: Task, accountName: String)
|
||||
suspend fun deleteTask(id: Long, accountName: String)
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.client.assistant.repository.local
|
||||
|
||||
import com.nextcloud.client.database.dao.AssistantDao
|
||||
import com.nextcloud.client.database.entity.AssistantEntity
|
||||
import com.owncloud.android.lib.resources.assistant.v2.model.Task
|
||||
import com.owncloud.android.lib.resources.assistant.v2.model.TaskInput
|
||||
import com.owncloud.android.lib.resources.assistant.v2.model.TaskOutput
|
||||
|
||||
class AssistantLocalRepositoryImpl(private val assistantDao: AssistantDao) : AssistantLocalRepository {
|
||||
|
||||
override suspend fun cacheTasks(tasks: List<Task>, accountName: String) {
|
||||
val entities = tasks.map { it.toEntity(accountName) }
|
||||
assistantDao.insertAssistantTasks(entities)
|
||||
}
|
||||
|
||||
override suspend fun getCachedTasks(accountName: String): List<Task> {
|
||||
val entities = assistantDao.getAssistantTasksByAccount(accountName)
|
||||
return entities.map { it.toTask() }
|
||||
}
|
||||
|
||||
override suspend fun insertTask(task: Task, accountName: String) {
|
||||
assistantDao.insertAssistantTask(task.toEntity(accountName))
|
||||
}
|
||||
|
||||
override suspend fun deleteTask(id: Long, accountName: String) {
|
||||
val cached = assistantDao.getAssistantTasksByAccount(accountName).firstOrNull { it.id == id } ?: return
|
||||
assistantDao.deleteAssistantTask(cached)
|
||||
}
|
||||
|
||||
// region Mapping helpers
|
||||
private fun Task.toEntity(accountName: String): AssistantEntity = AssistantEntity(
|
||||
id = this.id,
|
||||
accountName = accountName,
|
||||
type = this.type,
|
||||
status = this.status,
|
||||
userId = this.userId,
|
||||
appId = this.appId,
|
||||
input = this.input?.input,
|
||||
output = this.output?.output,
|
||||
completionExpectedAt = this.completionExpectedAt,
|
||||
progress = this.progress,
|
||||
lastUpdated = this.lastUpdated,
|
||||
scheduledAt = this.scheduledAt,
|
||||
endedAt = this.endedAt
|
||||
)
|
||||
|
||||
private fun AssistantEntity.toTask(): Task = Task(
|
||||
id = this.id,
|
||||
type = this.type,
|
||||
status = this.status,
|
||||
userId = this.userId,
|
||||
appId = this.appId,
|
||||
input = TaskInput(input = this.input),
|
||||
output = TaskOutput(output = this.output),
|
||||
completionExpectedAt = this.completionExpectedAt,
|
||||
progress = this.progress,
|
||||
lastUpdated = this.lastUpdated,
|
||||
scheduledAt = this.scheduledAt,
|
||||
endedAt = this.endedAt
|
||||
)
|
||||
// endregion
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.client.assistant.repository.local
|
||||
|
||||
import com.owncloud.android.lib.resources.assistant.v2.model.Task
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
class MockAssistantLocalRepository : AssistantLocalRepository {
|
||||
|
||||
private val tasks = mutableListOf<Task>()
|
||||
private val mutex = Mutex()
|
||||
|
||||
override suspend fun cacheTasks(tasks: List<Task>, accountName: String) {
|
||||
mutex.withLock {
|
||||
this.tasks.clear()
|
||||
this.tasks.addAll(tasks)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getCachedTasks(accountName: String): List<Task> = mutex.withLock { tasks.toList() }
|
||||
|
||||
override suspend fun insertTask(task: Task, accountName: String) {
|
||||
mutex.withLock { tasks.add(task) }
|
||||
}
|
||||
|
||||
override suspend fun deleteTask(id: Long, accountName: String) {
|
||||
mutex.withLock { tasks.removeAll { it.id == id } }
|
||||
}
|
||||
}
|
||||
+7
-6
@@ -1,21 +1,22 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2024 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.nextcloud.client.assistant.repository
|
||||
|
||||
package com.nextcloud.client.assistant.repository.remote
|
||||
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult
|
||||
import com.owncloud.android.lib.resources.assistant.v2.model.Task
|
||||
import com.owncloud.android.lib.resources.assistant.v2.model.TaskTypeData
|
||||
|
||||
interface AssistantRepositoryType {
|
||||
interface AssistantRemoteRepository {
|
||||
fun getTaskTypes(): List<TaskTypeData>?
|
||||
|
||||
fun createTask(input: String, taskType: TaskTypeData): RemoteOperationResult<Void>
|
||||
|
||||
fun getTaskList(taskType: String): List<com.owncloud.android.lib.resources.assistant.v2.model.Task>?
|
||||
fun getTaskList(taskType: String): List<Task>?
|
||||
|
||||
fun deleteTask(id: Long): RemoteOperationResult<Void>
|
||||
}
|
||||
+5
-5
@@ -1,11 +1,10 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2024 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.nextcloud.client.assistant.repository
|
||||
package com.nextcloud.client.assistant.repository.remote
|
||||
|
||||
import com.nextcloud.common.NextcloudClient
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult
|
||||
@@ -24,7 +23,8 @@ import com.owncloud.android.lib.resources.assistant.v2.model.TaskTypeData
|
||||
import com.owncloud.android.lib.resources.status.NextcloudVersion
|
||||
import com.owncloud.android.lib.resources.status.OCCapability
|
||||
|
||||
class AssistantRepository(private val client: NextcloudClient, capability: OCCapability) : AssistantRepositoryType {
|
||||
class AssistantRemoteRepositoryImpl(private val client: NextcloudClient, capability: OCCapability) :
|
||||
AssistantRemoteRepository {
|
||||
|
||||
private val supportsV2 = capability.version.isNewerOrEqual(NextcloudVersion.nextcloud_30)
|
||||
|
||||
+4
-5
@@ -1,11 +1,10 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2024 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.nextcloud.client.assistant.repository
|
||||
package com.nextcloud.client.assistant.repository.remote
|
||||
|
||||
import com.nextcloud.utils.extensions.getRandomString
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult
|
||||
@@ -16,7 +15,7 @@ import com.owncloud.android.lib.resources.assistant.v2.model.TaskOutput
|
||||
import com.owncloud.android.lib.resources.assistant.v2.model.TaskTypeData
|
||||
|
||||
@Suppress("MagicNumber")
|
||||
class AssistantMockRepository(private val giveEmptyTasks: Boolean = false) : AssistantRepositoryType {
|
||||
class MockAssistantRemoteRepository(private val giveEmptyTasks: Boolean = false) : AssistantRemoteRepository {
|
||||
override fun getTaskTypes(): List<TaskTypeData> = listOf(
|
||||
TaskTypeData(
|
||||
id = "core:text2text",
|
||||
+49
-18
@@ -8,7 +8,9 @@
|
||||
package com.nextcloud.client.assistant.taskDetail
|
||||
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
@@ -17,6 +19,8 @@ import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
@@ -28,9 +32,11 @@ import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.colorResource
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.tooling.preview.Preview
|
||||
@@ -54,29 +60,54 @@ fun TaskDetailBottomSheet(task: Task, showTaskActions: () -> Unit, dismiss: () -
|
||||
onDismissRequest = { dismiss() },
|
||||
sheetState = sheetState
|
||||
) {
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp)
|
||||
) {
|
||||
stickyHeader {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Spacer(modifier = Modifier.weight(1f))
|
||||
Box {
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp)
|
||||
) {
|
||||
stickyHeader {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Spacer(modifier = Modifier.weight(1f))
|
||||
|
||||
IconButton(onClick = showTaskActions) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.MoreVert,
|
||||
contentDescription = "More button",
|
||||
tint = colorResource(R.color.text_color)
|
||||
)
|
||||
IconButton(onClick = showTaskActions) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.MoreVert,
|
||||
contentDescription = "More button",
|
||||
tint = colorResource(R.color.text_color)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
InputOutputCard(task)
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
InputOutputCard(task)
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.fillMaxWidth()
|
||||
.padding(bottom = 16.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.ic_assistant),
|
||||
contentDescription = "assistant icon",
|
||||
modifier = Modifier.size(12.dp)
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
|
||||
Text(
|
||||
text = stringResource(R.string.assistant_generation_warning),
|
||||
color = colorResource(R.color.text_color),
|
||||
fontSize = 12.sp
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,10 +8,9 @@
|
||||
package com.nextcloud.client.assistant.taskTypes
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import androidx.compose.material3.ScrollableTabRow
|
||||
import androidx.compose.material3.PrimaryScrollableTabRow
|
||||
import androidx.compose.material3.Tab
|
||||
import androidx.compose.material3.TabRowDefaults
|
||||
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -26,13 +25,13 @@ import com.owncloud.android.lib.resources.assistant.v2.model.TaskTypeData
|
||||
fun TaskTypesRow(selectedTaskType: TaskTypeData?, data: List<TaskTypeData>, selectTaskType: (TaskTypeData) -> Unit) {
|
||||
val selectedTabIndex = data.indexOfFirst { it.id == selectedTaskType?.id }.takeIf { it >= 0 } ?: 0
|
||||
|
||||
ScrollableTabRow(
|
||||
PrimaryScrollableTabRow(
|
||||
selectedTabIndex = selectedTabIndex,
|
||||
edgePadding = 0.dp,
|
||||
containerColor = colorResource(R.color.actionbar_color),
|
||||
indicator = {
|
||||
TabRowDefaults.SecondaryIndicator(
|
||||
Modifier.tabIndicatorOffset(it[selectedTabIndex]),
|
||||
Modifier.tabIndicatorOffset(selectedTabIndex),
|
||||
color = colorResource(R.color.primary)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import androidx.room.TypeConverters
|
||||
import com.nextcloud.client.core.Clock
|
||||
import com.nextcloud.client.core.ClockImpl
|
||||
import com.nextcloud.client.database.dao.ArbitraryDataDao
|
||||
import com.nextcloud.client.database.dao.AssistantDao
|
||||
import com.nextcloud.client.database.dao.FileDao
|
||||
import com.nextcloud.client.database.dao.FileSystemDao
|
||||
import com.nextcloud.client.database.dao.OfflineOperationDao
|
||||
@@ -23,6 +24,7 @@ import com.nextcloud.client.database.dao.RecommendedFileDao
|
||||
import com.nextcloud.client.database.dao.SyncedFolderDao
|
||||
import com.nextcloud.client.database.dao.UploadDao
|
||||
import com.nextcloud.client.database.entity.ArbitraryDataEntity
|
||||
import com.nextcloud.client.database.entity.AssistantEntity
|
||||
import com.nextcloud.client.database.entity.CapabilityEntity
|
||||
import com.nextcloud.client.database.entity.ExternalLinkEntity
|
||||
import com.nextcloud.client.database.entity.FileEntity
|
||||
@@ -39,6 +41,7 @@ import com.nextcloud.client.database.migrations.Migration67to68
|
||||
import com.nextcloud.client.database.migrations.RoomMigration
|
||||
import com.nextcloud.client.database.migrations.addLegacyMigrations
|
||||
import com.nextcloud.client.database.typeConverter.OfflineOperationTypeConverter
|
||||
import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.db.ProviderMeta
|
||||
|
||||
@Database(
|
||||
@@ -53,7 +56,8 @@ import com.owncloud.android.db.ProviderMeta
|
||||
UploadEntity::class,
|
||||
VirtualEntity::class,
|
||||
OfflineOperationEntity::class,
|
||||
RecommendedFileEntity::class
|
||||
RecommendedFileEntity::class,
|
||||
AssistantEntity::class
|
||||
],
|
||||
version = ProviderMeta.DB_VERSION,
|
||||
autoMigrations = [
|
||||
@@ -83,7 +87,10 @@ import com.owncloud.android.db.ProviderMeta
|
||||
AutoMigration(from = 89, to = 90),
|
||||
AutoMigration(from = 90, to = 91),
|
||||
AutoMigration(from = 91, to = 92),
|
||||
AutoMigration(from = 92, to = 93, spec = DatabaseMigrationUtil.ResetCapabilitiesPostMigration::class)
|
||||
AutoMigration(from = 92, to = 93, spec = DatabaseMigrationUtil.ResetCapabilitiesPostMigration::class),
|
||||
AutoMigration(from = 93, to = 94, spec = DatabaseMigrationUtil.ResetCapabilitiesPostMigration::class),
|
||||
AutoMigration(from = 94, to = 95, spec = DatabaseMigrationUtil.ResetCapabilitiesPostMigration::class),
|
||||
AutoMigration(from = 95, to = 96)
|
||||
],
|
||||
exportSchema = true
|
||||
)
|
||||
@@ -98,6 +105,7 @@ abstract class NextcloudDatabase : RoomDatabase() {
|
||||
abstract fun recommendedFileDao(): RecommendedFileDao
|
||||
abstract fun fileSystemDao(): FileSystemDao
|
||||
abstract fun syncedFolderDao(): SyncedFolderDao
|
||||
abstract fun assistantDao(): AssistantDao
|
||||
|
||||
companion object {
|
||||
const val FIRST_ROOM_DB_VERSION = 65
|
||||
@@ -123,5 +131,9 @@ abstract class NextcloudDatabase : RoomDatabase() {
|
||||
}
|
||||
return instance!!
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
@JvmStatic
|
||||
fun instance(): NextcloudDatabase = getInstance(MainApp.getAppContext())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.client.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Delete
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Update
|
||||
import com.nextcloud.client.database.entity.AssistantEntity
|
||||
import com.owncloud.android.db.ProviderMeta
|
||||
|
||||
@Dao
|
||||
interface AssistantDao {
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertAssistantTask(task: AssistantEntity)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertAssistantTasks(tasks: List<AssistantEntity>)
|
||||
|
||||
@Update
|
||||
suspend fun updateAssistantTask(task: AssistantEntity)
|
||||
|
||||
@Delete
|
||||
suspend fun deleteAssistantTask(task: AssistantEntity)
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM ${ProviderMeta.ProviderTableMeta.ASSISTANT_TABLE_NAME}
|
||||
WHERE accountName = :accountName
|
||||
ORDER BY lastUpdated DESC
|
||||
"""
|
||||
)
|
||||
suspend fun getAssistantTasksByAccount(accountName: String): List<AssistantEntity>
|
||||
}
|
||||
@@ -72,9 +72,25 @@ interface UploadDao {
|
||||
suspend fun updateStatus(remotePath: String, accountName: String, status: Int): Int
|
||||
|
||||
@Query(
|
||||
"SELECT * FROM ${ProviderTableMeta.UPLOADS_TABLE_NAME} " +
|
||||
"WHERE ${ProviderTableMeta.UPLOADS_ACCOUNT_NAME} = :accountName " +
|
||||
"AND ${ProviderTableMeta.UPLOADS_STATUS} = :status"
|
||||
"""
|
||||
SELECT * FROM ${ProviderTableMeta.UPLOADS_TABLE_NAME}
|
||||
WHERE ${ProviderTableMeta.UPLOADS_STATUS} = :status
|
||||
AND (:nameCollisionPolicy IS NULL OR ${ProviderTableMeta.UPLOADS_NAME_COLLISION_POLICY} = :nameCollisionPolicy)
|
||||
"""
|
||||
)
|
||||
suspend fun getUploadsByStatus(accountName: String, status: Int): List<UploadEntity>
|
||||
suspend fun getUploadsByStatus(status: Int, nameCollisionPolicy: Int? = null): List<UploadEntity>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM ${ProviderTableMeta.UPLOADS_TABLE_NAME}
|
||||
WHERE ${ProviderTableMeta.UPLOADS_ACCOUNT_NAME} = :accountName
|
||||
AND ${ProviderTableMeta.UPLOADS_STATUS} = :status
|
||||
AND (:nameCollisionPolicy IS NULL OR ${ProviderTableMeta.UPLOADS_NAME_COLLISION_POLICY} = :nameCollisionPolicy)
|
||||
"""
|
||||
)
|
||||
suspend fun getUploadsByAccountNameAndStatus(
|
||||
accountName: String,
|
||||
status: Int,
|
||||
nameCollisionPolicy: Int? = null
|
||||
): List<UploadEntity>
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.client.database.entity
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
import com.owncloud.android.db.ProviderMeta
|
||||
|
||||
@Entity(tableName = ProviderMeta.ProviderTableMeta.ASSISTANT_TABLE_NAME)
|
||||
data class AssistantEntity(
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
val id: Long = 0L,
|
||||
val accountName: String?,
|
||||
val type: String?,
|
||||
val status: String?,
|
||||
val userId: String?,
|
||||
val appId: String?,
|
||||
val input: String? = null,
|
||||
val output: String? = null,
|
||||
val completionExpectedAt: Int? = null,
|
||||
var progress: Int? = null,
|
||||
val lastUpdated: Int? = null,
|
||||
val scheduledAt: Int? = null,
|
||||
val endedAt: Int? = null
|
||||
)
|
||||
@@ -142,5 +142,9 @@ data class CapabilityEntity(
|
||||
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_DEFAULT_PERMISSIONS)
|
||||
val defaultPermissions: Int?,
|
||||
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_USER_STATUS_SUPPORTS_BUSY)
|
||||
val userStatusSupportsBusy: Int?
|
||||
val userStatusSupportsBusy: Int?,
|
||||
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_WINDOWS_COMPATIBLE_FILENAMES)
|
||||
val isWCFEnabled: Int?,
|
||||
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_HAS_VALID_SUBSCRIPTION)
|
||||
val hasValidSubscription: Int?
|
||||
)
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
package com.nextcloud.client.etm
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
@@ -20,6 +21,7 @@ class EtmMenuAdapter(context: Context, val onItemClicked: (Int) -> Unit) :
|
||||
|
||||
private val layoutInflater = LayoutInflater.from(context)
|
||||
var pages: List<EtmMenuEntry> = listOf()
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
set(value) {
|
||||
field = value
|
||||
notifyDataSetChanged()
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
package com.nextcloud.client.etm.pages
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import android.view.Menu
|
||||
@@ -63,6 +64,7 @@ class EtmFileTransferFragment : EtmBaseFragment() {
|
||||
|
||||
private var transfers = listOf<Transfer>()
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
fun setStatus(status: TransferManager.Status) {
|
||||
transfers = listOf(status.pending, status.running, status.completed).flatten().reversed()
|
||||
notifyDataSetChanged()
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.client.jobs.autoUpload
|
||||
|
||||
import com.nextcloud.utils.extensions.shouldSkipFile
|
||||
import com.nextcloud.utils.extensions.toLocalPath
|
||||
import com.owncloud.android.datamodel.FilesystemDataProvider
|
||||
import com.owncloud.android.datamodel.SyncedFolder
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import java.io.IOException
|
||||
import java.nio.file.AccessDeniedException
|
||||
import java.nio.file.FileVisitOption
|
||||
import java.nio.file.FileVisitResult
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import java.nio.file.Paths
|
||||
import java.nio.file.SimpleFileVisitor
|
||||
import java.nio.file.attribute.BasicFileAttributes
|
||||
|
||||
@Suppress("TooGenericExceptionCaught", "MagicNumber", "ReturnCount")
|
||||
class AutoUploadHelper {
|
||||
companion object {
|
||||
private const val TAG = "AutoUploadHelper"
|
||||
private const val MAX_DEPTH = 100
|
||||
}
|
||||
|
||||
fun insertCustomFolderIntoDB(folder: SyncedFolder, filesystemDataProvider: FilesystemDataProvider?): Int {
|
||||
val path = Paths.get(folder.localPath)
|
||||
|
||||
if (!Files.exists(path)) {
|
||||
Log_OC.w(TAG, "Folder does not exist: ${folder.localPath}")
|
||||
return 0
|
||||
}
|
||||
|
||||
if (!Files.isReadable(path)) {
|
||||
Log_OC.w(TAG, "Folder is not readable: ${folder.localPath}")
|
||||
return 0
|
||||
}
|
||||
|
||||
val excludeHidden = folder.isExcludeHidden
|
||||
|
||||
var fileCount = 0
|
||||
var skipCount = 0
|
||||
var errorCount = 0
|
||||
|
||||
try {
|
||||
Files.walkFileTree(
|
||||
path,
|
||||
setOf(FileVisitOption.FOLLOW_LINKS),
|
||||
MAX_DEPTH,
|
||||
object : SimpleFileVisitor<Path>() {
|
||||
|
||||
override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes?): FileVisitResult {
|
||||
if (excludeHidden && dir != path && dir.toFile().isHidden) {
|
||||
Log_OC.d(TAG, "Skipping hidden directory: ${dir.fileName}")
|
||||
skipCount++
|
||||
return FileVisitResult.SKIP_SUBTREE
|
||||
}
|
||||
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
|
||||
override fun visitFile(file: Path, attrs: BasicFileAttributes?): FileVisitResult {
|
||||
try {
|
||||
val javaFile = file.toFile()
|
||||
val lastModified = attrs?.lastModifiedTime()?.toMillis() ?: javaFile.lastModified()
|
||||
val creationTime = attrs?.creationTime()?.toMillis()
|
||||
|
||||
if (folder.shouldSkipFile(javaFile, lastModified, creationTime)) {
|
||||
skipCount++
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
|
||||
val localPath = file.toLocalPath()
|
||||
|
||||
filesystemDataProvider?.storeOrUpdateFileValue(
|
||||
localPath,
|
||||
lastModified,
|
||||
javaFile.isDirectory,
|
||||
folder
|
||||
)
|
||||
|
||||
fileCount++
|
||||
|
||||
if (fileCount % 100 == 0) {
|
||||
Log_OC.d(TAG, "Processed $fileCount files so far...")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log_OC.e(TAG, "Error processing file: $file", e)
|
||||
errorCount++
|
||||
}
|
||||
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
|
||||
override fun visitFileFailed(file: Path, exc: IOException?): FileVisitResult {
|
||||
when (exc) {
|
||||
is AccessDeniedException -> {
|
||||
Log_OC.w(TAG, "Access denied: $file")
|
||||
}
|
||||
else -> {
|
||||
Log_OC.e(TAG, "Failed to visit file: $file", exc)
|
||||
}
|
||||
}
|
||||
errorCount++
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
|
||||
override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
|
||||
if (exc != null) {
|
||||
Log_OC.e(TAG, "Error after visiting directory: $dir", exc)
|
||||
errorCount++
|
||||
}
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
Log_OC.d(
|
||||
TAG,
|
||||
"Scan complete for ${folder.localPath}: " +
|
||||
"$fileCount files processed, $skipCount skipped, $errorCount errors"
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log_OC.e(TAG, "Error walking file tree: ${folder.localPath}", e)
|
||||
}
|
||||
|
||||
return fileCount
|
||||
}
|
||||
}
|
||||
@@ -76,6 +76,7 @@ class AutoUploadWorker(
|
||||
private const val NOTIFICATION_ID = 266
|
||||
}
|
||||
|
||||
private val helper = AutoUploadHelper()
|
||||
private lateinit var syncedFolder: SyncedFolder
|
||||
private val notificationManager by lazy {
|
||||
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
@@ -209,7 +210,7 @@ class AutoUploadWorker(
|
||||
private suspend fun collectFileChangesFromContentObserverWork(contentUris: Array<String>?) = try {
|
||||
withContext(Dispatchers.IO) {
|
||||
if (contentUris.isNullOrEmpty()) {
|
||||
FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder)
|
||||
FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder, helper)
|
||||
} else {
|
||||
val isContentUrisStored = FilesSyncHelper.insertChangedEntries(syncedFolder, contentUris)
|
||||
if (!isContentUrisStored) {
|
||||
@@ -218,7 +219,7 @@ class AutoUploadWorker(
|
||||
"changed content uris not stored, fallback to insert all db entries to not lose files"
|
||||
)
|
||||
|
||||
FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder)
|
||||
FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder, helper)
|
||||
}
|
||||
}
|
||||
syncedFolder.lastScanTimestampMs = System.currentTimeMillis()
|
||||
@@ -351,36 +352,34 @@ class AutoUploadWorker(
|
||||
val (needsCharging, needsWifi, uploadAction) = getUploadSettings(syncedFolder)
|
||||
Log_OC.d(TAG, "creating oc upload for ${user.accountName}")
|
||||
|
||||
// Get or create upload entity
|
||||
var uploadEntity = uploadsStorageManager.uploadDao.getUploadByAccountAndPaths(
|
||||
// Get existing upload or create new one
|
||||
val uploadEntity = uploadsStorageManager.uploadDao.getUploadByAccountAndPaths(
|
||||
localPath = localPath,
|
||||
remotePath = remotePath,
|
||||
accountName = user.accountName
|
||||
)
|
||||
|
||||
val upload: OCUpload
|
||||
if (uploadEntity != null) {
|
||||
// Existing upload - convert and update status
|
||||
val upload = (
|
||||
uploadEntity?.toOCUpload(null) ?: OCUpload(
|
||||
localPath,
|
||||
remotePath,
|
||||
user.accountName
|
||||
)
|
||||
).apply {
|
||||
uploadStatus = UploadsStorageManager.UploadStatus.UPLOAD_IN_PROGRESS
|
||||
nameCollisionPolicy = syncedFolder.nameCollisionPolicy
|
||||
isUseWifiOnly = needsWifi
|
||||
isWhileChargingOnly = needsCharging
|
||||
localAction = uploadAction
|
||||
|
||||
upload = uploadEntity.toOCUpload(null)
|
||||
upload.uploadStatus = UploadsStorageManager.UploadStatus.UPLOAD_IN_PROGRESS
|
||||
uploadEntity = upload.toUploadEntity()
|
||||
} else {
|
||||
// New upload - create with all settings
|
||||
|
||||
upload = OCUpload(localPath, remotePath, user.accountName).apply {
|
||||
nameCollisionPolicy = syncedFolder.nameCollisionPolicy
|
||||
isUseWifiOnly = needsWifi
|
||||
isWhileChargingOnly = needsCharging
|
||||
uploadStatus = UploadsStorageManager.UploadStatus.UPLOAD_IN_PROGRESS
|
||||
// Only set these for new uploads
|
||||
if (uploadEntity == null) {
|
||||
createdBy = UploadFileOperation.CREATED_AS_INSTANT_PICTURE
|
||||
isCreateRemoteFolder = true
|
||||
localAction = uploadAction
|
||||
}
|
||||
uploadEntity = upload.toUploadEntity()
|
||||
}
|
||||
|
||||
return uploadEntity to upload
|
||||
return upload.toUploadEntity() to upload
|
||||
}
|
||||
|
||||
private fun createUploadFileOperation(upload: OCUpload, user: User): UploadFileOperation = UploadFileOperation(
|
||||
|
||||
@@ -88,18 +88,42 @@ class FileUploadHelper {
|
||||
fun buildRemoteName(accountName: String, remotePath: String): String = accountName + remotePath
|
||||
}
|
||||
|
||||
/**
|
||||
* Retries all failed uploads across all user accounts.
|
||||
*
|
||||
* This function retrieves all uploads with the status [UploadStatus.UPLOAD_FAILED], including both
|
||||
* manual uploads and auto uploads. It runs in a background thread (Dispatcher.IO) and ensures
|
||||
* that only one retry operation runs at a time by using a semaphore to prevent concurrent execution.
|
||||
*
|
||||
* Once the failed uploads are retrieved, it calls [retryUploads], which triggers the corresponding
|
||||
* upload workers for each failed upload.
|
||||
*
|
||||
* The function returns `true` if there were any failed uploads to retry and the retry process was
|
||||
* started, or `false` if no uploads were retried.
|
||||
*
|
||||
* @param uploadsStorageManager Provides access to upload data and persistence.
|
||||
* @param connectivityService Checks the current network connectivity state.
|
||||
* @param accountManager Handles user account authentication and selection.
|
||||
* @param powerManagementService Ensures uploads respect power constraints.
|
||||
* @return `true` if any failed uploads were found and retried; `false` otherwise.
|
||||
*/
|
||||
fun retryFailedUploads(
|
||||
uploadsStorageManager: UploadsStorageManager,
|
||||
connectivityService: ConnectivityService,
|
||||
accountManager: UserAccountManager,
|
||||
powerManagementService: PowerManagementService
|
||||
) {
|
||||
if (retryFailedUploadsSemaphore.tryAcquire()) {
|
||||
try {
|
||||
val failedUploads = uploadsStorageManager.failedUploads
|
||||
if (failedUploads == null || failedUploads.isEmpty()) {
|
||||
Log_OC.d(TAG, "Failed uploads are empty or null")
|
||||
return
|
||||
): Boolean {
|
||||
if (!retryFailedUploadsSemaphore.tryAcquire()) {
|
||||
Log_OC.d(TAG, "skipping retryFailedUploads, already running")
|
||||
return true
|
||||
}
|
||||
|
||||
var isUploadStarted = false
|
||||
|
||||
try {
|
||||
getUploadsByStatus(null, UploadStatus.UPLOAD_FAILED) {
|
||||
if (it.isNotEmpty()) {
|
||||
isUploadStarted = true
|
||||
}
|
||||
|
||||
retryUploads(
|
||||
@@ -107,14 +131,14 @@ class FileUploadHelper {
|
||||
connectivityService,
|
||||
accountManager,
|
||||
powerManagementService,
|
||||
failedUploads
|
||||
uploads = it
|
||||
)
|
||||
} finally {
|
||||
retryFailedUploadsSemaphore.release()
|
||||
}
|
||||
} else {
|
||||
Log_OC.d(TAG, "Skip retryFailedUploads since it is already running")
|
||||
} finally {
|
||||
retryFailedUploadsSemaphore.release()
|
||||
}
|
||||
|
||||
return isUploadStarted
|
||||
}
|
||||
|
||||
fun retryCancelledUploads(
|
||||
@@ -123,18 +147,18 @@ class FileUploadHelper {
|
||||
accountManager: UserAccountManager,
|
||||
powerManagementService: PowerManagementService
|
||||
): Boolean {
|
||||
val cancelledUploads = uploadsStorageManager.cancelledUploadsForCurrentAccount
|
||||
if (cancelledUploads == null || cancelledUploads.isEmpty()) {
|
||||
return false
|
||||
var result = false
|
||||
getUploadsByStatus(accountManager.user.accountName, UploadStatus.UPLOAD_CANCELLED) {
|
||||
result = retryUploads(
|
||||
uploadsStorageManager,
|
||||
connectivityService,
|
||||
accountManager,
|
||||
powerManagementService,
|
||||
it
|
||||
)
|
||||
}
|
||||
|
||||
return retryUploads(
|
||||
uploadsStorageManager,
|
||||
connectivityService,
|
||||
accountManager,
|
||||
powerManagementService,
|
||||
cancelledUploads
|
||||
)
|
||||
return result
|
||||
}
|
||||
|
||||
@Suppress("ComplexCondition")
|
||||
@@ -143,35 +167,32 @@ class FileUploadHelper {
|
||||
connectivityService: ConnectivityService,
|
||||
accountManager: UserAccountManager,
|
||||
powerManagementService: PowerManagementService,
|
||||
failedUploads: Array<OCUpload>
|
||||
uploads: Array<OCUpload>
|
||||
): Boolean {
|
||||
var showNotExistMessage = false
|
||||
val isOnline = checkConnectivity(connectivityService)
|
||||
val connectivity = connectivityService.connectivity
|
||||
val batteryStatus = powerManagementService.battery
|
||||
val accountNames = accountManager.accounts.filter { account ->
|
||||
accountManager.getUser(account.name).isPresent
|
||||
}.map { account ->
|
||||
account.name
|
||||
}.toHashSet()
|
||||
|
||||
for (failedUpload in failedUploads) {
|
||||
if (!accountNames.contains(failedUpload.accountName)) {
|
||||
uploadsStorageManager.removeUpload(failedUpload)
|
||||
continue
|
||||
}
|
||||
val uploadsToRetry = mutableListOf<Long>()
|
||||
|
||||
val uploadResult =
|
||||
checkUploadConditions(failedUpload, connectivity, batteryStatus, powerManagementService, isOnline)
|
||||
for (upload in uploads) {
|
||||
val uploadResult = checkUploadConditions(
|
||||
upload,
|
||||
connectivity,
|
||||
batteryStatus,
|
||||
powerManagementService,
|
||||
isOnline
|
||||
)
|
||||
|
||||
if (uploadResult != UploadResult.UPLOADED) {
|
||||
if (failedUpload.lastResult != uploadResult) {
|
||||
if (upload.lastResult != uploadResult) {
|
||||
// Setting Upload status else cancelled uploads will behave wrong, when retrying
|
||||
// Needs to happen first since lastResult wil be overwritten by setter
|
||||
failedUpload.uploadStatus = UploadStatus.UPLOAD_FAILED
|
||||
upload.uploadStatus = UploadStatus.UPLOAD_FAILED
|
||||
|
||||
failedUpload.lastResult = uploadResult
|
||||
uploadsStorageManager.updateUpload(failedUpload)
|
||||
upload.lastResult = uploadResult
|
||||
uploadsStorageManager.updateUpload(upload)
|
||||
}
|
||||
if (uploadResult == UploadResult.FILE_NOT_FOUND) {
|
||||
showNotExistMessage = true
|
||||
@@ -179,15 +200,18 @@ class FileUploadHelper {
|
||||
continue
|
||||
}
|
||||
|
||||
failedUpload.uploadStatus = UploadStatus.UPLOAD_IN_PROGRESS
|
||||
uploadsStorageManager.updateUpload(failedUpload)
|
||||
// Only uploads that passed checks get marked in progress and are collected for scheduling
|
||||
upload.uploadStatus = UploadStatus.UPLOAD_IN_PROGRESS
|
||||
uploadsStorageManager.updateUpload(upload)
|
||||
uploadsToRetry.add(upload.uploadId)
|
||||
}
|
||||
|
||||
accountNames.forEach { accountName ->
|
||||
val user = accountManager.getUser(accountName)
|
||||
if (user.isPresent) {
|
||||
backgroundJobManager.startFilesUploadJob(user.get(), failedUploads.getUploadIds(), false)
|
||||
}
|
||||
if (uploadsToRetry.isNotEmpty()) {
|
||||
backgroundJobManager.startFilesUploadJob(
|
||||
accountManager.user,
|
||||
uploadsToRetry.toLongArray(),
|
||||
false
|
||||
)
|
||||
}
|
||||
|
||||
return showNotExistMessage
|
||||
@@ -235,11 +259,35 @@ class FileUploadHelper {
|
||||
}
|
||||
}
|
||||
|
||||
fun getUploadsByStatus(accountName: String, status: UploadStatus, onCompleted: (Array<OCUpload>) -> Unit) {
|
||||
/**
|
||||
* Retrieves uploads filtered by their status, optionally for a specific account.
|
||||
*
|
||||
* This function queries the uploads database asynchronously to obtain a list of uploads
|
||||
* that match the specified [status]. If an [accountName] is provided, only uploads
|
||||
* belonging to that account are retrieved. If [accountName] is `null`, uploads with the
|
||||
* given [status] from **all user accounts** are returned.
|
||||
*
|
||||
* Once the uploads are fetched, the [onCompleted] callback is invoked with the resulting array.
|
||||
*
|
||||
* @param accountName The name of the account to filter uploads by.
|
||||
* If `null`, uploads matching the given [status] from all accounts are returned.
|
||||
* @param status The [UploadStatus] to filter uploads by (e.g., `UPLOAD_FAILED`).
|
||||
* @param nameCollisionPolicy The [NameCollisionPolicy] to filter uploads by (e.g., `SKIP`).
|
||||
* @param onCompleted A callback invoked with the resulting array of [OCUpload] objects.
|
||||
*/
|
||||
fun getUploadsByStatus(
|
||||
accountName: String?,
|
||||
status: UploadStatus,
|
||||
nameCollisionPolicy: NameCollisionPolicy? = null,
|
||||
onCompleted: (Array<OCUpload>) -> Unit
|
||||
) {
|
||||
ioScope.launch {
|
||||
val result =
|
||||
uploadsStorageManager.uploadDao.getUploadsByStatus(accountName, status.value)
|
||||
.map { it.toOCUpload(null) }.toTypedArray()
|
||||
val dao = uploadsStorageManager.uploadDao
|
||||
val result = if (accountName != null) {
|
||||
dao.getUploadsByAccountNameAndStatus(accountName, status.value, nameCollisionPolicy?.serialize())
|
||||
} else {
|
||||
dao.getUploadsByStatus(status.value, nameCollisionPolicy?.serialize())
|
||||
}.map { it.toOCUpload(null) }.toTypedArray()
|
||||
onCompleted(result)
|
||||
}
|
||||
}
|
||||
@@ -439,8 +487,8 @@ class FileUploadHelper {
|
||||
}
|
||||
|
||||
fun showFileUploadLimitMessage(activity: Activity) {
|
||||
val message = activity.getString(
|
||||
R.string.file_upload_limit_message,
|
||||
val message = activity.resources.getQuantityString(
|
||||
R.plurals.file_upload_limit_message,
|
||||
MAX_FILE_COUNT
|
||||
)
|
||||
DisplayUtils.showSnackMessage(activity, message)
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
package com.nextcloud.client.logger.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import androidx.lifecycle.LiveData
|
||||
import androidx.lifecycle.MutableLiveData
|
||||
@@ -17,6 +18,7 @@ import com.nextcloud.client.logger.LogsRepository
|
||||
import com.owncloud.android.R
|
||||
import javax.inject.Inject
|
||||
|
||||
@SuppressLint("StaticFieldLeak")
|
||||
class LogsViewModel @Inject constructor(
|
||||
private val context: Context,
|
||||
clock: Clock,
|
||||
|
||||
@@ -335,6 +335,7 @@ class SetStatusMessageBottomSheet(val user: User, val currentStatus: Status?) :
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
@VisibleForTesting
|
||||
fun setPredefinedStatus(predefinedStatus: ArrayList<PredefinedStatus>) {
|
||||
adapter.list = predefinedStatus
|
||||
|
||||
@@ -18,7 +18,9 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.nextcloud.client.assistant.AssistantScreen
|
||||
import com.nextcloud.client.assistant.AssistantViewModel
|
||||
import com.nextcloud.client.assistant.repository.AssistantRepository
|
||||
import com.nextcloud.client.assistant.repository.local.AssistantLocalRepositoryImpl
|
||||
import com.nextcloud.client.assistant.repository.remote.AssistantRemoteRepositoryImpl
|
||||
import com.nextcloud.client.database.NextcloudDatabase
|
||||
import com.nextcloud.common.NextcloudClient
|
||||
import com.nextcloud.utils.extensions.getSerializableArgument
|
||||
import com.owncloud.android.R
|
||||
@@ -79,10 +81,14 @@ class ComposeActivity : DrawerActivity() {
|
||||
isChecked = true
|
||||
}
|
||||
|
||||
val dao = NextcloudDatabase.instance().assistantDao()
|
||||
|
||||
nextcloudClient?.let { client ->
|
||||
AssistantScreen(
|
||||
viewModel = AssistantViewModel(
|
||||
repository = AssistantRepository(client, capabilities)
|
||||
accountName = userAccountManager.user.accountName,
|
||||
remoteRepository = AssistantRemoteRepositoryImpl(client, capabilities),
|
||||
localRepository = AssistantLocalRepositoryImpl(dao)
|
||||
),
|
||||
activity = this,
|
||||
capability = capabilities
|
||||
|
||||
@@ -8,10 +8,15 @@
|
||||
package com.nextcloud.utils
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Matrix
|
||||
import androidx.core.graphics.scale
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import com.nextcloud.utils.extensions.toFile
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.utils.BitmapUtils.calculateSampleFactor
|
||||
|
||||
private const val TAG = "BitmapExtension"
|
||||
|
||||
@Suppress("MagicNumber")
|
||||
fun Bitmap.allocationKilobyte(): Int = allocationByteCount.div(1024)
|
||||
@@ -117,3 +122,39 @@ fun Bitmap?.rotateBitmapViaExif(orientation: Int): Bitmap? {
|
||||
this
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes a bitmap from a file path while minimizing memory usage.
|
||||
*
|
||||
* This function first checks if the file exists (via [toFile]), then performs following steps:
|
||||
*
|
||||
* 1. Reads image dimensions using [BitmapFactory.Options.inJustDecodeBounds] without allocating memory.
|
||||
* 2. Calculates a sampling factor with [calculateSampleFactor] to scale down large images efficiently.
|
||||
* 3. Decodes the actual bitmap using the computed sample size.
|
||||
*
|
||||
* @param srcPath Absolute path to the image file.
|
||||
* @param reqWidth Desired width in pixels of the output bitmap.
|
||||
* @param reqHeight Desired height in pixels of the output bitmap.
|
||||
* @return The decoded [Bitmap], or `null` if the file does not exist or decoding fails.
|
||||
*/
|
||||
@Suppress("TooGenericExceptionCaught")
|
||||
fun decodeSampledBitmapFromFile(srcPath: String?, reqWidth: Int, reqHeight: Int): Bitmap? {
|
||||
// check existence of file
|
||||
srcPath?.toFile() ?: return null
|
||||
|
||||
// Read image dimensions without allocating memory just to get pixels
|
||||
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(srcPath, options)
|
||||
|
||||
// Calculate sampling factor
|
||||
options.inSampleSize = calculateSampleFactor(options, reqWidth, reqHeight)
|
||||
options.inJustDecodeBounds = false
|
||||
|
||||
// Decode actual bitmap
|
||||
return try {
|
||||
BitmapFactory.decodeFile(srcPath, options)
|
||||
} catch (e: Exception) {
|
||||
Log_OC.e(TAG, "exception during decoding path: $e")
|
||||
null
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ package com.nextcloud.utils
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.Service
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import androidx.core.app.ServiceCompat
|
||||
@@ -32,7 +33,7 @@ object ForegroundServiceHelper {
|
||||
service,
|
||||
id,
|
||||
notification,
|
||||
foregroundServiceType.getId()
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.d(TAG, "Exception caught at ForegroundServiceHelper.startService: $e")
|
||||
|
||||
@@ -8,12 +8,12 @@
|
||||
package com.nextcloud.utils.autoRename
|
||||
|
||||
import com.nextcloud.utils.extensions.StringConstants
|
||||
import com.nextcloud.utils.extensions.checkWCFRestrictions
|
||||
import com.nextcloud.utils.extensions.forbiddenFilenameCharacters
|
||||
import com.nextcloud.utils.extensions.forbiddenFilenameExtensions
|
||||
import com.nextcloud.utils.extensions.shouldRemoveNonPrintableUnicodeCharactersAndConvertToUTF8
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.lib.resources.status.NextcloudVersion
|
||||
import com.owncloud.android.lib.resources.status.OCCapability
|
||||
import org.apache.commons.io.FilenameUtils
|
||||
import java.util.regex.Pattern
|
||||
@@ -25,12 +25,12 @@ object AutoRename {
|
||||
@Suppress("NestedBlockDepth")
|
||||
@JvmOverloads
|
||||
fun rename(filename: String, capability: OCCapability, isFolderPath: Boolean? = null): String {
|
||||
Log_OC.d(TAG, "Before - $filename")
|
||||
|
||||
if (!capability.version.isNewerOrEqual(NextcloudVersion.nextcloud_30)) {
|
||||
if (!capability.checkWCFRestrictions()) {
|
||||
return filename
|
||||
}
|
||||
|
||||
Log_OC.d(TAG, "Before - $filename")
|
||||
|
||||
val isFolder = isFolderPath ?: filename.endsWith(OCFile.PATH_SEPARATOR)
|
||||
val pathSegments = filename.split(OCFile.PATH_SEPARATOR).toMutableList()
|
||||
|
||||
|
||||
@@ -11,6 +11,9 @@ import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.utils.DisplayUtils
|
||||
import java.io.File
|
||||
import java.nio.file.Path
|
||||
|
||||
private const val TAG = "FileExtensions"
|
||||
|
||||
fun OCFile?.logFileSize(tag: String) {
|
||||
val size = DisplayUtils.bytesToHumanReadable(this?.fileLength ?: -1)
|
||||
@@ -23,3 +26,27 @@ fun File?.logFileSize(tag: String) {
|
||||
val rawByte = this?.length() ?: -1
|
||||
Log_OC.d(tag, "onSaveInstanceState: $size, raw byte $rawByte")
|
||||
}
|
||||
|
||||
fun Path.toLocalPath(): String = toAbsolutePath().toString()
|
||||
|
||||
/**
|
||||
* Converts a non-null and non-empty [String] path into a [File] object, if it exists.
|
||||
*
|
||||
* @receiver String path to a file.
|
||||
* @return [File] instance if the file exists, or `null` if the path is null, empty, or non-existent.
|
||||
*/
|
||||
@Suppress("ReturnCount")
|
||||
fun String.toFile(): File? {
|
||||
if (isNullOrEmpty()) {
|
||||
Log_OC.e(TAG, "given path is null or empty")
|
||||
return null
|
||||
}
|
||||
|
||||
val file = File(this)
|
||||
if (!file.exists()) {
|
||||
Log_OC.e(TAG, "File does not exist: $this")
|
||||
return null
|
||||
}
|
||||
|
||||
return file
|
||||
}
|
||||
@@ -8,11 +8,31 @@
|
||||
package com.nextcloud.utils.extensions
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.owncloud.android.lib.resources.status.NextcloudVersion
|
||||
import com.owncloud.android.lib.resources.status.OCCapability
|
||||
import org.json.JSONException
|
||||
|
||||
private val gson = Gson()
|
||||
|
||||
/**
|
||||
* Determines whether **Windows-compatible file (WCF)** restrictions should be applied
|
||||
* for the current server version and configuration.
|
||||
*
|
||||
* Behavior:
|
||||
* - For **Nextcloud 32 and newer**, WCF enforcement depends on the [`isWCFEnabled`] flag
|
||||
* provided by the server capabilities.
|
||||
* - For **Nextcloud 30 and 31**, WCF restrictions are always applied (feature considered enabled).
|
||||
* - For **versions older than 30**, WCF is not supported, and no restrictions are applied.
|
||||
*
|
||||
* @return `true` if WCF restrictions should be enforced based on the server version and configuration;
|
||||
* `false` otherwise.
|
||||
*/
|
||||
fun OCCapability.checkWCFRestrictions(): Boolean = if (version.isNewerOrEqual(NextcloudVersion.nextcloud_32)) {
|
||||
isWCFEnabled.isTrue
|
||||
} else {
|
||||
version.isNewerOrEqual(NextcloudVersion.nextcloud_30)
|
||||
}
|
||||
|
||||
fun OCCapability.forbiddenFilenames(): List<String> = jsonToList(forbiddenFilenamesJson)
|
||||
|
||||
fun OCCapability.forbiddenFilenameCharacters(): List<String> = jsonToList(forbiddenFilenameCharactersJson)
|
||||
@@ -33,7 +53,7 @@ private fun jsonToList(json: String?): List<String> {
|
||||
|
||||
return try {
|
||||
return gson.fromJson(json, Array<String>::class.java).toList()
|
||||
} catch (e: JSONException) {
|
||||
} catch (_: JSONException) {
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
@@ -13,8 +13,44 @@ import com.nextcloud.client.network.ConnectivityService
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.SyncedFolder
|
||||
import com.owncloud.android.datamodel.SyncedFolderDisplayItem
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import java.io.File
|
||||
|
||||
private const val TAG = "SyncedFolderExtensions"
|
||||
|
||||
/**
|
||||
* Determines whether a file should be skipped during auto-upload based on folder settings.
|
||||
*/
|
||||
@Suppress("ReturnCount")
|
||||
fun SyncedFolder.shouldSkipFile(file: File, lastModified: Long, creationTime: Long?): Boolean {
|
||||
if (isExcludeHidden && file.isHidden) {
|
||||
Log_OC.d(TAG, "Skipping hidden: ${file.absolutePath}")
|
||||
return true
|
||||
}
|
||||
|
||||
// If "upload existing files" is DISABLED, only upload files created after enabled time
|
||||
if (!isExisting) {
|
||||
if (creationTime != null) {
|
||||
if (creationTime < enabledTimestampMs) {
|
||||
Log_OC.d(TAG, "Skipping pre-existing file (creation < enabled): ${file.absolutePath}")
|
||||
return true
|
||||
}
|
||||
} else {
|
||||
Log_OC.w(TAG, "file sent for upload - cannot determine creation time: ${file.absolutePath}")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Skip files that haven't changed since last scan (already processed)
|
||||
// BUT only if this is not the first scan
|
||||
if (lastScanTimestampMs != -1L && lastModified < lastScanTimestampMs) {
|
||||
Log_OC.d(TAG, "Skipping unchanged file (last modified < last scan): ${file.absolutePath}")
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
fun List<SyncedFolderDisplayItem>.filterEnabledOrWithoutEnabledParent(): List<SyncedFolderDisplayItem> = filter {
|
||||
it.isEnabled || !hasEnabledParent(it.localPath)
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ package com.nextcloud.utils.fileNameValidator
|
||||
import android.content.Context
|
||||
import android.text.TextUtils
|
||||
import com.nextcloud.utils.extensions.StringConstants
|
||||
import com.nextcloud.utils.extensions.checkWCFRestrictions
|
||||
import com.nextcloud.utils.extensions.forbiddenFilenameBaseNames
|
||||
import com.nextcloud.utils.extensions.forbiddenFilenameCharacters
|
||||
import com.nextcloud.utils.extensions.forbiddenFilenameExtensions
|
||||
@@ -17,7 +18,6 @@ import com.nextcloud.utils.extensions.forbiddenFilenames
|
||||
import com.nextcloud.utils.extensions.removeFileExtension
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.lib.resources.status.NextcloudVersion
|
||||
import com.owncloud.android.lib.resources.status.OCCapability
|
||||
|
||||
object FileNameValidator {
|
||||
@@ -49,10 +49,11 @@ object FileNameValidator {
|
||||
}
|
||||
}
|
||||
|
||||
if (!capability.version.isNewerOrEqual(NextcloudVersion.nextcloud_30)) {
|
||||
if (!capability.checkWCFRestrictions()) {
|
||||
return null
|
||||
}
|
||||
|
||||
// region WCF related checks
|
||||
checkInvalidCharacters(filename, capability, context)?.let { return it }
|
||||
|
||||
val filenameVariants = setOf(filename.lowercase(), filename.removeFileExtension().lowercase())
|
||||
@@ -91,6 +92,7 @@ object FileNameValidator {
|
||||
}
|
||||
}
|
||||
}
|
||||
// endregion
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -48,7 +48,6 @@ import android.widget.Toast;
|
||||
|
||||
import com.blikoon.qrcodescanner.QrCodeActivity;
|
||||
import com.google.android.material.button.MaterialButton;
|
||||
import com.google.android.material.snackbar.Snackbar;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
@@ -105,7 +104,6 @@ import com.owncloud.android.utils.DisplayUtils;
|
||||
import com.owncloud.android.utils.ErrorMessageAdapter;
|
||||
import com.owncloud.android.utils.PermissionUtil;
|
||||
import com.owncloud.android.utils.WebViewUtil;
|
||||
import com.owncloud.android.utils.theme.CapabilityUtils;
|
||||
import com.owncloud.android.utils.theme.ViewThemeUtils;
|
||||
|
||||
import java.io.InputStream;
|
||||
@@ -1104,13 +1102,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
|
||||
// 4. we got the authentication method required by the server
|
||||
mServerInfo = (GetServerInfoOperation.ServerInfo) (result.getData().get(0));
|
||||
|
||||
// show outdated warning
|
||||
if (CapabilityUtils.checkOutdatedWarning(getResources(),
|
||||
mServerInfo.mVersion,
|
||||
mServerInfo.hasExtendedSupport)) {
|
||||
DisplayUtils.showServerOutdatedSnackbar(this, Snackbar.LENGTH_INDEFINITE);
|
||||
}
|
||||
|
||||
if (webViewUser != null && !webViewUser.isEmpty() &&
|
||||
webViewPassword != null && !webViewPassword.isEmpty()) {
|
||||
checkBasicAuthorization(webViewUser, webViewPassword);
|
||||
|
||||
@@ -2411,6 +2411,7 @@ public class FileDataStorageManager {
|
||||
contentValues.put(ProviderTableMeta.CAPABILITIES_FORBIDDEN_FILENAMES, capability.getForbiddenFilenamesJson());
|
||||
contentValues.put(ProviderTableMeta.CAPABILITIES_FORBIDDEN_FORBIDDEN_FILENAME_EXTENSIONS, capability.getForbiddenFilenameExtensionJson());
|
||||
contentValues.put(ProviderTableMeta.CAPABILITIES_FORBIDDEN_FORBIDDEN_FILENAME_BASE_NAMES, capability.getForbiddenFilenameBaseNamesJson());
|
||||
contentValues.put(ProviderTableMeta.CAPABILITIES_WINDOWS_COMPATIBLE_FILENAMES, capability.isWCFEnabled().getValue());
|
||||
contentValues.put(ProviderTableMeta.CAPABILITIES_FILES_DOWNLOAD_LIMIT, capability.getFilesDownloadLimit().getValue());
|
||||
contentValues.put(ProviderTableMeta.CAPABILITIES_FILES_DOWNLOAD_LIMIT_DEFAULT, capability.getFilesDownloadLimitDefault());
|
||||
|
||||
@@ -2419,6 +2420,8 @@ public class FileDataStorageManager {
|
||||
contentValues.put(ProviderTableMeta.CAPABILITIES_NOTES_FOLDER_PATH, capability.getNotesFolderPath());
|
||||
|
||||
contentValues.put(ProviderTableMeta.CAPABILITIES_DEFAULT_PERMISSIONS, capability.getDefaultPermissions());
|
||||
|
||||
contentValues.put(ProviderTableMeta.CAPABILITIES_HAS_VALID_SUBSCRIPTION, capability.getHasValidSubscription().getValue());
|
||||
|
||||
return contentValues;
|
||||
}
|
||||
@@ -2595,6 +2598,7 @@ public class FileDataStorageManager {
|
||||
capability.setForbiddenFilenamesJson(getString(cursor, ProviderTableMeta.CAPABILITIES_FORBIDDEN_FILENAMES));
|
||||
capability.setForbiddenFilenameExtensionJson(getString(cursor, ProviderTableMeta.CAPABILITIES_FORBIDDEN_FORBIDDEN_FILENAME_EXTENSIONS));
|
||||
capability.setForbiddenFilenameBaseNamesJson(getString(cursor, ProviderTableMeta.CAPABILITIES_FORBIDDEN_FORBIDDEN_FILENAME_BASE_NAMES));
|
||||
capability.setWCFEnabled(getBoolean(cursor, ProviderTableMeta.CAPABILITIES_WINDOWS_COMPATIBLE_FILENAMES));
|
||||
capability.setFilesDownloadLimit(getBoolean(cursor, ProviderTableMeta.CAPABILITIES_FILES_DOWNLOAD_LIMIT));
|
||||
capability.setFilesDownloadLimitDefault(getInt(cursor, ProviderTableMeta.CAPABILITIES_FILES_DOWNLOAD_LIMIT_DEFAULT));
|
||||
|
||||
@@ -2603,6 +2607,7 @@ public class FileDataStorageManager {
|
||||
capability.setNotesFolderPath(getString(cursor, ProviderTableMeta.CAPABILITIES_NOTES_FOLDER_PATH));
|
||||
|
||||
capability.setDefaultPermissions(getInt(cursor, ProviderTableMeta.CAPABILITIES_DEFAULT_PERMISSIONS));
|
||||
capability.setHasValidSubscription(getBoolean(cursor, ProviderTableMeta.CAPABILITIES_HAS_VALID_SUBSCRIPTION));
|
||||
}
|
||||
|
||||
return capability;
|
||||
|
||||
@@ -179,6 +179,28 @@ public class SyncedFolder implements Serializable, Cloneable {
|
||||
return this.chargingOnly;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates whether the "Also upload existing files" option is enabled for this folder.
|
||||
*
|
||||
* <p>
|
||||
* This flag controls how files in the folder are treated when auto-upload is enabled:
|
||||
* <ul>
|
||||
* <li>If {@code true} (existing files are included):
|
||||
* <ul>
|
||||
* <li>All files in the folder, regardless of creation date, will be uploaded.</li>
|
||||
* </ul>
|
||||
* </li>
|
||||
* <li>If {@code false} (existing files are skipped):
|
||||
* <ul>
|
||||
* <li>Only files created or added after the folder was enabled will be uploaded.</li>
|
||||
* <li>Files that existed before enabling will be skipped, based on their creation time.</li>
|
||||
* </ul>
|
||||
* </li>
|
||||
* </ul>
|
||||
* </p>
|
||||
*
|
||||
* @return {@code true} if existing files should also be uploaded, {@code false} otherwise
|
||||
*/
|
||||
public boolean isExisting() {
|
||||
return this.existing;
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
package com.owncloud.android.datamodel;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Bitmap;
|
||||
@@ -37,7 +38,6 @@ import android.widget.ImageView;
|
||||
import com.nextcloud.client.account.User;
|
||||
import com.nextcloud.client.network.ConnectivityService;
|
||||
import com.nextcloud.utils.BitmapExtensionsKt;
|
||||
import com.nextcloud.utils.extensions.ThumbnailsCacheManagerExtensionsKt;
|
||||
import com.owncloud.android.MainApp;
|
||||
import com.owncloud.android.R;
|
||||
import com.owncloud.android.lib.common.OwnCloudAccount;
|
||||
@@ -885,7 +885,7 @@ public final class ThumbnailsCacheManager {
|
||||
private final WeakReference<ImageView> mImageViewReference;
|
||||
private File mFile;
|
||||
private String mImageKey;
|
||||
private final Context mContext;
|
||||
@SuppressLint("StaticFieldLeak") private final Context mContext;
|
||||
private final ViewThemeUtils viewThemeUtils;
|
||||
|
||||
public MediaThumbnailGenerationTask(ImageView imageView,
|
||||
@@ -1010,7 +1010,7 @@ public final class ThumbnailsCacheManager {
|
||||
private final String mUserId;
|
||||
private final String displayName;
|
||||
private final String mServerName;
|
||||
private final Context mContext;
|
||||
@SuppressLint("StaticFieldLeak") private final Context mContext;
|
||||
|
||||
|
||||
public AvatarGenerationTask(AvatarGenerationListener avatarGenerationListener,
|
||||
|
||||
@@ -483,35 +483,10 @@ public class UploadsStorageManager extends Observable {
|
||||
.toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all failed uploads.
|
||||
*/
|
||||
public OCUpload[] getFailedUploads() {
|
||||
return getUploads("(" + ProviderTableMeta.UPLOADS_STATUS + IS_EQUAL +
|
||||
OR + ProviderTableMeta.UPLOADS_LAST_RESULT +
|
||||
EQUAL + UploadResult.DELAYED_FOR_WIFI.getValue() +
|
||||
OR + ProviderTableMeta.UPLOADS_LAST_RESULT +
|
||||
EQUAL + UploadResult.LOCK_FAILED.getValue() +
|
||||
OR + ProviderTableMeta.UPLOADS_LAST_RESULT +
|
||||
EQUAL + UploadResult.DELAYED_FOR_CHARGING.getValue() +
|
||||
OR + ProviderTableMeta.UPLOADS_LAST_RESULT +
|
||||
EQUAL + UploadResult.DELAYED_IN_POWER_SAVE_MODE.getValue() +
|
||||
" ) AND " + ProviderTableMeta.UPLOADS_LAST_RESULT +
|
||||
"!= " + UploadResult.VIRUS_DETECTED.getValue()
|
||||
, String.valueOf(UploadStatus.UPLOAD_FAILED.value));
|
||||
}
|
||||
|
||||
public OCUpload[] getUploadsForAccount(final @NonNull String accountName) {
|
||||
return getUploads(ProviderTableMeta.UPLOADS_ACCOUNT_NAME + IS_EQUAL, accountName);
|
||||
}
|
||||
|
||||
public OCUpload[] getCancelledUploadsForCurrentAccount() {
|
||||
User user = currentAccountProvider.getUser();
|
||||
|
||||
return getUploads(ProviderTableMeta.UPLOADS_STATUS + EQUAL + UploadStatus.UPLOAD_CANCELLED.value + AND +
|
||||
ProviderTableMeta.UPLOADS_ACCOUNT_NAME + IS_EQUAL, user.getAccountName());
|
||||
}
|
||||
|
||||
private ContentResolver getDB() {
|
||||
return contentResolver;
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ import java.util.List;
|
||||
*/
|
||||
public class ProviderMeta {
|
||||
public static final String DB_NAME = "filelist";
|
||||
public static final int DB_VERSION = 93;
|
||||
public static final int DB_VERSION = 96;
|
||||
|
||||
private ProviderMeta() {
|
||||
// No instance
|
||||
@@ -52,6 +52,7 @@ public class ProviderMeta {
|
||||
public static final String EXTERNAL_LINKS_TABLE_NAME = "external_links";
|
||||
public static final String ARBITRARY_DATA_TABLE_NAME = "arbitrary_data";
|
||||
public static final String VIRTUAL_TABLE_NAME = "virtual";
|
||||
public static final String ASSISTANT_TABLE_NAME = "assistant";
|
||||
public static final String FILESYSTEM_TABLE_NAME = "filesystem";
|
||||
public static final String EDITORS_TABLE_NAME = "editors";
|
||||
public static final String CREATORS_TABLE_NAME = "creators";
|
||||
@@ -285,10 +286,12 @@ public class ProviderMeta {
|
||||
public static final String CAPABILITIES_FORBIDDEN_FILENAMES = "forbidden_filenames";
|
||||
public static final String CAPABILITIES_FORBIDDEN_FORBIDDEN_FILENAME_EXTENSIONS = "forbidden_filename_extensions";
|
||||
public static final String CAPABILITIES_FORBIDDEN_FORBIDDEN_FILENAME_BASE_NAMES = "forbidden_filename_basenames";
|
||||
public static final String CAPABILITIES_WINDOWS_COMPATIBLE_FILENAMES = "windows_compatible_filenames";
|
||||
public static final String CAPABILITIES_FILES_DOWNLOAD_LIMIT = "files_download_limit";
|
||||
public static final String CAPABILITIES_FILES_DOWNLOAD_LIMIT_DEFAULT = "files_download_limit_default";
|
||||
public static final String CAPABILITIES_NOTES_FOLDER_PATH = "notes_folder_path";
|
||||
public static final String CAPABILITIES_DEFAULT_PERMISSIONS = "default_permissions";
|
||||
public static final String CAPABILITIES_HAS_VALID_SUBSCRIPTION = "has_valid_subscription";
|
||||
|
||||
//Columns of Uploads table
|
||||
public static final String UPLOADS_LOCAL_PATH = "local_path";
|
||||
|
||||
@@ -7,12 +7,24 @@
|
||||
package com.owncloud.android.files.services;
|
||||
|
||||
/**
|
||||
* Ordinal of enumerated constants is important for old data compatibility.
|
||||
* Defines how to handle file name collisions during uploads.
|
||||
*
|
||||
* <p><b>Important:</b> Enum ordinals are stored directly in the database.
|
||||
* Do <b>not</b> change their order or remove constants to avoid breaking
|
||||
* compatibility with old data.</p>
|
||||
*
|
||||
* <p><b>Database value mapping:</b></p>
|
||||
* <ul>
|
||||
* <li>0 → {@link #RENAME} (old forceOverwrite = false)</li>
|
||||
* <li>1 → {@link #OVERWRITE} (old forceOverwrite = true)</li>
|
||||
* <li>2 → {@link #SKIP}</li>
|
||||
* <li>3 → {@link #ASK_USER}</li>
|
||||
* </ul>
|
||||
*/
|
||||
public enum NameCollisionPolicy {
|
||||
RENAME, // Ordinal corresponds to old forceOverwrite = false (0 in database)
|
||||
OVERWRITE, // Ordinal corresponds to old forceOverwrite = true (1 in database)
|
||||
CANCEL,
|
||||
RENAME,
|
||||
OVERWRITE,
|
||||
SKIP,
|
||||
ASK_USER;
|
||||
|
||||
public static final NameCollisionPolicy DEFAULT = RENAME;
|
||||
|
||||
@@ -1183,11 +1183,13 @@ public class UploadFileOperation extends SyncOperation {
|
||||
throws OperationCancelledException {
|
||||
Log_OC.d(TAG, "Checking name collision in server");
|
||||
|
||||
if (existsFile(client, mRemotePath, fileNames, encrypted)) {
|
||||
boolean isFileExists = existsFile(client, mRemotePath, fileNames, encrypted);
|
||||
|
||||
if (isFileExists) {
|
||||
switch (mNameCollisionPolicy) {
|
||||
case CANCEL:
|
||||
Log_OC.d(TAG, "File exists; canceling");
|
||||
throw new OperationCancelledException();
|
||||
case SKIP:
|
||||
Log_OC.d(TAG, "user choose to skip upload if same file exists");
|
||||
return new RemoteOperationResult<>(ResultCode.OK);
|
||||
case RENAME:
|
||||
mRemotePath = getNewAvailableRemotePath(client, mRemotePath, fileNames, encrypted);
|
||||
mWasRenamed = true;
|
||||
@@ -1672,5 +1674,4 @@ public class UploadFileOperation extends SyncOperation {
|
||||
|
||||
void onRenameUpload();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -138,30 +138,34 @@ class AvatarGroupLayout @JvmOverloads constructor(
|
||||
avatar: ImageView,
|
||||
viewThemeUtils: ViewThemeUtils
|
||||
) {
|
||||
// maybe federated share
|
||||
val split = user.split("@".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
|
||||
val userId: String? = split[0]
|
||||
val server = split[1]
|
||||
val split = user.split("@")
|
||||
val userId = split.getOrNull(0) ?: user
|
||||
val server = split.getOrNull(1)
|
||||
|
||||
val url = "https://" + server + "/index.php/avatar/" + userId + "/" +
|
||||
resources.getInteger(R.integer.file_avatar_px)
|
||||
var placeholder: Drawable?
|
||||
try {
|
||||
placeholder = TextDrawable.createAvatarByUserId(userId, avatarRadius)
|
||||
val url = if (server != null) {
|
||||
"https://$server/index.php/avatar/$userId/${resources.getInteger(R.integer.file_avatar_px)}"
|
||||
} else {
|
||||
// fallback: no federated server, maybe use local avatar
|
||||
null
|
||||
}
|
||||
|
||||
val placeholder: Drawable = try {
|
||||
TextDrawable.createAvatarByUserId(userId, avatarRadius)
|
||||
} catch (e: Exception) {
|
||||
Log_OC.e(TAG, "Error calculating RGB value for active account icon.", e)
|
||||
placeholder = viewThemeUtils.platform.colorDrawable(
|
||||
ResourcesCompat.getDrawable(
|
||||
resources,
|
||||
R.drawable.account_circle_white,
|
||||
null
|
||||
)!!,
|
||||
viewThemeUtils.platform.colorDrawable(
|
||||
ResourcesCompat
|
||||
.getDrawable(resources, R.drawable.account_circle_white, null)!!,
|
||||
ContextCompat.getColor(context, R.color.black)
|
||||
)
|
||||
}
|
||||
|
||||
avatar.tag = null
|
||||
loadCircularBitmapIntoImageView(context, url, avatar, placeholder)
|
||||
if (url != null) {
|
||||
loadCircularBitmapIntoImageView(context, url, avatar, placeholder)
|
||||
} else {
|
||||
avatar.setImageDrawable(placeholder)
|
||||
}
|
||||
}
|
||||
|
||||
override fun avatarGenerated(avatarDrawable: Drawable?, callContext: Any) {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
package com.owncloud.android.ui;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.preference.SwitchPreference;
|
||||
import android.util.AttributeSet;
|
||||
@@ -54,7 +55,7 @@ public class ThemeableSwitchPreference extends SwitchPreference {
|
||||
for (int i = 0; i < viewGroup.getChildCount(); i++) {
|
||||
View child = viewGroup.getChildAt(i);
|
||||
|
||||
if (child instanceof Switch switchView) {
|
||||
if (child instanceof @SuppressLint("UseSwitchCompatOrMaterialCode") Switch switchView) {
|
||||
viewThemeUtils.platform.colorSwitch(switchView);
|
||||
|
||||
break;
|
||||
|
||||
+4
-3
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
package com.owncloud.android.ui.activities.data.files;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.os.AsyncTask;
|
||||
|
||||
@@ -33,8 +34,8 @@ public class FilesServiceApiImpl implements FilesServiceApi {
|
||||
|
||||
private static final String TAG = FilesServiceApiImpl.class.getSimpleName();
|
||||
|
||||
private UserAccountManager accountManager;
|
||||
private ClientFactory clientFactory;
|
||||
private final UserAccountManager accountManager;
|
||||
private final ClientFactory clientFactory;
|
||||
|
||||
public FilesServiceApiImpl(UserAccountManager accountManager, ClientFactory clientFactory) {
|
||||
this.accountManager = accountManager;
|
||||
@@ -58,7 +59,7 @@ public class FilesServiceApiImpl implements FilesServiceApi {
|
||||
private OCFile remoteOcFile;
|
||||
private String errorMessage;
|
||||
// TODO: Figure out a better way to do this than passing a BaseActivity reference.
|
||||
private final BaseActivity baseActivity;
|
||||
@SuppressLint("StaticFieldLeak") private final BaseActivity baseActivity;
|
||||
private final String fileUrl;
|
||||
private final User user;
|
||||
private final UserAccountManager accountManager;
|
||||
|
||||
+2
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
package com.owncloud.android.ui.activity;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.AsyncTask;
|
||||
@@ -194,6 +195,7 @@ public class ErrorsWhileCopyingHandlerActivity extends AppCompatActivity implem
|
||||
/**
|
||||
* Asynchronous task performing the move of all the local files to the ownCloud folder.
|
||||
*/
|
||||
@SuppressLint("StaticFieldLeak")
|
||||
private class MoveFilesTask extends AsyncTask<Void, Void, Boolean> {
|
||||
|
||||
/**
|
||||
|
||||
@@ -334,6 +334,7 @@ public abstract class FileActivity extends DrawerActivity
|
||||
*
|
||||
* @return Main {@link OCFile} handled by the activity.
|
||||
*/
|
||||
@Nullable
|
||||
public OCFile getFile() {
|
||||
return mFile;
|
||||
}
|
||||
@@ -654,6 +655,7 @@ public abstract class FileActivity extends DrawerActivity
|
||||
return fileUploadHelper;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public OCFile getCurrentDir() {
|
||||
OCFile file = getFile();
|
||||
if (file != null) {
|
||||
|
||||
@@ -431,7 +431,8 @@ class FileDisplayActivity :
|
||||
CapabilityUtils.checkOutdatedWarning(
|
||||
getResources(),
|
||||
user.get().server.version,
|
||||
capabilities.extendedSupport.isTrue
|
||||
capabilities.extendedSupport.isTrue,
|
||||
capabilities.hasValidSubscription.isTrue
|
||||
)
|
||||
) {
|
||||
DisplayUtils.showServerOutdatedSnackbar(this, Snackbar.LENGTH_LONG)
|
||||
@@ -585,6 +586,7 @@ class FileDisplayActivity :
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("UnsafeIntentLaunch")
|
||||
private fun handleRestartIntent(intent: Intent) {
|
||||
if (intent.action != RESTART) {
|
||||
return
|
||||
@@ -1070,7 +1072,7 @@ class FileDisplayActivity :
|
||||
localBasePath = "$localBasePath/"
|
||||
}
|
||||
|
||||
val remotePathBase = getCurrentDir().remotePath
|
||||
val remotePathBase = getCurrentDir()?.remotePath
|
||||
val decryptedRemotePaths = getRemotePaths(remotePathBase, filePaths, localBasePath)
|
||||
|
||||
val behaviour = when (resultCode) {
|
||||
@@ -1081,8 +1083,8 @@ class FileDisplayActivity :
|
||||
|
||||
connectivityService.isNetworkAndServerAvailable { result: Boolean? ->
|
||||
if (result == true) {
|
||||
val isValidFolderPath = checkFolderPath(remotePathBase, capabilities, this)
|
||||
if (!isValidFolderPath) {
|
||||
val isValidFolderPath = remotePathBase?.let { checkFolderPath(it, capabilities, this) }
|
||||
if (isValidFolderPath == false) {
|
||||
DisplayUtils.showSnackMessage(
|
||||
this,
|
||||
R.string.file_name_validator_error_contains_reserved_names_or_invalid_characters
|
||||
@@ -1311,10 +1313,11 @@ class FileDisplayActivity :
|
||||
val ocFileListFragment = leftFragment
|
||||
syncAndUpdateFolder(ignoreETag = true, ignoreFocus = true)
|
||||
|
||||
var startFile: OCFile? = null
|
||||
if (intent != null) {
|
||||
startFile = getFileFromIntent(intent)
|
||||
file = startFile
|
||||
// Try to get the OCFile from the intent, if one was provided when launching this activity.
|
||||
// 'file' comes from the FileActivity base class and represents the currently opened file or folder.
|
||||
// We update it only when a valid file is found in the intent.
|
||||
val startFile = intent?.let { getFileFromIntent(it) }?.also {
|
||||
file = it
|
||||
}
|
||||
|
||||
// refresh list of files
|
||||
@@ -1492,9 +1495,8 @@ class FileDisplayActivity :
|
||||
return
|
||||
}
|
||||
|
||||
var currentFile = if (file == null) null else storageManager.getFileByPath(file.remotePath)
|
||||
val currentDir =
|
||||
if (getCurrentDir() == null) null else storageManager.getFileByPath(getCurrentDir().remotePath)
|
||||
var currentFile = file?.remotePath?.let { storageManager.getFileByPath(it) }
|
||||
val currentDir = getCurrentDir()?.remotePath?.let { storageManager.getFileByPath(it) }
|
||||
val isSyncFolderRemotePathRoot = OCFile.ROOT_PATH == syncFolderRemotePath
|
||||
|
||||
if (currentDir == null && !isSyncFolderRemotePathRoot) {
|
||||
@@ -1518,7 +1520,7 @@ class FileDisplayActivity :
|
||||
}
|
||||
|
||||
private fun handleRemovedFileFromServer(currentFile: OCFile?, currentDir: OCFile?): OCFile? {
|
||||
if (currentFile == null && !file.isFolder) {
|
||||
if (currentFile == null && file?.isFolder == false) {
|
||||
resetTitleBarAndScrolling()
|
||||
return currentDir
|
||||
}
|
||||
@@ -1667,8 +1669,8 @@ class FileDisplayActivity :
|
||||
var sameFile = false
|
||||
if (file != null) {
|
||||
renamedInUpload =
|
||||
file.remotePath == intent.getStringExtra(FileUploadWorker.EXTRA_OLD_REMOTE_PATH)
|
||||
sameFile = file.remotePath == uploadedRemotePath || renamedInUpload
|
||||
file?.remotePath == intent.getStringExtra(FileUploadWorker.EXTRA_OLD_REMOTE_PATH)
|
||||
sameFile = file?.remotePath == uploadedRemotePath || renamedInUpload
|
||||
}
|
||||
|
||||
if (sameAccount && sameFile && this@FileDisplayActivity.leftFragment is FileDetailFragment) {
|
||||
@@ -1688,7 +1690,7 @@ class FileDisplayActivity :
|
||||
)
|
||||
}
|
||||
|
||||
if (uploadWasFine || file != null && file.fileExists()) {
|
||||
if (uploadWasFine || file?.fileExists() == true) {
|
||||
fileDetailFragment.updateFileDetails(false, true)
|
||||
} else {
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
@@ -1696,13 +1698,13 @@ class FileDisplayActivity :
|
||||
|
||||
// Force the preview if the file is an image or text file
|
||||
if (uploadWasFine) {
|
||||
val ocFile = file
|
||||
if (PreviewImageFragment.canBePreviewed(ocFile)) {
|
||||
startImagePreview(file, true)
|
||||
} else if (PreviewTextFileFragment.canBePreviewed(ocFile)) {
|
||||
startTextPreview(ocFile, true)
|
||||
file?.let {
|
||||
if (PreviewImageFragment.canBePreviewed(it)) {
|
||||
startImagePreview(it, true)
|
||||
} else if (PreviewTextFileFragment.canBePreviewed(it)) {
|
||||
startTextPreview(it, true)
|
||||
}
|
||||
}
|
||||
// TODO what about other kind of previews?
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1960,7 +1962,7 @@ class FileDisplayActivity :
|
||||
if (getCurrentDir() !=
|
||||
null
|
||||
) {
|
||||
storageManager.getFileByDecryptedRemotePath(getCurrentDir().remotePath)
|
||||
storageManager.getFileByDecryptedRemotePath(getCurrentDir()?.remotePath)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
@@ -2130,17 +2132,17 @@ class FileDisplayActivity :
|
||||
val file = getFile()
|
||||
|
||||
// delete old local copy
|
||||
if (file.isDown) {
|
||||
if (file?.isDown == true) {
|
||||
val list: MutableList<OCFile?> = ArrayList()
|
||||
list.add(file)
|
||||
fileOperationsHelper.removeFiles(list, true, true)
|
||||
|
||||
// download new version, only if file was previously download
|
||||
showSyncLoadingDialog(file.isFolder)
|
||||
showSyncLoadingDialog(file.isFolder == true)
|
||||
fileOperationsHelper.syncFile(file)
|
||||
}
|
||||
|
||||
val parent = storageManager.getFileById(file.parentId)
|
||||
val parent = file?.let { storageManager.getFileById(it.parentId) }
|
||||
startSyncFolderOperation(parent, ignoreETag = true, ignoreFocus = true)
|
||||
|
||||
val leftFragment = this.leftFragment
|
||||
@@ -2973,11 +2975,17 @@ class FileDisplayActivity :
|
||||
}
|
||||
|
||||
fun performUnifiedSearch(query: String, listOfHiddenFiles: ArrayList<String>?) {
|
||||
val path = currentDir?.decryptedRemotePath
|
||||
?: run {
|
||||
Log_OC.w(TAG, "currentDir is null, using ROOT_PATH")
|
||||
OCFile.ROOT_PATH
|
||||
}
|
||||
|
||||
val unifiedSearchFragment =
|
||||
UnifiedSearchFragment.Companion.newInstance(
|
||||
query,
|
||||
listOfHiddenFiles,
|
||||
currentDir.decryptedRemotePath
|
||||
path
|
||||
)
|
||||
setLeftFragment(unifiedSearchFragment, false)
|
||||
}
|
||||
|
||||
@@ -21,7 +21,9 @@ import android.view.Menu
|
||||
import android.view.MenuItem
|
||||
import android.view.View
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager
|
||||
import com.nextcloud.client.account.User
|
||||
import com.nextcloud.client.di.Injectable
|
||||
import com.nextcloud.utils.fileNameValidator.FileNameValidator
|
||||
import com.owncloud.android.R
|
||||
@@ -48,6 +50,8 @@ import com.owncloud.android.utils.DisplayUtils
|
||||
import com.owncloud.android.utils.ErrorMessageAdapter
|
||||
import com.owncloud.android.utils.FileSortOrder
|
||||
import com.owncloud.android.utils.PathUtils
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
import javax.inject.Inject
|
||||
|
||||
@@ -60,7 +64,6 @@ open class FolderPickerActivity :
|
||||
OnSortingOrderListener {
|
||||
|
||||
private var mSyncBroadcastReceiver: SyncBroadcastReceiver? = null
|
||||
private var mSyncInProgress = false
|
||||
private var mSearchOnlyFolders = false
|
||||
var isDoNotEnterEncryptedFolder = false
|
||||
private set
|
||||
@@ -105,7 +108,6 @@ open class FolderPickerActivity :
|
||||
}
|
||||
|
||||
updateActionBarTitleAndHomeButtonByString(captionText)
|
||||
setBackgroundText()
|
||||
handleBackPress()
|
||||
}
|
||||
|
||||
@@ -211,25 +213,6 @@ open class FolderPickerActivity :
|
||||
transaction.commit()
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a text message on screen view for notifying user if content is loading or folder is empty
|
||||
*/
|
||||
private fun setBackgroundText() {
|
||||
val listFragment = listOfFilesFragment
|
||||
|
||||
if (listFragment == null) {
|
||||
Log_OC.e(TAG, "OCFileListFragment is null")
|
||||
}
|
||||
|
||||
listFragment?.let {
|
||||
if (mSyncInProgress) {
|
||||
it.setEmptyListMessage(EmptyListState.LOADING)
|
||||
} else {
|
||||
it.setEmptyListMessage(EmptyListState.ADD_FOLDER)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected val listOfFilesFragment: OCFileListFragment?
|
||||
get() {
|
||||
val listOfFiles = supportFragmentManager.findFragmentByTag(TAG_LIST_OF_FOLDERS)
|
||||
@@ -259,21 +242,33 @@ open class FolderPickerActivity :
|
||||
}
|
||||
|
||||
private fun startSyncFolderOperation(folder: OCFile?, ignoreETag: Boolean) {
|
||||
val currentSyncTime = System.currentTimeMillis()
|
||||
mSyncInProgress = true
|
||||
|
||||
RefreshFolderOperation(
|
||||
folder,
|
||||
currentSyncTime,
|
||||
false,
|
||||
ignoreETag,
|
||||
storageManager,
|
||||
user.orElseThrow { RuntimeException("User not set") },
|
||||
applicationContext
|
||||
).also {
|
||||
it.execute(account, this, null, null)
|
||||
val optionalUser = user ?: return
|
||||
if (optionalUser.isEmpty) {
|
||||
return
|
||||
}
|
||||
val user: User = optionalUser.get()
|
||||
listOfFilesFragment?.setEmptyListMessage(EmptyListState.LOADING)
|
||||
|
||||
lifecycleScope.launch(Dispatchers.IO) {
|
||||
val currentSyncTime = System.currentTimeMillis()
|
||||
val operation = RefreshFolderOperation(
|
||||
folder,
|
||||
currentSyncTime,
|
||||
false,
|
||||
ignoreETag,
|
||||
storageManager,
|
||||
user,
|
||||
applicationContext
|
||||
)
|
||||
operation.execute(
|
||||
account,
|
||||
this@FolderPickerActivity,
|
||||
{ _, _ ->
|
||||
listOfFilesFragment?.setEmptyListMessage(EmptyListState.LOCAL_FILE_LIST_EMPTY_FILE)
|
||||
},
|
||||
null
|
||||
)
|
||||
}
|
||||
setBackgroundText()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
@@ -414,10 +409,10 @@ open class FolderPickerActivity :
|
||||
file?.isFolder != true -> true
|
||||
|
||||
// all of the target files are already in the selected directory
|
||||
targetFilePaths?.all { PathUtils.isDirectParent(file.remotePath, it) } == true -> false
|
||||
targetFilePaths?.all { PathUtils.isDirectParent(file?.remotePath ?: "", it) } == true -> false
|
||||
|
||||
// some of the target files are parents of the selected folder
|
||||
targetFilePaths?.any { PathUtils.isAncestor(it, file.remotePath) } == true -> false
|
||||
targetFilePaths?.any { PathUtils.isAncestor(it, file?.remotePath ?: "") } == true -> false
|
||||
else -> true
|
||||
}
|
||||
|
||||
@@ -434,7 +429,7 @@ open class FolderPickerActivity :
|
||||
}
|
||||
|
||||
private fun getSelectedFolderPathTitle(): String? {
|
||||
val atRoot = (currentDir == null || currentDir.parentId == 0L)
|
||||
val atRoot = (currentDir == null || currentDir?.parentId == 0L)
|
||||
return if (atRoot) captionText ?: "" else currentDir?.fileName
|
||||
}
|
||||
|
||||
@@ -554,15 +549,13 @@ open class FolderPickerActivity :
|
||||
return
|
||||
}
|
||||
|
||||
if (FileSyncAdapter.EVENT_FULL_SYNC_START == event) {
|
||||
mSyncInProgress = true
|
||||
} else {
|
||||
if (FileSyncAdapter.EVENT_FULL_SYNC_START != event) {
|
||||
var (currentFile, currentDir) = getCurrentFileAndDirectory()
|
||||
|
||||
if (currentDir == null) {
|
||||
browseRootForRemovedFolder()
|
||||
} else {
|
||||
if (currentFile == null && !file.isFolder) {
|
||||
if (currentFile == null && file?.isFolder == false) {
|
||||
// currently selected file was removed in the server, and now we know it
|
||||
currentFile = currentDir
|
||||
}
|
||||
@@ -572,28 +565,22 @@ open class FolderPickerActivity :
|
||||
file = currentFile
|
||||
}
|
||||
|
||||
mSyncInProgress = (
|
||||
FileSyncAdapter.EVENT_FULL_SYNC_END != event &&
|
||||
RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED != event
|
||||
)
|
||||
|
||||
checkCredentials(syncResult, event)
|
||||
}
|
||||
|
||||
DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT))
|
||||
Log_OC.d(TAG, "Setting progress visibility to $mSyncInProgress")
|
||||
setBackgroundText()
|
||||
} catch (e: RuntimeException) {
|
||||
Log_OC.e(TAG, "Error on broadcast receiver", e)
|
||||
// avoid app crashes after changing the serial id of RemoteOperationResult
|
||||
// in owncloud library with broadcast notifications pending to process
|
||||
DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT))
|
||||
} finally {
|
||||
listOfFilesFragment?.setEmptyListMessage(EmptyListState.LOCAL_FILE_LIST_EMPTY_FILE)
|
||||
}
|
||||
}
|
||||
|
||||
private fun getCurrentFileAndDirectory(): Pair<OCFile?, OCFile?> {
|
||||
val currentFile =
|
||||
if (file == null) null else storageManager.getFileByEncryptedRemotePath(file.remotePath)
|
||||
val currentFile = file?.let { storageManager.getFileByEncryptedRemotePath(it.remotePath) }
|
||||
|
||||
val currentDir = if (currentFolder == null) {
|
||||
null
|
||||
|
||||
@@ -185,7 +185,7 @@ class RichDocumentsEditorWebView : EditorWebView() {
|
||||
renameString ?: return
|
||||
val renameJson = JSONObject(renameString)
|
||||
val newName = renameJson.getString(NEW_NAME)
|
||||
file.fileName = newName
|
||||
file?.fileName = newName
|
||||
} catch (e: JSONException) {
|
||||
Log_OC.e(this, "Failed to parse rename json message: $e")
|
||||
}
|
||||
|
||||
@@ -11,11 +11,10 @@ package com.owncloud.android.ui.activity;
|
||||
|
||||
import android.accounts.Account;
|
||||
import android.accounts.AccountManager;
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.ProgressDialog;
|
||||
import android.content.ContentResolver;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.DialogInterface.OnClickListener;
|
||||
import android.os.AsyncTask;
|
||||
import android.view.View;
|
||||
|
||||
@@ -177,7 +176,7 @@ public class StorageMigration {
|
||||
private static abstract class FileMigrationTaskBase extends AsyncTask<Void, Integer, Integer> {
|
||||
protected String mStorageSource;
|
||||
protected String mStorageTarget;
|
||||
protected Context mContext;
|
||||
@SuppressLint("StaticFieldLeak") protected Context mContext;
|
||||
protected User user;
|
||||
protected ProgressDialog mProgressDialog;
|
||||
protected StorageMigrationProgressListener mListener;
|
||||
|
||||
@@ -43,7 +43,7 @@ class TextEditorWebView : EditorWebView() {
|
||||
finish()
|
||||
}
|
||||
|
||||
val editor = editorUtils.getEditor(user.get(), file.mimeType)
|
||||
val editor = editorUtils.getEditor(user.get(), file?.mimeType)
|
||||
|
||||
if (editor != null && editor.id == "onlyoffice") {
|
||||
webView.settings.userAgentString = generateOnlyOfficeUserAgent()
|
||||
|
||||
@@ -41,7 +41,6 @@ import com.owncloud.android.lib.common.utils.Log_OC;
|
||||
import com.owncloud.android.operations.CheckCurrentCredentialsOperation;
|
||||
import com.owncloud.android.ui.adapter.UploadListAdapter;
|
||||
import com.owncloud.android.ui.decoration.MediaGridItemDecoration;
|
||||
import com.owncloud.android.utils.DisplayUtils;
|
||||
import com.owncloud.android.utils.FilesSyncHelper;
|
||||
|
||||
import javax.inject.Inject;
|
||||
@@ -133,15 +132,13 @@ public class UploadListActivity extends FileActivity {
|
||||
WorkerStateLiveData.Companion.instance().observe(this, state -> {
|
||||
if (state instanceof WorkerState.UploadStarted) {
|
||||
Log_OC.d(TAG, "Upload worker started");
|
||||
handleUploadWorkerState();
|
||||
uploadListAdapter.loadUploadItemsFromDb();
|
||||
} else if (state instanceof WorkerState.UploadFinished) {
|
||||
uploadListAdapter.loadUploadItemsFromDb(() -> swipeListRefreshLayout.setRefreshing(false));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void handleUploadWorkerState() {
|
||||
uploadListAdapter.loadUploadItemsFromDb();
|
||||
}
|
||||
|
||||
private void setupContent() {
|
||||
binding.list.setEmptyView(binding.emptyList.getRoot());
|
||||
binding.emptyList.getRoot().setVisibility(View.GONE);
|
||||
@@ -182,25 +179,15 @@ public class UploadListActivity extends FileActivity {
|
||||
}
|
||||
|
||||
private void refresh() {
|
||||
FilesSyncHelper.startAutoUploadImmediately(syncedFolderProvider,
|
||||
backgroundJobManager,
|
||||
true);
|
||||
boolean isUploadStarted = FileUploadHelper.Companion.instance().retryFailedUploads(
|
||||
uploadsStorageManager,
|
||||
connectivityService,
|
||||
accountManager,
|
||||
powerManagementService);
|
||||
|
||||
if (uploadsStorageManager.getFailedUploads().length > 0) {
|
||||
new Thread(() -> {
|
||||
FileUploadHelper.Companion.instance().retryFailedUploads(
|
||||
uploadsStorageManager,
|
||||
connectivityService,
|
||||
accountManager,
|
||||
powerManagementService);
|
||||
uploadListAdapter.loadUploadItemsFromDb();
|
||||
}).start();
|
||||
DisplayUtils.showSnackMessage(this, R.string.uploader_local_files_uploaded);
|
||||
if (!isUploadStarted) {
|
||||
uploadListAdapter.loadUploadItemsFromDb(() -> swipeListRefreshLayout.setRefreshing(false));
|
||||
}
|
||||
|
||||
|
||||
// update UI
|
||||
uploadListAdapter.loadUploadItemsFromDb(() -> swipeListRefreshLayout.setRefreshing(false));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
*/
|
||||
package com.owncloud.android.ui.activity;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.graphics.drawable.LayerDrawable;
|
||||
import android.os.Bundle;
|
||||
@@ -392,6 +393,7 @@ public class UserInfoActivity extends DrawerActivity implements Injectable {
|
||||
this.viewThemeUtils = viewThemeUtils;
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
public void setData(List<UserInfoDetailsItem> displayList) {
|
||||
mDisplayList = displayList == null ? new LinkedList<>() : displayList;
|
||||
notifyDataSetChanged();
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
package com.owncloud.android.ui.adapter;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.text.format.DateFormat;
|
||||
import android.view.LayoutInflater;
|
||||
@@ -54,6 +55,7 @@ public class ActivityAndVersionListAdapter extends ActivityListAdapter {
|
||||
this.versionListInterface = versionListInterface;
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
public void setActivityAndVersionItems(List<Object> items, NextcloudClient newClient, boolean clear) {
|
||||
if (client == null) {
|
||||
client = newClient;
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
package com.owncloud.android.ui.adapter;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.content.res.Configuration;
|
||||
import android.content.res.Resources;
|
||||
@@ -98,6 +99,7 @@ public class ActivityListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
|
||||
this.viewThemeUtils = viewThemeUtils;
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
public void setActivityItems(List<Object> activityItems, NextcloudClient client, boolean clear) {
|
||||
this.client = client;
|
||||
String sTime = "";
|
||||
|
||||
@@ -15,8 +15,6 @@ package com.owncloud.android.ui.adapter
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
@@ -31,6 +29,7 @@ import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
import com.owncloud.android.datamodel.GalleryItems
|
||||
import com.owncloud.android.datamodel.GalleryRow
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.ui.activity.ComponentsGetter
|
||||
import com.owncloud.android.ui.fragment.GalleryFragment
|
||||
import com.owncloud.android.ui.fragment.GalleryFragmentBottomSheetDialog
|
||||
@@ -57,7 +56,28 @@ class GalleryAdapter(
|
||||
) : SectionedRecyclerViewAdapter<SectionedViewHolder>(),
|
||||
CommonOCFileListAdapterInterface,
|
||||
PopupTextProvider {
|
||||
var files: List<GalleryItems> = mutableListOf()
|
||||
|
||||
companion object {
|
||||
private const val TAG = "GalleryAdapter"
|
||||
}
|
||||
|
||||
// fileId -> (section, row)
|
||||
private val filePositionMap = mutableMapOf<Long, Pair<Int, Int>>()
|
||||
|
||||
// (section, row) -> unique stable ID for that row
|
||||
private val rowIdMap = mutableMapOf<Pair<Int, Int>, Long>()
|
||||
|
||||
private var cachedAllFiles: List<OCFile>? = null
|
||||
private var cachedFilesCount: Int = 0
|
||||
|
||||
private var _files: List<GalleryItems> = mutableListOf()
|
||||
var files: List<GalleryItems>
|
||||
get() = _files
|
||||
private set(value) {
|
||||
_files = value
|
||||
invalidateCaches()
|
||||
}
|
||||
|
||||
private val ocFileListDelegate: OCFileListDelegate
|
||||
private var storageManager: FileDataStorageManager = transferServiceGetter.storageManager
|
||||
|
||||
@@ -78,7 +98,50 @@ class GalleryAdapter(
|
||||
)
|
||||
}
|
||||
|
||||
override fun getItemId(section: Int, position: Int): Long = files[section].rows[position].calculateHashCode()
|
||||
private fun invalidateCaches() {
|
||||
Log_OC.d(TAG, "invalidating caches")
|
||||
cachedAllFiles = null
|
||||
updateFilesCount()
|
||||
rebuildFilePositionMap()
|
||||
}
|
||||
|
||||
private fun updateFilesCount() {
|
||||
cachedFilesCount = files.fold(0) { acc, item -> acc + item.rows.size }
|
||||
}
|
||||
|
||||
private fun rebuildFilePositionMap() {
|
||||
filePositionMap.clear()
|
||||
rowIdMap.clear()
|
||||
|
||||
files.forEachIndexed { sectionIndex, galleryItem ->
|
||||
galleryItem.rows.forEachIndexed { rowIndex, row ->
|
||||
val position = sectionIndex to rowIndex
|
||||
|
||||
// since row can contain files two to five use first files id as adapter id
|
||||
row.files.firstOrNull()?.fileId?.let { firstFileId ->
|
||||
rowIdMap[position] = firstFileId
|
||||
}
|
||||
|
||||
// map all row files
|
||||
row.files.forEach { file ->
|
||||
filePositionMap[file.fileId] = position
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun getItemId(section: Int, position: Int): Long = rowIdMap[section to position] ?: -1L
|
||||
|
||||
override fun getItemCount(section: Int): Int = files.getOrNull(section)?.rows?.size ?: 0
|
||||
|
||||
override fun getSectionCount(): Int = files.size
|
||||
|
||||
override fun getFilesCount(): Int = cachedFilesCount
|
||||
|
||||
override fun getItemPosition(file: OCFile): Int {
|
||||
val (section, row) = filePositionMap[file.fileId] ?: return -1
|
||||
return getAbsolutePosition(section, row)
|
||||
}
|
||||
|
||||
override fun selectAll(value: Boolean) {
|
||||
if (value) {
|
||||
@@ -116,16 +179,12 @@ class GalleryAdapter(
|
||||
relativePosition: Int,
|
||||
absolutePosition: Int
|
||||
) {
|
||||
if (holder != null) {
|
||||
val rowHolder = holder as GalleryRowHolder
|
||||
rowHolder.bind(files[section].rows[relativePosition])
|
||||
if (holder is GalleryRowHolder) {
|
||||
val row = files.getOrNull(section)?.rows?.getOrNull(relativePosition)
|
||||
row?.let { holder.bind(it) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun getItemCount(section: Int): Int = files[section].rows.size
|
||||
|
||||
override fun getSectionCount(): Int = files.size
|
||||
|
||||
override fun getPopupText(p0: View, position: Int): CharSequence = DisplayUtils.getDateByPattern(
|
||||
files[getRelativePosition(position).section()].date,
|
||||
context,
|
||||
@@ -150,10 +209,6 @@ class GalleryAdapter(
|
||||
}
|
||||
}
|
||||
|
||||
override fun onBindFooterViewHolder(holder: SectionedViewHolder?, section: Int) {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
fun showAllGalleryItems(
|
||||
remotePath: String,
|
||||
@@ -194,36 +249,32 @@ class GalleryAdapter(
|
||||
photoFragment.setEmptyListMessage(SearchType.GALLERY_SEARCH)
|
||||
}
|
||||
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
files = finalSortedList.toGalleryItems()
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
files = finalSortedList.toGalleryItems()
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
private fun transformToRows(list: List<OCFile>): List<GalleryRow> = list
|
||||
.sortedBy { it.modificationTimestamp }
|
||||
.reversed()
|
||||
.chunked(columns)
|
||||
.map { entry -> GalleryRow(entry, defaultThumbnailSize, defaultThumbnailSize) }
|
||||
private fun transformToRows(list: List<OCFile>): List<GalleryRow> {
|
||||
if (list.isEmpty()) return emptyList()
|
||||
|
||||
return list
|
||||
.sortedByDescending { it.modificationTimestamp }
|
||||
.chunked(columns)
|
||||
.map { chunk -> GalleryRow(chunk, defaultThumbnailSize, defaultThumbnailSize) }
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
fun clear() {
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
files = emptyList()
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
files = emptyList()
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
private fun firstOfMonth(timestamp: Long): Long {
|
||||
val cal = Calendar.getInstance()
|
||||
cal.time = Date(timestamp)
|
||||
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH))
|
||||
cal.set(Calendar.HOUR_OF_DAY, 0)
|
||||
cal.set(Calendar.MINUTE, 0)
|
||||
cal.set(Calendar.SECOND, 0)
|
||||
|
||||
return cal.timeInMillis
|
||||
}
|
||||
private fun firstOfMonth(timestamp: Long): Long = Calendar.getInstance().apply {
|
||||
time = Date(timestamp)
|
||||
set(Calendar.DAY_OF_MONTH, getActualMinimum(Calendar.DAY_OF_MONTH))
|
||||
set(Calendar.HOUR_OF_DAY, 0)
|
||||
set(Calendar.MINUTE, 0)
|
||||
set(Calendar.SECOND, 0)
|
||||
}.timeInMillis
|
||||
|
||||
fun isEmpty(): Boolean = files.isEmpty()
|
||||
|
||||
@@ -244,37 +295,6 @@ class GalleryAdapter(
|
||||
ocFileListDelegate.cancelAllPendingTasks()
|
||||
}
|
||||
|
||||
override fun getItemPosition(file: OCFile): Int {
|
||||
val findResult = files
|
||||
.asSequence()
|
||||
.flatMapIndexed { itemIndex, item ->
|
||||
item.rows.withIndex().map { row -> Triple(itemIndex, row.index, row.value) }
|
||||
}.find {
|
||||
it.third.files.contains(file)
|
||||
}
|
||||
|
||||
val (item, row) = findResult ?: Triple(0, 0, null)
|
||||
return getAbsolutePosition(item, row)
|
||||
}
|
||||
|
||||
override fun swapDirectory(
|
||||
user: User,
|
||||
directory: OCFile,
|
||||
storageManager: FileDataStorageManager,
|
||||
onlyOnDevice: Boolean,
|
||||
mLimitToMimeType: String
|
||||
) {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
override fun setHighlightedItem(file: OCFile) {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
override fun setSortOrder(mFile: OCFile, sortOrder: FileSortOrder) {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
override fun addCheckedFile(file: OCFile) {
|
||||
ocFileListDelegate.addCheckedFile(file)
|
||||
}
|
||||
@@ -288,23 +308,20 @@ class GalleryAdapter(
|
||||
}
|
||||
|
||||
override fun notifyItemChanged(file: OCFile) {
|
||||
notifyItemChanged(getItemPosition(file))
|
||||
}
|
||||
|
||||
override fun getFilesCount(): Int = files.fold(0) { acc, item -> acc + item.rows.size }
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
override fun setMultiSelect(boolean: Boolean) {
|
||||
ocFileListDelegate.isMultiSelect = boolean
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
private fun getAllFiles(): List<OCFile> = files.flatMap { galleryItem ->
|
||||
galleryItem.rows.flatMap { row ->
|
||||
row.files
|
||||
val position = getItemPosition(file)
|
||||
if (position >= 0) {
|
||||
notifyItemChanged(position)
|
||||
}
|
||||
}
|
||||
|
||||
override fun setMultiSelect(boolean: Boolean) {
|
||||
ocFileListDelegate.isMultiSelect = boolean
|
||||
}
|
||||
|
||||
private fun getAllFiles(): List<OCFile> = cachedAllFiles ?: files.flatMap { galleryItem ->
|
||||
galleryItem.rows.flatMap { row -> row.files }
|
||||
}.also { cachedAllFiles = it }
|
||||
|
||||
private fun addAllFilesToCheckedFiles() {
|
||||
val allFiles = getAllFiles()
|
||||
ocFileListDelegate.addToCheckedFiles(allFiles)
|
||||
@@ -323,24 +340,36 @@ class GalleryAdapter(
|
||||
columns = newColumn
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
fun markAsFavorite(remotePath: String, favorite: Boolean) {
|
||||
val allFiles = getAllFiles()
|
||||
for (file in allFiles) {
|
||||
if (file.remotePath == remotePath) {
|
||||
file.isFavorite = favorite
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
allFiles.firstOrNull { it.remotePath == remotePath }?.also { file ->
|
||||
file.isFavorite = favorite
|
||||
files = allFiles.toGalleryItems()
|
||||
notifyDataSetChanged()
|
||||
notifyItemChanged(file)
|
||||
}
|
||||
}
|
||||
|
||||
private fun List<OCFile>.toGalleryItems(): List<GalleryItems> = this
|
||||
.groupBy { firstOfMonth(it.modificationTimestamp) }
|
||||
.map { GalleryItems(it.key, transformToRows(it.value)) }
|
||||
.sortedBy { it.date }.reversed()
|
||||
private fun List<OCFile>.toGalleryItems(): List<GalleryItems> {
|
||||
if (isEmpty()) return emptyList()
|
||||
|
||||
return groupBy { firstOfMonth(it.modificationTimestamp) }
|
||||
.map { (date, filesList) ->
|
||||
GalleryItems(date, transformToRows(filesList))
|
||||
}
|
||||
.sortedByDescending { it.date }
|
||||
}
|
||||
|
||||
override fun onBindFooterViewHolder(holder: SectionedViewHolder?, section: Int) = Unit
|
||||
|
||||
override fun swapDirectory(
|
||||
user: User,
|
||||
directory: OCFile,
|
||||
storageManager: FileDataStorageManager,
|
||||
onlyOnDevice: Boolean,
|
||||
mLimitToMimeType: String
|
||||
) = Unit
|
||||
|
||||
override fun setHighlightedItem(file: OCFile) = Unit
|
||||
|
||||
override fun setSortOrder(mFile: OCFile, sortOrder: FileSortOrder) = Unit
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
package com.owncloud.android.ui.adapter;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Intent;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Typeface;
|
||||
@@ -75,6 +76,7 @@ public class NotificationListAdapter extends RecyclerView.Adapter<NotificationLi
|
||||
notificationsActivity.getResources().getColor(R.color.text_color));
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
public void setNotificationItems(List<Notification> notificationItems) {
|
||||
notificationsList.clear();
|
||||
notificationsList.addAll(notificationItems);
|
||||
@@ -340,6 +342,7 @@ public class NotificationListAdapter extends RecyclerView.Adapter<NotificationLi
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
public void removeAllNotifications() {
|
||||
notificationsList.clear();
|
||||
notifyDataSetChanged();
|
||||
|
||||
@@ -14,8 +14,10 @@ import android.accounts.AuthenticatorException;
|
||||
import android.accounts.OperationCanceledException;
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Activity;
|
||||
import android.content.ComponentCallbacks;
|
||||
import android.content.ContentValues;
|
||||
import android.content.res.ColorStateList;
|
||||
import android.content.res.Configuration;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.Drawable;
|
||||
@@ -198,6 +200,17 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
|
||||
// initialise thumbnails cache on background thread
|
||||
ThumbnailsCacheManager.initDiskCacheAsync();
|
||||
isRTL = DisplayUtils.isRTL();
|
||||
|
||||
activity.registerComponentCallbacks(new ComponentCallbacks() {
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
@Override
|
||||
public void onConfigurationChanged(@NonNull Configuration newConfig) {
|
||||
notifyDataSetChanged(); // force update of orientation-dependent layout (e.g. share button visibility)
|
||||
}
|
||||
@Override
|
||||
public void onLowMemory() {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public boolean isMultiSelect() {
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
package com.owncloud.android.ui.adapter
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.Color
|
||||
import android.os.AsyncTask
|
||||
import android.view.View
|
||||
@@ -261,6 +262,7 @@ class OCFileListDelegate(
|
||||
// shares
|
||||
val shouldHideShare = (
|
||||
hideItemOptions ||
|
||||
context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT ||
|
||||
!file.isFolder &&
|
||||
file.isEncrypted ||
|
||||
file.isEncrypted &&
|
||||
|
||||
@@ -90,6 +90,7 @@ public class TrashbinListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
|
||||
this.viewThemeUtils = viewThemeUtils;
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
public void setTrashbinFiles(List<TrashbinFile> trashbinFiles, boolean clear) {
|
||||
if (clear) {
|
||||
files.clear();
|
||||
@@ -206,6 +207,7 @@ public class TrashbinListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
public void removeAllFiles() {
|
||||
files.clear();
|
||||
notifyDataSetChanged();
|
||||
@@ -345,6 +347,7 @@ public class TrashbinListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
|
||||
asyncTasks.clear();
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
public void setSortOrder(FileSortOrder sortOrder) {
|
||||
preferences.setSortOrder(FileSortOrder.Type.trashBinView, sortOrder);
|
||||
files = sortOrder.sortTrashbinFiles(files);
|
||||
|
||||
@@ -44,6 +44,7 @@ import com.owncloud.android.datamodel.UploadsStorageManager.UploadStatus;
|
||||
import com.owncloud.android.db.OCUpload;
|
||||
import com.owncloud.android.db.OCUploadComparator;
|
||||
import com.owncloud.android.db.UploadResult;
|
||||
import com.owncloud.android.files.services.NameCollisionPolicy;
|
||||
import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
|
||||
import com.owncloud.android.lib.common.utils.Log_OC;
|
||||
import com.owncloud.android.operations.RefreshFolderOperation;
|
||||
@@ -81,11 +82,23 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
final Type type;
|
||||
final int titleRes;
|
||||
final UploadStatus status;
|
||||
final NameCollisionPolicy nameCollisionPolicy;
|
||||
|
||||
GroupConfig(Type type, int titleRes, UploadStatus status) {
|
||||
GroupConfig(Type type, int titleRes, UploadStatus status, NameCollisionPolicy nameCollisionPolicy) {
|
||||
this.type = type;
|
||||
this.titleRes = titleRes;
|
||||
this.status = status;
|
||||
this.nameCollisionPolicy = nameCollisionPolicy;
|
||||
}
|
||||
|
||||
public static List<GroupConfig> getConfigs() {
|
||||
return List.of(
|
||||
new GroupConfig(Type.CURRENT, R.string.uploads_view_group_current_uploads, UploadStatus.UPLOAD_IN_PROGRESS, null),
|
||||
new GroupConfig(Type.FAILED, R.string.uploads_view_group_failed_uploads, UploadStatus.UPLOAD_FAILED, null),
|
||||
new GroupConfig(Type.CANCELLED, R.string.uploads_view_group_manually_cancelled_uploads, UploadStatus.UPLOAD_CANCELLED, null),
|
||||
new GroupConfig(Type.FINISHED, R.string.uploads_view_group_finished_uploads, UploadStatus.UPLOAD_SUCCEEDED, NameCollisionPolicy.ASK_USER), // ASK_USER default value
|
||||
new GroupConfig(Type.SKIPPED, R.string.uploads_view_upload_status_skip, UploadStatus.UPLOAD_SUCCEEDED, NameCollisionPolicy.SKIP)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,6 +119,8 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
new LinkedBlockingQueue<>(1),
|
||||
new UploadGroupLoadPolicy());
|
||||
|
||||
private final List<GroupConfig> uploadGroupConfigs = GroupConfig.getConfigs();
|
||||
|
||||
private final FileUploadHelper uploadHelper = FileUploadHelper.Companion.instance();
|
||||
|
||||
public UploadListAdapter(final FileActivity fileActivity,
|
||||
@@ -127,7 +142,7 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
this.clock = clock;
|
||||
this.viewThemeUtils = viewThemeUtils;
|
||||
|
||||
uploadGroups = new UploadGroup[4];
|
||||
uploadGroups = new UploadGroup[uploadGroupConfigs.size()];
|
||||
|
||||
shouldShowHeadersForEmptySections(false);
|
||||
initUploadGroups();
|
||||
@@ -142,15 +157,8 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
|
||||
final var accountName = optionalUser.get().getAccountName();
|
||||
|
||||
var groups = List.of(
|
||||
new GroupConfig(Type.CURRENT, R.string.uploads_view_group_current_uploads, UploadStatus.UPLOAD_IN_PROGRESS),
|
||||
new GroupConfig(Type.FAILED, R.string.uploads_view_group_failed_uploads, UploadStatus.UPLOAD_FAILED),
|
||||
new GroupConfig(Type.CANCELLED, R.string.uploads_view_group_manually_cancelled_uploads, UploadStatus.UPLOAD_CANCELLED),
|
||||
new GroupConfig(Type.FINISHED, R.string.uploads_view_group_finished_uploads, UploadStatus.UPLOAD_SUCCEEDED)
|
||||
);
|
||||
|
||||
for (int i = 0; i < groups.size(); i++) {
|
||||
var config = groups.get(i);
|
||||
for (int i = 0; i < uploadGroupConfigs.size(); i++) {
|
||||
final var config = uploadGroupConfigs.get(i);
|
||||
uploadGroups[i] = createUploadGroup(config, accountName);
|
||||
}
|
||||
}
|
||||
@@ -159,7 +167,7 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
return new UploadGroup(config.type, parentActivity.getString(config.titleRes)) {
|
||||
@Override
|
||||
public void refresh(LoadCompleteListener listener) {
|
||||
uploadHelper.getUploadsByStatus(accountName, config.status, ocUploads -> {
|
||||
uploadHelper.getUploadsByStatus(accountName, config.status, config.nameCollisionPolicy,ocUploads -> {
|
||||
fixAndSortItems(ocUploads);
|
||||
listener.onComplete();
|
||||
return Unit.INSTANCE;
|
||||
@@ -196,6 +204,13 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
R.drawable.ic_expand_more);
|
||||
});
|
||||
|
||||
headerViewHolder.binding.uploadListStateLayout.setOnClickListener(v -> {{
|
||||
toggleSectionExpanded(section);
|
||||
headerViewHolder.binding.uploadListState.setImageResource(isSectionExpanded(section) ?
|
||||
R.drawable.ic_expand_less :
|
||||
R.drawable.ic_expand_more);
|
||||
}});
|
||||
|
||||
switch (group.type) {
|
||||
case CURRENT, FINISHED -> headerViewHolder.binding.uploadListAction.setImageResource(R.drawable.ic_close);
|
||||
case CANCELLED, FAILED ->
|
||||
@@ -208,7 +223,7 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
|
||||
headerViewHolder.binding.uploadListAction.setOnClickListener(v -> {
|
||||
switch (group.type) {
|
||||
case CURRENT -> new Thread(() -> {
|
||||
case CURRENT -> {
|
||||
OCUpload ocUpload = group.getItem(0);
|
||||
if (ocUpload == null) {
|
||||
return;
|
||||
@@ -224,16 +239,15 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
FileUploadWorker.Companion.cancelCurrentUpload(upload.getRemotePath(), accountName, () -> Unit.INSTANCE);
|
||||
}
|
||||
loadUploadItemsFromDb();
|
||||
}).start();
|
||||
}
|
||||
case FINISHED -> {
|
||||
uploadsStorageManager.clearSuccessfulUploads();
|
||||
loadUploadItemsFromDb();
|
||||
}
|
||||
case FAILED -> {
|
||||
showFailedPopupMenu(headerViewHolder);
|
||||
}
|
||||
case CANCELLED -> {
|
||||
showCancelledPopupMenu(headerViewHolder);
|
||||
case FAILED -> showFailedPopupMenu(headerViewHolder);
|
||||
case CANCELLED -> showCancelledPopupMenu(headerViewHolder);
|
||||
default -> {
|
||||
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -250,16 +264,12 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
clearTempEncryptedFolder();
|
||||
loadUploadItemsFromDb();
|
||||
} else if (itemId == R.id.action_upload_list_failed_retry) {
|
||||
|
||||
// FIXME For e2e resume is not working
|
||||
new Thread(() -> {
|
||||
uploadHelper.retryFailedUploads(
|
||||
uploadsStorageManager,
|
||||
connectivityService,
|
||||
accountManager,
|
||||
powerManagementService);
|
||||
loadUploadItemsFromDb();
|
||||
}).start();
|
||||
uploadHelper.retryFailedUploads(
|
||||
uploadsStorageManager,
|
||||
connectivityService,
|
||||
accountManager,
|
||||
powerManagementService);
|
||||
loadUploadItemsFromDb();
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -750,40 +760,48 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
*/
|
||||
private String getStatusText(OCUpload upload) {
|
||||
String status;
|
||||
switch (upload.getUploadStatus()) {
|
||||
var statusRes = parentActivity.getResources();
|
||||
var prefs = parentActivity.getAppPreferences();
|
||||
var uploadStatus = upload.getUploadStatus();
|
||||
|
||||
switch (uploadStatus) {
|
||||
case UPLOAD_IN_PROGRESS -> {
|
||||
status = parentActivity.getString(R.string.uploads_view_later_waiting_to_upload);
|
||||
if (uploadHelper.isUploadingNow(upload)) {
|
||||
// really uploading, bind the progress bar to listen for progress updates
|
||||
status = parentActivity.getString(R.string.uploader_upload_in_progress_ticker);
|
||||
}
|
||||
if (parentActivity.getAppPreferences().isGlobalUploadPaused()) {
|
||||
status = parentActivity.getString(R.string.upload_global_pause_title);
|
||||
}
|
||||
}
|
||||
case UPLOAD_SUCCEEDED -> {
|
||||
if (upload.getLastResult() == UploadResult.SAME_FILE_CONFLICT) {
|
||||
status = parentActivity.getString(R.string.uploads_view_upload_status_succeeded_same_file);
|
||||
} else if (upload.getLastResult() == UploadResult.FILE_NOT_FOUND) {
|
||||
status = getUploadFailedStatusText(upload.getLastResult());
|
||||
if (prefs.isGlobalUploadPaused()) {
|
||||
status = statusRes.getString(R.string.upload_global_pause_title);
|
||||
} else if (uploadHelper.isUploadingNow(upload)) {
|
||||
status = statusRes.getString(R.string.uploader_upload_in_progress_ticker);
|
||||
} else {
|
||||
status = parentActivity.getString(R.string.uploads_view_upload_status_succeeded);
|
||||
status = statusRes.getString(R.string.uploads_view_later_waiting_to_upload);
|
||||
}
|
||||
}
|
||||
case UPLOAD_FAILED -> {
|
||||
status = getUploadFailedStatusText(upload.getLastResult());
|
||||
}
|
||||
case UPLOAD_CANCELLED -> {
|
||||
status = parentActivity.getString(R.string.upload_manually_cancelled);
|
||||
}
|
||||
|
||||
default -> {
|
||||
status = "Uncontrolled status: " + upload.getUploadStatus();
|
||||
case UPLOAD_SUCCEEDED -> {
|
||||
UploadResult result = upload.getLastResult();
|
||||
if (result == UploadResult.SAME_FILE_CONFLICT) {
|
||||
status = statusRes.getString(R.string.uploads_view_upload_status_succeeded_same_file);
|
||||
} else if (result == UploadResult.FILE_NOT_FOUND) {
|
||||
status = getUploadFailedStatusText(result);
|
||||
} else if (upload.getNameCollisionPolicy() == NameCollisionPolicy.SKIP) {
|
||||
status = statusRes.getString(R.string.uploads_view_upload_status_skip_reason);
|
||||
} else {
|
||||
status = statusRes.getString(R.string.uploads_view_upload_status_succeeded);
|
||||
}
|
||||
}
|
||||
|
||||
case UPLOAD_FAILED ->
|
||||
status = getUploadFailedStatusText(upload.getLastResult());
|
||||
|
||||
case UPLOAD_CANCELLED ->
|
||||
status = statusRes.getString(R.string.upload_manually_cancelled);
|
||||
|
||||
default ->
|
||||
status = "Uncontrolled status: " + uploadStatus;
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
|
||||
@NonNull
|
||||
private String getUploadFailedStatusText(UploadResult result) {
|
||||
return switch (result) {
|
||||
@@ -941,7 +959,7 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
}
|
||||
|
||||
enum Type {
|
||||
CURRENT, FINISHED, FAILED, CANCELLED
|
||||
CURRENT, FINISHED, FAILED, CANCELLED, SKIPPED
|
||||
}
|
||||
|
||||
abstract class UploadGroup implements Refresh, Apply {
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
*/
|
||||
package com.owncloud.android.ui.adapter;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.drawable.Drawable;
|
||||
@@ -162,6 +163,7 @@ public class UserListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
|
||||
*
|
||||
* @param items The item list to be added
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
public void addAll(List<UserListItem> items){
|
||||
if(values == null){
|
||||
values = new ArrayList<>();
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
package com.owncloud.android.ui.asynctasks;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.os.AsyncTask;
|
||||
|
||||
import com.nextcloud.client.account.User;
|
||||
@@ -30,7 +31,7 @@ public class FetchRemoteFileTask extends AsyncTask<Void, Void, String> {
|
||||
private final User user;
|
||||
private final String fileId;
|
||||
private final FileDataStorageManager storageManager;
|
||||
private final FileDisplayActivity fileDisplayActivity;
|
||||
@SuppressLint("StaticFieldLeak") private final FileDisplayActivity fileDisplayActivity;
|
||||
private OCFile ocFile;
|
||||
|
||||
public FetchRemoteFileTask(User user,
|
||||
|
||||
+2
-1
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
package com.owncloud.android.ui.asynctasks;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.os.AsyncTask;
|
||||
|
||||
import com.nextcloud.common.NextcloudClient;
|
||||
@@ -32,7 +33,7 @@ public class NotificationExecuteActionTask extends AsyncTask<Action, Void, Boole
|
||||
private final NotificationListAdapter.NotificationViewHolder holder;
|
||||
private final NextcloudClient client;
|
||||
private final Notification notification;
|
||||
private final NotificationsActivity notificationsActivity;
|
||||
@SuppressLint("StaticFieldLeak") private final NotificationsActivity notificationsActivity;
|
||||
|
||||
public NotificationExecuteActionTask(NextcloudClient client,
|
||||
NotificationListAdapter.NotificationViewHolder holder,
|
||||
|
||||
+36
-6
@@ -542,29 +542,59 @@ class SyncedFolderPreferencesDialogFragment :
|
||||
}
|
||||
|
||||
/**
|
||||
* Get index for name collision selection dialog.
|
||||
* Converts a [NameCollisionPolicy] enum value into the corresponding
|
||||
* **UI dialog selection index** used in the dialog.
|
||||
*
|
||||
* @return 0 if ASK_USER, 1 if OVERWRITE, 2 if RENAME, 3 if SKIP, Otherwise: 0
|
||||
* ⚠️ **Important:**
|
||||
* These dialog indices are **not** the same as the integer values stored
|
||||
* in the database or defined in [NameCollisionPolicy].
|
||||
* This mapping is purely for UI selection purposes.
|
||||
*
|
||||
* | Policy | Dialog Index |
|
||||
* |---------------------|--------------|
|
||||
* | ASK_USER (default) | 0 |
|
||||
* | OVERWRITE | 1 |
|
||||
* | RENAME | 2 |
|
||||
* | SKIP | 3 |
|
||||
*
|
||||
* @param nameCollisionPolicy The collision handling policy.
|
||||
* @return The index to preselect in the UI dialog for the given policy.
|
||||
*/
|
||||
@Suppress("MagicNumber")
|
||||
private fun getSelectionIndexForNameCollisionPolicy(nameCollisionPolicy: NameCollisionPolicy): Int =
|
||||
when (nameCollisionPolicy) {
|
||||
NameCollisionPolicy.OVERWRITE -> 1
|
||||
NameCollisionPolicy.RENAME -> 2
|
||||
NameCollisionPolicy.CANCEL -> 3
|
||||
NameCollisionPolicy.SKIP -> 3
|
||||
NameCollisionPolicy.ASK_USER -> 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Get index for name collision selection dialog. Inverse of getSelectionIndexForNameCollisionPolicy.
|
||||
* Converts a **UI dialog selection index** from the dialog
|
||||
* back into a [NameCollisionPolicy] enum value.
|
||||
*
|
||||
* @return ASK_USER if 0, OVERWRITE if 1, RENAME if 2, SKIP if 3. Otherwise: ASK_USER
|
||||
* ⚠️ **Important:**
|
||||
* These indices are defined only for the dialog and are **not** the same as
|
||||
* the values used in the database or internal enum ordinals.
|
||||
* Always use this function to translate the dialog result safely.
|
||||
*
|
||||
* | Dialog Index | Policy |
|
||||
* |---------------|--------------------|
|
||||
* | 0 | ASK_USER (default) |
|
||||
* | 1 | OVERWRITE |
|
||||
* | 2 | RENAME |
|
||||
* | 3 | SKIP |
|
||||
*
|
||||
* Any unexpected index value will default to [NameCollisionPolicy.ASK_USER].
|
||||
*
|
||||
* @param index The selected index from the dialog.
|
||||
* @return The corresponding [NameCollisionPolicy] value.
|
||||
*/
|
||||
@Suppress("MagicNumber")
|
||||
private fun getNameCollisionPolicyForSelectionIndex(index: Int): NameCollisionPolicy = when (index) {
|
||||
1 -> NameCollisionPolicy.OVERWRITE
|
||||
2 -> NameCollisionPolicy.RENAME
|
||||
3 -> NameCollisionPolicy.CANCEL
|
||||
3 -> NameCollisionPolicy.SKIP
|
||||
0 -> NameCollisionPolicy.ASK_USER
|
||||
else -> NameCollisionPolicy.ASK_USER
|
||||
}
|
||||
|
||||
@@ -704,6 +704,14 @@ open class ExtendedListFragment :
|
||||
true
|
||||
)
|
||||
}
|
||||
EmptyListState.ERROR -> {
|
||||
setMessageForEmptyList(
|
||||
R.string.file_list_error_headline,
|
||||
R.string.file_list_error_description,
|
||||
R.drawable.ic_no_internet,
|
||||
false
|
||||
)
|
||||
}
|
||||
else -> {
|
||||
setMessageForEmptyList(
|
||||
R.string.file_list_empty_headline,
|
||||
|
||||
@@ -295,10 +295,8 @@ public class GalleryFragment extends OCFileListFragment implements GalleryFragme
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
|
||||
// Handle item selection
|
||||
if (item.getItemId() == R.id.action_three_dot_icon && !this.isPhotoSearchQueryRunning()
|
||||
&& galleryFragmentBottomSheetDialog != null) {
|
||||
if (item.getItemId() == R.id.action_three_dot_icon && galleryFragmentBottomSheetDialog != null) {
|
||||
showBottomSheet();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -225,7 +225,7 @@ public class OCFileListFragment extends ExtendedListFragment implements
|
||||
protected SearchType currentSearchType;
|
||||
protected boolean searchFragment;
|
||||
protected SearchEvent searchEvent;
|
||||
protected AsyncTask<Void, Void, Boolean> remoteOperationAsyncTask;
|
||||
private OCFileListSearchTask searchTask;
|
||||
protected String mLimitToMimeType;
|
||||
private FloatingActionButton mFabMain;
|
||||
public static boolean isMultipleFileSelectedForCopyOrMove = false;
|
||||
@@ -350,8 +350,8 @@ public class OCFileListFragment extends ExtendedListFragment implements
|
||||
setOnRefreshListener(null);
|
||||
mContainerActivity = null;
|
||||
|
||||
if (remoteOperationAsyncTask != null) {
|
||||
remoteOperationAsyncTask.cancel(true);
|
||||
if (searchTask != null) {
|
||||
searchTask.cancel();
|
||||
}
|
||||
super.onDetach();
|
||||
}
|
||||
@@ -1907,10 +1907,10 @@ public class OCFileListFragment extends ExtendedListFragment implements
|
||||
return;
|
||||
}
|
||||
|
||||
// avoid calling api multiple times if async task is already executing
|
||||
if (remoteOperationAsyncTask != null && remoteOperationAsyncTask.getStatus() != AsyncTask.Status.FINISHED) {
|
||||
// avoid calling api multiple times if task is already executing
|
||||
if (searchTask != null && !searchTask.isFinished()) {
|
||||
if (searchEvent != null) {
|
||||
Log_OC.d(TAG, "OCFileListSearchAsyncTask already running skipping new api call for search event: " + searchEvent.getSearchType());
|
||||
Log_OC.d(TAG, "OCFileListSearchTask already running skipping new api call for search event: " + searchEvent.getSearchType());
|
||||
}
|
||||
|
||||
return;
|
||||
@@ -1941,11 +1941,10 @@ public class OCFileListFragment extends ExtendedListFragment implements
|
||||
|
||||
final User currentUser = accountManager.getUser();
|
||||
|
||||
final RemoteOperation remoteOperation = getSearchRemoteOperation(currentUser, event);
|
||||
final var remoteOperation = getSearchRemoteOperation(currentUser, event);
|
||||
|
||||
remoteOperationAsyncTask = new OCFileListSearchAsyncTask(mContainerActivity, this, remoteOperation, currentUser, event);
|
||||
|
||||
remoteOperationAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
|
||||
searchTask = new OCFileListSearchTask(mContainerActivity, this, remoteOperation, currentUser, event, SharedListFragment.TASK_TIMEOUT);
|
||||
searchTask.execute();
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2022 Álvaro Brey <alvaro@alvarobrey.com>
|
||||
* SPDX-FileCopyrightText: 2022 Nextcloud GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.fragment
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.os.AsyncTask
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import com.nextcloud.client.account.User
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperation
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult
|
||||
import com.owncloud.android.ui.events.SearchEvent
|
||||
import java.lang.ref.WeakReference
|
||||
|
||||
class OCFileListSearchAsyncTask(
|
||||
containerActivity: FileFragment.ContainerActivity,
|
||||
fragment: OCFileListFragment,
|
||||
private val remoteOperation: RemoteOperation<List<Any>>,
|
||||
private val currentUser: User,
|
||||
private val event: SearchEvent
|
||||
) : AsyncTask<Void, Void, Boolean>() {
|
||||
private val activityReference: WeakReference<FileFragment.ContainerActivity> = WeakReference(containerActivity)
|
||||
private val fragmentReference: WeakReference<OCFileListFragment> = WeakReference(fragment)
|
||||
|
||||
private val fileDataStorageManager: FileDataStorageManager?
|
||||
get() = activityReference.get()?.storageManager
|
||||
|
||||
private fun RemoteOperationResult<out Any>.hasSuccessfulResult() = this.isSuccess && this.resultData != null
|
||||
|
||||
override fun onPreExecute() {
|
||||
fragmentReference.get()?.let { fragment ->
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
fragment.setEmptyListMessage(EmptyListState.LOADING)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun doInBackground(vararg voids: Void): Boolean {
|
||||
val fragment = fragmentReference.get()
|
||||
if (fragment?.context == null || isCancelled) {
|
||||
return java.lang.Boolean.FALSE
|
||||
}
|
||||
|
||||
fragment.setTitle()
|
||||
lateinit var remoteOperationResult: RemoteOperationResult<List<Any>>
|
||||
try {
|
||||
remoteOperationResult = remoteOperation.execute(currentUser, fragment.context)
|
||||
} catch (_: UnsupportedOperationException) {
|
||||
remoteOperationResult = remoteOperation.executeNextcloudClient(currentUser, fragment.requireContext())
|
||||
}
|
||||
|
||||
if (remoteOperationResult.hasSuccessfulResult() && !isCancelled && fragment.searchFragment) {
|
||||
fragment.searchEvent = event
|
||||
if (remoteOperationResult.resultData.isNullOrEmpty()) {
|
||||
fragment.setEmptyView(event)
|
||||
} else {
|
||||
fragment.adapter.setData(
|
||||
remoteOperationResult.resultData,
|
||||
fragment.currentSearchType,
|
||||
fileDataStorageManager,
|
||||
fragment.mFile,
|
||||
true
|
||||
)
|
||||
}
|
||||
}
|
||||
return remoteOperationResult.isSuccess
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
override fun onPostExecute(bool: Boolean) {
|
||||
fragmentReference.get()?.let { fragment ->
|
||||
if (!isCancelled) {
|
||||
fragment.adapter.notifyDataSetChanged()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
|
||||
* SPDX-FileCopyrightText: 2022 Álvaro Brey <alvaro@alvarobrey.com>
|
||||
* SPDX-FileCopyrightText: 2022 Nextcloud GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.owncloud.android.ui.fragment
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.nextcloud.client.account.User
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperation
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult
|
||||
import com.owncloud.android.ui.events.SearchEvent
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import java.lang.ref.WeakReference
|
||||
|
||||
@Suppress("LongParameterList")
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
class OCFileListSearchTask(
|
||||
containerActivity: FileFragment.ContainerActivity,
|
||||
fragment: OCFileListFragment,
|
||||
private val remoteOperation: RemoteOperation<List<Any>>,
|
||||
private val currentUser: User,
|
||||
private val event: SearchEvent,
|
||||
private val taskTimeout: Long
|
||||
) {
|
||||
private val activityReference: WeakReference<FileFragment.ContainerActivity> = WeakReference(containerActivity)
|
||||
private val fragmentReference: WeakReference<OCFileListFragment> = WeakReference(fragment)
|
||||
|
||||
private val fileDataStorageManager: FileDataStorageManager?
|
||||
get() = activityReference.get()?.storageManager
|
||||
|
||||
private fun RemoteOperationResult<out Any>.hasSuccessfulResult() = this.isSuccess && this.resultData != null
|
||||
|
||||
private var job: Job? = null
|
||||
|
||||
@Suppress("TooGenericExceptionCaught", "DEPRECATION")
|
||||
fun execute() {
|
||||
fragmentReference.get()?.let { fragment ->
|
||||
job = fragment.lifecycleScope.launch(Dispatchers.IO) {
|
||||
val result = withTimeoutOrNull(taskTimeout) {
|
||||
if (!isActive) {
|
||||
false
|
||||
} else {
|
||||
fragment.setTitle()
|
||||
lateinit var remoteOperationResult: RemoteOperationResult<List<Any>>
|
||||
try {
|
||||
remoteOperationResult = remoteOperation.execute(currentUser, fragment.requireContext())
|
||||
} catch (_: Exception) {
|
||||
remoteOperationResult =
|
||||
remoteOperation.executeNextcloudClient(currentUser, fragment.requireContext())
|
||||
}
|
||||
|
||||
if (remoteOperationResult.hasSuccessfulResult() && isActive && fragment.searchFragment) {
|
||||
fragment.searchEvent = event
|
||||
if (remoteOperationResult.resultData.isNullOrEmpty()) {
|
||||
fragment.setEmptyView(event)
|
||||
} else {
|
||||
fragment.adapter.setData(
|
||||
remoteOperationResult.resultData,
|
||||
fragment.currentSearchType,
|
||||
fileDataStorageManager,
|
||||
fragment.mFile,
|
||||
true
|
||||
)
|
||||
}
|
||||
}
|
||||
remoteOperationResult.isSuccess
|
||||
}
|
||||
} ?: false
|
||||
|
||||
withContext(Dispatchers.Main) {
|
||||
if (result && isActive) {
|
||||
fragment.adapter.notifyDataSetChanged()
|
||||
} else {
|
||||
fragment.setEmptyListMessage(EmptyListState.ERROR)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun cancel() = job?.cancel(null)
|
||||
|
||||
fun isFinished(): Boolean = job?.isCompleted == true
|
||||
}
|
||||
@@ -32,5 +32,6 @@ enum class EmptyListState : Parcelable {
|
||||
ADD_FOLDER,
|
||||
ONLY_ON_DEVICE,
|
||||
LOCAL_FILE_LIST_EMPTY_FILE,
|
||||
LOCAL_FILE_LIST_EMPTY_FOLDER
|
||||
LOCAL_FILE_LIST_EMPTY_FOLDER,
|
||||
ERROR
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import androidx.lifecycle.lifecycleScope
|
||||
import com.nextcloud.client.account.User
|
||||
import com.nextcloud.client.di.Injectable
|
||||
import com.nextcloud.client.logger.Logger
|
||||
import com.nextcloud.common.SessionTimeOut
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperation
|
||||
@@ -68,7 +69,7 @@ class SharedListFragment :
|
||||
}
|
||||
|
||||
override fun getSearchRemoteOperation(currentUser: User?, event: SearchEvent?): RemoteOperation<*> =
|
||||
GetSharesRemoteOperation()
|
||||
GetSharesRemoteOperation(false, SessionTimeOut(TASK_TIMEOUT, TASK_TIMEOUT))
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private suspend fun fetchFileData(partialFile: OCFile): OCFile? = withContext(Dispatchers.IO) {
|
||||
@@ -185,5 +186,6 @@ class SharedListFragment :
|
||||
|
||||
companion object {
|
||||
private val SHARED_TAG = SharedListFragment::class.java.simpleName
|
||||
const val TASK_TIMEOUT = 120_000
|
||||
}
|
||||
}
|
||||
@@ -177,7 +177,7 @@ class PreviewImageActivity :
|
||||
)
|
||||
} else {
|
||||
// get parent from path
|
||||
var parentFolder = storageManager.getFileById(file.parentId)
|
||||
var parentFolder = file?.let { storageManager.getFileById(it.parentId) }
|
||||
|
||||
if (parentFolder == null) {
|
||||
// should not be necessary
|
||||
@@ -197,7 +197,13 @@ class PreviewImageActivity :
|
||||
|
||||
viewPager = findViewById(R.id.fragmentPager)
|
||||
|
||||
var position = if (savedPosition != null) savedPosition else previewImagePagerAdapter?.getFilePosition(file)
|
||||
var position = if (savedPosition !=
|
||||
null
|
||||
) {
|
||||
savedPosition
|
||||
} else {
|
||||
file?.let { previewImagePagerAdapter?.getFilePosition(it) }
|
||||
}
|
||||
position = position?.toDouble()?.let { max(it, 0.0).toInt() }
|
||||
|
||||
viewPager?.adapter = previewImagePagerAdapter
|
||||
@@ -210,7 +216,7 @@ class PreviewImageActivity :
|
||||
viewPager?.setCurrentItem(position, false)
|
||||
}
|
||||
|
||||
if (position == 0 && !file.isDown) {
|
||||
if (position == 0 && file?.isDown == false) {
|
||||
// this is necessary because mViewPager.setCurrentItem(0) just after setting the
|
||||
// adapter does not result in a call to #onPageSelected(0)
|
||||
screenState = PreviewImageActivityState.WaitingForBinder
|
||||
@@ -275,7 +281,7 @@ class PreviewImageActivity :
|
||||
if (file != null) {
|
||||
// / Refresh the activity according to the Account and OCFile set
|
||||
setFile(file) // reset after getting it fresh from storageManager
|
||||
updateActionBarTitle(getFile().fileName)
|
||||
updateActionBarTitle(getFile()?.fileName)
|
||||
// if (!stateWasRecovered) {
|
||||
initViewPager(optionalUser.get())
|
||||
|
||||
@@ -353,8 +359,10 @@ class PreviewImageActivity :
|
||||
savedPosition?.let { position ->
|
||||
|
||||
previewImagePagerAdapter?.run {
|
||||
updateFile(position, file)
|
||||
notifyItemChanged(position)
|
||||
file?.let {
|
||||
updateFile(position, it)
|
||||
notifyItemChanged(position)
|
||||
}
|
||||
}
|
||||
|
||||
if (user.isPresent) {
|
||||
@@ -378,7 +386,9 @@ class PreviewImageActivity :
|
||||
dismissLoadingDialog()
|
||||
screenState = PreviewImageActivityState.Idle
|
||||
file = downloadedFile
|
||||
startEditImageActivity(file)
|
||||
file?.let {
|
||||
startEditImageActivity(it)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
|
||||
@@ -384,18 +384,19 @@ class PreviewMediaActivity :
|
||||
|
||||
@Suppress("TooGenericExceptionCaught")
|
||||
private fun playAudio() {
|
||||
if (file.isDown) {
|
||||
prepareAudioPlayer(file.storageUri)
|
||||
if (file?.isDown == true) {
|
||||
prepareAudioPlayer(file?.storageUri)
|
||||
} else {
|
||||
try {
|
||||
LoadStreamUrl(this, user, clientFactory).execute(file.localId)
|
||||
LoadStreamUrl(this, user, clientFactory).execute(file?.localId)
|
||||
} catch (e: Exception) {
|
||||
Log_OC.e(TAG, "Loading stream url for Audio not possible: $e")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun prepareAudioPlayer(uri: Uri) {
|
||||
private fun prepareAudioPlayer(uri: Uri?) {
|
||||
uri ?: return
|
||||
audioMediaController?.let { audioPlayer ->
|
||||
audioPlayer.addListener(object : Player.Listener {
|
||||
|
||||
@@ -434,7 +435,7 @@ class PreviewMediaActivity :
|
||||
})
|
||||
val mediaItem = MediaItem.Builder()
|
||||
.setUri(uri)
|
||||
.setMediaMetadata(MediaMetadata.Builder().setTitle(file.fileName).build())
|
||||
.setMediaMetadata(MediaMetadata.Builder().setTitle(file?.fileName).build())
|
||||
.build()
|
||||
audioPlayer.setMediaItem(mediaItem)
|
||||
audioPlayer.playWhenReady = autoplay
|
||||
@@ -563,8 +564,8 @@ class PreviewMediaActivity :
|
||||
|
||||
R.id.action_remove_file -> {
|
||||
videoPlayer?.pause()
|
||||
val dialog = RemoveFilesDialogFragment.newInstance(file)
|
||||
dialog.show(supportFragmentManager, ConfirmationDialogFragment.FTAG_CONFIRMATION)
|
||||
val dialog = file?.let { RemoveFilesDialogFragment.newInstance(it) }
|
||||
dialog?.show(supportFragmentManager, ConfirmationDialogFragment.FTAG_CONFIRMATION)
|
||||
}
|
||||
|
||||
R.id.action_see_details -> {
|
||||
@@ -572,7 +573,7 @@ class PreviewMediaActivity :
|
||||
}
|
||||
|
||||
R.id.action_sync_file -> {
|
||||
showSyncLoadingDialog(file.isFolder)
|
||||
showSyncLoadingDialog(file?.isFolder == true)
|
||||
fileOperationsHelper.syncFile(file)
|
||||
}
|
||||
|
||||
@@ -586,7 +587,7 @@ class PreviewMediaActivity :
|
||||
|
||||
R.id.action_export_file -> {
|
||||
val list = ArrayList<OCFile>()
|
||||
list.add(file)
|
||||
file?.let { list.add(it) }
|
||||
fileOperationsHelper.exportFiles(
|
||||
list,
|
||||
this,
|
||||
@@ -673,18 +674,19 @@ class PreviewMediaActivity :
|
||||
private fun playVideo() {
|
||||
setupVideoView()
|
||||
|
||||
if (file.isDown) {
|
||||
prepareVideoPlayer(file.storageUri)
|
||||
if (file?.isDown == true) {
|
||||
prepareVideoPlayer(file?.storageUri)
|
||||
} else {
|
||||
try {
|
||||
LoadStreamUrl(this, user, clientFactory).execute(file.localId)
|
||||
LoadStreamUrl(this, user, clientFactory).execute(file?.localId)
|
||||
} catch (e: Exception) {
|
||||
Log_OC.e(TAG, "Loading stream url for Video not possible: $e")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun prepareVideoPlayer(uri: Uri) {
|
||||
private fun prepareVideoPlayer(uri: Uri?) {
|
||||
uri ?: return
|
||||
binding.progress.visibility = View.GONE
|
||||
val videoMediaItem = MediaItem.fromUri(uri)
|
||||
videoPlayer?.run {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
package com.owncloud.android.ui.preview;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
@@ -146,6 +147,7 @@ public class PreviewTextFileFragment extends PreviewTextFragment {
|
||||
/**
|
||||
* Reads the file to preview and shows its contents. Too critical to be anonymous.
|
||||
*/
|
||||
@SuppressLint("StaticFieldLeak")
|
||||
private class TextLoadAsyncTask extends AsyncTask<Object, Void, StringWriter> {
|
||||
private static final int PARAMS_LENGTH = 1;
|
||||
private final WeakReference<TextView> textViewReference;
|
||||
|
||||
@@ -15,7 +15,6 @@ import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.graphics.BitmapFactory.Options;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.ImageDecoder;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.PorterDuff;
|
||||
import android.graphics.PorterDuffColorFilter;
|
||||
@@ -24,10 +23,9 @@ import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.drawable.BitmapDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Build;
|
||||
import android.text.TextUtils;
|
||||
import android.widget.ImageView;
|
||||
|
||||
import com.nextcloud.utils.BitmapExtensionsKt;
|
||||
import com.owncloud.android.MainApp;
|
||||
import com.owncloud.android.R;
|
||||
import com.owncloud.android.lib.common.utils.Log_OC;
|
||||
@@ -35,8 +33,6 @@ import com.owncloud.android.lib.resources.users.Status;
|
||||
import com.owncloud.android.lib.resources.users.StatusType;
|
||||
import com.owncloud.android.ui.StatusDrawable;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
@@ -44,12 +40,13 @@ import java.util.Locale;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.RequiresApi;
|
||||
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
|
||||
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
|
||||
import androidx.exifinterface.media.ExifInterface;
|
||||
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
|
||||
|
||||
import static com.nextcloud.utils.extensions.ThumbnailsCacheManagerExtensionsKt.getExifOrientation;
|
||||
|
||||
/**
|
||||
* Utility class with methods for decoding Bitmaps.
|
||||
*/
|
||||
@@ -76,23 +73,6 @@ public final class BitmapUtils {
|
||||
return resultBitmap;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@RequiresApi(Build.VERSION_CODES.P)
|
||||
private static Bitmap decodeSampledBitmapViaImageDecoder(@NonNull File file, int reqWidth, int reqHeight) {
|
||||
try {
|
||||
Log_OC.i(TAG, "Decoding Bitmap via ImageDecoder");
|
||||
|
||||
final var imageDecoderSource = ImageDecoder.createSource(file);
|
||||
|
||||
return ImageDecoder.decodeBitmap(imageDecoderSource, (decoder, info, source1) -> decoder.setTargetSize(reqWidth, reqHeight)
|
||||
);
|
||||
|
||||
} catch (IOException exception) {
|
||||
Log_OC.w(TAG, "Decoding Bitmap via ImageDecoder failed, BitmapFactory.decodeFile will be used");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes a bitmap from a file containing it minimizing the memory use, known that the bitmap will be drawn in a
|
||||
* surface of reqWidth x reqHeight
|
||||
@@ -104,41 +84,7 @@ public final class BitmapUtils {
|
||||
*/
|
||||
@Nullable
|
||||
public static Bitmap decodeSampledBitmapFromFile(String srcPath, int reqWidth, int reqHeight) {
|
||||
if (TextUtils.isEmpty(srcPath)) {
|
||||
Log_OC.e(TAG, "srcPath is null or empty");
|
||||
return null;
|
||||
}
|
||||
|
||||
final var file = new File(srcPath);
|
||||
if (!file.exists()) {
|
||||
Log_OC.e(TAG, "File does not exists, returning null");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
final var result = decodeSampledBitmapViaImageDecoder(file, reqWidth, reqHeight);
|
||||
if (result != null) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
Log_OC.i(TAG, "Decoding Bitmap via BitmapFactory.decodeFile");
|
||||
|
||||
// set desired options that will affect the size of the bitmap
|
||||
final Options options = new Options();
|
||||
|
||||
// make a false load of the bitmap to get its dimensions
|
||||
options.inJustDecodeBounds = true;
|
||||
|
||||
// FIXME after auto-rename can't generate thumbnail from localPath
|
||||
BitmapFactory.decodeFile(srcPath, options);
|
||||
|
||||
// calculate factor to subsample the bitmap
|
||||
options.inSampleSize = calculateSampleFactor(options, reqWidth, reqHeight);
|
||||
|
||||
// decode bitmap with inSampleSize set
|
||||
options.inJustDecodeBounds = false;
|
||||
return BitmapFactory.decodeFile(srcPath, options);
|
||||
return BitmapExtensionsKt.decodeSampledBitmapFromFile(srcPath, reqWidth, reqHeight);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -152,15 +98,6 @@ public final class BitmapUtils {
|
||||
var originalWidth = bitmapResolution[0];
|
||||
var originalHeight = bitmapResolution[1];
|
||||
|
||||
// Detect Orientation and swap height/width if the image is to be rotated
|
||||
var shouldRotate = detectRotateImage(storagePath);
|
||||
if (shouldRotate) {
|
||||
// Swap the width and height
|
||||
var tempWidth = originalWidth;
|
||||
originalWidth = originalHeight;
|
||||
originalHeight = tempWidth;
|
||||
}
|
||||
|
||||
// Calculate the scaling factors based on screen dimensions
|
||||
var widthScaleFactor = (float) minWidth/ originalWidth;
|
||||
var heightScaleFactor = (float) minHeight / originalHeight;
|
||||
@@ -172,7 +109,14 @@ public final class BitmapUtils {
|
||||
var scaledWidth = (int) (originalWidth * scaleFactor);
|
||||
var scaledHeight = (int) (originalHeight * scaleFactor);
|
||||
|
||||
return decodeSampledBitmapFromFile(storagePath, scaledWidth, scaledHeight);
|
||||
var shouldRotate = detectRotateImage(storagePath);
|
||||
var result = decodeSampledBitmapFromFile(storagePath, scaledWidth, scaledHeight);
|
||||
if (shouldRotate) {
|
||||
int orientation = getExifOrientation(storagePath);
|
||||
return BitmapExtensionsKt.rotateBitmapViaExif(result, orientation);
|
||||
} else {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Calculates a proper value for options.inSampleSize in order to decode a Bitmap minimizing the memory overload and
|
||||
|
||||
@@ -79,6 +79,7 @@ import java.net.IDN;
|
||||
import java.nio.charset.Charset;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -828,7 +829,7 @@ public final class DisplayUtils {
|
||||
|
||||
private static void setThumbnailFirstTimeForFile(OCFile file, ImageView thumbnailView, FileDataStorageManager storageManager, List<ThumbnailsCacheManager.ThumbnailGenerationTask> asyncTasks, boolean gridView, LoaderImageView shimmerThumbnail, User user, AppPreferences preferences, Context context, ViewThemeUtils viewThemeUtils) {
|
||||
if (file.getRemoteId() != null) {
|
||||
generateNewThumbnail(file, thumbnailView, user, storageManager, asyncTasks, gridView, context, shimmerThumbnail, preferences, viewThemeUtils);
|
||||
generateNewThumbnail(file, thumbnailView, user, storageManager, new ArrayList<>(asyncTasks), gridView, context, shimmerThumbnail, preferences, viewThemeUtils);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -873,7 +874,7 @@ public final class DisplayUtils {
|
||||
private static void setThumbnailFromCache(OCFile file, ImageView thumbnailView, FileDataStorageManager storageManager, List<ThumbnailsCacheManager.ThumbnailGenerationTask> asyncTasks, boolean gridView, LoaderImageView shimmerThumbnail, User user, AppPreferences preferences, Context context, ViewThemeUtils viewThemeUtils) {
|
||||
final var thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(ThumbnailsCacheManager.PREFIX_THUMBNAIL + file.getRemoteId());
|
||||
if (thumbnail == null || file.isUpdateThumbnailNeeded()) {
|
||||
generateNewThumbnail(file, thumbnailView, user, storageManager, asyncTasks, gridView, context, shimmerThumbnail, preferences, viewThemeUtils);
|
||||
generateNewThumbnail(file, thumbnailView, user, storageManager, new ArrayList<>(asyncTasks), gridView, context, shimmerThumbnail, preferences, viewThemeUtils);
|
||||
setThumbnailBackgroundForPNGFileIfNeeded(file, context, thumbnailView);
|
||||
return;
|
||||
}
|
||||
@@ -901,7 +902,7 @@ public final class DisplayUtils {
|
||||
ImageView thumbnailView,
|
||||
User user,
|
||||
FileDataStorageManager storageManager,
|
||||
List<ThumbnailsCacheManager.ThumbnailGenerationTask> asyncTasks,
|
||||
ArrayList<ThumbnailsCacheManager.ThumbnailGenerationTask> asyncTasks,
|
||||
boolean gridView,
|
||||
Context context,
|
||||
LoaderImageView shimmerThumbnail,
|
||||
@@ -986,7 +987,7 @@ public final class DisplayUtils {
|
||||
new ThumbnailsCacheManager.ThumbnailGenerationTaskObject(file,
|
||||
file.getRemoteId()));
|
||||
thumbnailView.invalidate();
|
||||
} catch (IllegalArgumentException e) {
|
||||
} catch (Exception e) {
|
||||
Log_OC.d(TAG, "ThumbnailGenerationTask : " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
package com.owncloud.android.utils;
|
||||
|
||||
import android.Manifest;
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.res.Resources;
|
||||
@@ -37,7 +38,6 @@ import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
@@ -232,6 +232,7 @@ public final class FileStorageUtils {
|
||||
*
|
||||
* @return Optimistic number of available bytes (can be less)
|
||||
*/
|
||||
@SuppressLint("UsableSpace")
|
||||
public static long getUsableSpace() {
|
||||
File savePath = new File(MainApp.getStoragePath());
|
||||
return savePath.getUsableSpace();
|
||||
|
||||
@@ -19,8 +19,8 @@ import com.nextcloud.client.account.UserAccountManager;
|
||||
import com.nextcloud.client.device.PowerManagementService;
|
||||
import com.nextcloud.client.jobs.BackgroundJobManager;
|
||||
import com.nextcloud.client.jobs.ContentObserverWork;
|
||||
import com.nextcloud.client.jobs.autoUpload.AutoUploadHelper;
|
||||
import com.nextcloud.client.jobs.upload.FileUploadHelper;
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker;
|
||||
import com.nextcloud.client.network.ConnectivityService;
|
||||
import com.nextcloud.utils.extensions.UriExtensionsKt;
|
||||
import com.owncloud.android.MainApp;
|
||||
@@ -31,20 +31,7 @@ import com.owncloud.android.datamodel.SyncedFolderProvider;
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager;
|
||||
import com.owncloud.android.lib.common.utils.Log_OC;
|
||||
|
||||
import org.lukhnos.nnio.file.AccessDeniedException;
|
||||
import org.lukhnos.nnio.file.FileVisitResult;
|
||||
import org.lukhnos.nnio.file.FileVisitor;
|
||||
import org.lukhnos.nnio.file.Files;
|
||||
import org.lukhnos.nnio.file.Path;
|
||||
import org.lukhnos.nnio.file.Paths;
|
||||
import org.lukhnos.nnio.file.SimpleFileVisitor;
|
||||
import org.lukhnos.nnio.file.attribute.BasicFileAttributes;
|
||||
import org.lukhnos.nnio.file.impl.FileBasedPathImpl;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
|
||||
import static com.owncloud.android.datamodel.OCFile.PATH_SEPARATOR;
|
||||
|
||||
@@ -60,110 +47,7 @@ public final class FilesSyncHelper {
|
||||
// utility class -> private constructor
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy of {@link Files#walkFileTree(Path, FileVisitor)} that walks the file tree in random order.
|
||||
*
|
||||
* @see org.lukhnos.nnio.file.Files#walkFileTree(Path, FileVisitor)
|
||||
*/
|
||||
public static void walkFileTreeRandomly(Path start, FileVisitor<? super Path> visitor) throws IOException {
|
||||
File file = start.toFile();
|
||||
if (!file.canRead()) {
|
||||
Log_OC.d(TAG, "walkFileTreeRandomly, cant read the file: " + file.getAbsolutePath());
|
||||
visitor.visitFileFailed(start, new AccessDeniedException(file.toString()));
|
||||
} else {
|
||||
Log_OC.d(TAG, "walkFileTreeRandomly, reading file: " + file.getAbsolutePath());
|
||||
|
||||
if (Files.isDirectory(start)) {
|
||||
Log_OC.d(TAG, "walkFileTreeRandomly, file is directory: " + file.getAbsolutePath());
|
||||
|
||||
FileVisitResult preVisitDirectoryResult = visitor.preVisitDirectory(start, null);
|
||||
if (preVisitDirectoryResult == FileVisitResult.CONTINUE) {
|
||||
Log_OC.d(TAG, "walkFileTreeRandomly, preVisitDirectoryResult == FileVisitResult.CONTINUE");
|
||||
File[] children = start.toFile().listFiles();
|
||||
if (children != null) {
|
||||
Log_OC.d(TAG, "walkFileTreeRandomly, children exists");
|
||||
|
||||
Collections.shuffle(Arrays.asList(children));
|
||||
File[] var5 = children;
|
||||
int var6 = children.length;
|
||||
|
||||
for(int var7 = 0; var7 < var6; ++var7) {
|
||||
Log_OC.d(TAG, "walkFileTreeRandomly -- recursive call");
|
||||
File child = var5[var7];
|
||||
walkFileTreeRandomly(FileBasedPathImpl.get(child), visitor);
|
||||
}
|
||||
|
||||
visitor.postVisitDirectory(start, null);
|
||||
} else {
|
||||
Log_OC.w(TAG, "walkFileTreeRandomly, children is null");
|
||||
}
|
||||
} else {
|
||||
Log_OC.w(TAG, "walkFileTreeRandomly, preVisitDirectoryResult != FileVisitResult.CONTINUE");
|
||||
}
|
||||
} else {
|
||||
Log_OC.d(TAG, "walkFileTreeRandomly, file is not directory");
|
||||
visitor.visitFile(start, new BasicFileAttributes(file));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void insertCustomFolderIntoDB(Path path,
|
||||
SyncedFolder syncedFolder,
|
||||
FilesystemDataProvider filesystemDataProvider,
|
||||
long lastCheck) {
|
||||
Log_OC.d(TAG, "insertCustomFolderIntoDB called");
|
||||
final long enabledTimestampMs = syncedFolder.getEnabledTimestampMs();
|
||||
|
||||
try {
|
||||
walkFileTreeRandomly(path, new SimpleFileVisitor<>() {
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
|
||||
File file = path.toFile();
|
||||
if (syncedFolder.isExcludeHidden() && file.isHidden()) {
|
||||
Log_OC.w(TAG, "skipping files, exclude hidden file/folder: " + path);
|
||||
// exclude hidden file or folder
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
if (attrs.lastModifiedTime().toMillis() < lastCheck) {
|
||||
Log_OC.w(TAG, "skipping files that already checked: " + path);
|
||||
// skip files that were already checked
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
if (syncedFolder.isExisting() || attrs.lastModifiedTime().toMillis() >= enabledTimestampMs) {
|
||||
// storeOrUpdateFileValue takes a few ms
|
||||
// -> Rest of this file check takes not even 1 ms.
|
||||
filesystemDataProvider.storeOrUpdateFileValue(path.toAbsolutePath().toString(),
|
||||
attrs.lastModifiedTime().toMillis(),
|
||||
file.isDirectory(), syncedFolder);
|
||||
} else {
|
||||
Log_OC.w(TAG, "skipping files. SynchedFolder not exists or enabledTimestampMs not meeting condition" + path);
|
||||
}
|
||||
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
|
||||
if (syncedFolder.isExcludeHidden() && dir.compareTo(Paths.get(syncedFolder.getLocalPath())) != 0 && dir.toFile().isHidden()) {
|
||||
Log_OC.d(TAG, "skipping hidden path: " + dir.getFileName());
|
||||
return FileVisitResult.SKIP_SUBTREE;
|
||||
}
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult visitFileFailed(Path file, IOException exc) {
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
} catch (IOException e) {
|
||||
Log_OC.e(TAG, "Something went wrong while indexing files for auto upload: " + e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static void insertAllDBEntriesForSyncedFolder(SyncedFolder syncedFolder) {
|
||||
public static void insertAllDBEntriesForSyncedFolder(SyncedFolder syncedFolder, AutoUploadHelper helper) {
|
||||
Log_OC.d(TAG, "insertAllDBEntriesForSyncedFolder, called. ID: " + syncedFolder.getId());
|
||||
|
||||
final Context context = MainApp.getAppContext();
|
||||
@@ -197,8 +81,7 @@ public final class FilesSyncHelper {
|
||||
} else {
|
||||
Log_OC.d(TAG, "inserting other media types: " + mediaType.toString());
|
||||
FilesystemDataProvider filesystemDataProvider = new FilesystemDataProvider(contentResolver);
|
||||
Path path = Paths.get(syncedFolder.getLocalPath());
|
||||
FilesSyncHelper.insertCustomFolderIntoDB(path, syncedFolder, filesystemDataProvider, lastCheckTimestampMs);
|
||||
helper.insertCustomFolderIntoDB(syncedFolder, filesystemDataProvider);
|
||||
}
|
||||
|
||||
Log_OC.d(TAG,"File-sync finished full check for custom folder "+syncedFolder.getLocalPath()+" within "+(System.nanoTime() - startTime)+ "ns");
|
||||
@@ -338,11 +221,11 @@ public final class FilesSyncHelper {
|
||||
final ConnectivityService connectivityService,
|
||||
final PowerManagementService powerManagementService) {
|
||||
Log_OC.d(TAG, "restartUploadsIfNeeded, called");
|
||||
new Thread(() -> FileUploadHelper.Companion.instance().retryFailedUploads(
|
||||
FileUploadHelper.Companion.instance().retryFailedUploads(
|
||||
uploadsStorageManager,
|
||||
connectivityService,
|
||||
accountManager,
|
||||
powerManagementService)).start();
|
||||
powerManagementService);
|
||||
}
|
||||
|
||||
public static void scheduleFilesSyncForAllFoldersIfNeeded(Context context, SyncedFolderProvider syncedFolderProvider, BackgroundJobManager jobManager) {
|
||||
|
||||
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user