Compare commits

..
1 Commits
Author SHA1 Message Date
tobiasKaminsky 0c205f6215 verify that modification date is not tampered
Signed-off-by: tobiasKaminsky <[email protected]>
2020-07-20 12:10:20 +02:00
240 changed files with 3429 additions and 6591 deletions

No files matched your search

+2 -6
View File
@@ -56,8 +56,6 @@ steps:
services:
- name: server
image: nextcloudci/server:server-17 # also change in updateScreenshots.sh
environment:
EVAL: true
commands:
- BRANCH='stable18' /usr/local/bin/initnc.sh
- echo 127.0.0.1 server >> /etc/hosts
@@ -140,8 +138,6 @@ steps:
services:
- name: server
image: nextcloudci/server:server-17 # also change in updateScreenshots.sh
environment:
EVAL: true
commands:
- /usr/local/bin/initnc.sh
- echo 127.0.0.1 server >> /etc/hosts
@@ -192,7 +188,7 @@ steps:
- ./gradlew assembleGplayDebug
- scripts/wait_for_emulator.sh
- ./gradlew installGplayDebugAndroidTest
- scripts/runAllScreenshotCombinations "stable" false
- ./gradlew gplayDebugExecuteScreenshotTests -Pandroid.testInstrumentationRunnerArguments.annotation=com.owncloud.android.utils.ScreenshotTest && scripts/deleteOutdatedComments.sh "stable" "Screenshot" $DRONE_PULL_REQUEST $GIT_USERNAME $GIT_TOKEN || scripts/uploadReport.sh $LOG_USERNAME $LOG_PASSWORD $DRONE_BUILD_NUMBER "stable" "Screenshot" $DRONE_PULL_REQUEST $GIT_USERNAME $GIT_TOKEN
- name: notify
image: drillster/drone-email
settings:
@@ -247,7 +243,7 @@ steps:
- scripts/wait_for_emulator.sh
- ./gradlew installGplayDebugAndroidTest
- sed -i s"#5#1#" ./src/androidTest/java/com/nextcloud/client/RetryTestRule.kt
- scripts/runAllScreenshotCombinations "master" false
- ./gradlew gplayDebugExecuteScreenshotTests -Pandroid.testInstrumentationRunnerArguments.annotation=com.owncloud.android.utils.ScreenshotTest && scripts/deleteOutdatedComments.sh "master" "Screenshot" $DRONE_PULL_REQUEST $GIT_USERNAME $GIT_TOKEN || scripts/uploadReport.sh $LOG_USERNAME $LOG_PASSWORD $DRONE_BUILD_NUMBER "master" "Screenshot" $DRONE_PULL_REQUEST $GIT_USERNAME $GIT_TOKEN
- name: notify
image: drillster/drone-email
settings:
-2
View File
@@ -47,5 +47,3 @@ fastlane/Fastfile
# scan temporary files
**/fastlane/test_output
/fastlane/vendor/
/.bundle/
-10
View File
@@ -1,13 +1,3 @@
## 3.13.0 (August, 18, 2020)
- new UI overhaul @Shagequi @JorisBodin
- E2EE beta support
- dark mode enhancement @AndyScherzinger
- warn on outdated NC16 server
- requires Android 4.3 or newer
For a full list, please see https://github.com/nextcloud/android/milestone/48
## 3.12.1 (July, 07, 2020)
- UI does not hang when changing auto upload
-1
View File
@@ -379,7 +379,6 @@ Generally, whenever you need:
* media playback
* networking
* logging
* notifications management
we have something more suitable.
-10
View File
@@ -1,10 +0,0 @@
# Autogenerated by fastlane
#
# Ensure this file is checked in to source control!
source "https://rubygems.org"
gem 'fastlane'
plugins_path = File.join(File.dirname(__FILE__), 'fastlane', 'Pluginfile')
eval_gemfile(plugins_path) if File.exist?(plugins_path)
-180
View File
@@ -1,180 +0,0 @@
GEM
remote: https://rubygems.org/
specs:
CFPropertyList (3.0.2)
addressable (2.7.0)
public_suffix (>= 2.0.2, < 5.0)
atomos (0.1.3)
aws-eventstream (1.1.0)
aws-partitions (1.343.0)
aws-sdk-core (3.104.1)
aws-eventstream (~> 1, >= 1.0.2)
aws-partitions (~> 1, >= 1.239.0)
aws-sigv4 (~> 1.1)
jmespath (~> 1.0)
aws-sdk-kms (1.36.0)
aws-sdk-core (~> 3, >= 3.99.0)
aws-sigv4 (~> 1.1)
aws-sdk-s3 (1.75.0)
aws-sdk-core (~> 3, >= 3.104.1)
aws-sdk-kms (~> 1)
aws-sigv4 (~> 1.1)
aws-sigv4 (1.2.1)
aws-eventstream (~> 1, >= 1.0.2)
babosa (1.0.3)
claide (1.0.3)
colored (1.2)
colored2 (3.1.2)
commander-fastlane (4.4.6)
highline (~> 1.7.2)
declarative (0.0.20)
declarative-option (0.1.0)
digest-crc (0.6.1)
rake (~> 13.0)
domain_name (0.5.20190701)
unf (>= 0.0.5, < 1.0.0)
dotenv (2.7.6)
emoji_regex (3.0.0)
excon (0.75.0)
faraday (0.17.3)
multipart-post (>= 1.2, < 3)
faraday-cookie_jar (0.0.6)
faraday (>= 0.7.4)
http-cookie (~> 1.0.0)
faraday_middleware (0.14.0)
faraday (>= 0.7.4, < 1.0)
fastimage (2.1.7)
fastlane (2.152.0)
CFPropertyList (>= 2.3, < 4.0.0)
addressable (>= 2.3, < 3.0.0)
aws-sdk-s3 (~> 1.0)
babosa (>= 1.0.3, < 2.0.0)
bundler (>= 1.12.0, < 3.0.0)
colored
commander-fastlane (>= 4.4.6, < 5.0.0)
dotenv (>= 2.1.1, < 3.0.0)
emoji_regex (>= 0.1, < 4.0)
excon (>= 0.71.0, < 1.0.0)
faraday (>= 0.17, < 1.0)
faraday-cookie_jar (~> 0.0.6)
faraday_middleware (>= 0.13.1, < 2.0)
fastimage (>= 2.1.0, < 3.0.0)
gh_inspector (>= 1.1.2, < 2.0.0)
google-api-client (>= 0.37.0, < 0.39.0)
google-cloud-storage (>= 1.15.0, < 2.0.0)
highline (>= 1.7.2, < 2.0.0)
json (< 3.0.0)
jwt (>= 2.1.0, < 3)
mini_magick (>= 4.9.4, < 5.0.0)
multipart-post (~> 2.0.0)
plist (>= 3.1.0, < 4.0.0)
rubyzip (>= 2.0.0, < 3.0.0)
security (= 0.1.3)
simctl (~> 1.6.3)
slack-notifier (>= 2.0.0, < 3.0.0)
terminal-notifier (>= 2.0.0, < 3.0.0)
terminal-table (>= 1.4.5, < 2.0.0)
tty-screen (>= 0.6.3, < 1.0.0)
tty-spinner (>= 0.8.0, < 1.0.0)
word_wrap (~> 1.0.0)
xcodeproj (>= 1.13.0, < 2.0.0)
xcpretty (~> 0.3.0)
xcpretty-travis-formatter (>= 0.0.3)
fastlane-plugin-huawei_appgallery_connect (1.0.9)
gh_inspector (1.1.3)
google-api-client (0.38.0)
addressable (~> 2.5, >= 2.5.1)
googleauth (~> 0.9)
httpclient (>= 2.8.1, < 3.0)
mini_mime (~> 1.0)
representable (~> 3.0)
retriable (>= 2.0, < 4.0)
signet (~> 0.12)
google-cloud-core (1.5.0)
google-cloud-env (~> 1.0)
google-cloud-errors (~> 1.0)
google-cloud-env (1.3.3)
faraday (>= 0.17.3, < 2.0)
google-cloud-errors (1.0.1)
google-cloud-storage (1.26.2)
addressable (~> 2.5)
digest-crc (~> 0.4)
google-api-client (~> 0.33)
google-cloud-core (~> 1.2)
googleauth (~> 0.9)
mini_mime (~> 1.0)
googleauth (0.13.0)
faraday (>= 0.17.3, < 2.0)
jwt (>= 1.4, < 3.0)
memoist (~> 0.16)
multi_json (~> 1.11)
os (>= 0.9, < 2.0)
signet (~> 0.14)
highline (1.7.10)
http-cookie (1.0.3)
domain_name (~> 0.5)
httpclient (2.8.3)
jmespath (1.4.0)
json (2.3.1)
jwt (2.2.1)
memoist (0.16.2)
mini_magick (4.10.1)
mini_mime (1.0.2)
multi_json (1.15.0)
multipart-post (2.0.0)
nanaimo (0.3.0)
naturally (2.2.0)
os (1.1.0)
plist (3.5.0)
public_suffix (4.0.5)
rake (13.0.1)
representable (3.0.4)
declarative (< 0.1.0)
declarative-option (< 0.2.0)
uber (< 0.2.0)
retriable (3.1.2)
rouge (2.0.7)
rubyzip (2.3.0)
security (0.1.3)
signet (0.14.0)
addressable (~> 2.3)
faraday (>= 0.17.3, < 2.0)
jwt (>= 1.5, < 3.0)
multi_json (~> 1.10)
simctl (1.6.8)
CFPropertyList
naturally
slack-notifier (2.3.2)
terminal-notifier (2.0.0)
terminal-table (1.8.0)
unicode-display_width (~> 1.1, >= 1.1.1)
tty-cursor (0.7.1)
tty-screen (0.8.1)
tty-spinner (0.9.3)
tty-cursor (~> 0.7)
uber (0.1.0)
unf (0.1.4)
unf_ext
unf_ext (0.0.7.7)
unicode-display_width (1.7.0)
word_wrap (1.0.0)
xcodeproj (1.17.1)
CFPropertyList (>= 2.3.3, < 4.0)
atomos (~> 0.1.3)
claide (>= 1.0.2, < 2.0)
colored2 (~> 3.1)
nanaimo (~> 0.3.0)
xcpretty (0.3.0)
rouge (~> 2.0.7)
xcpretty-travis-formatter (1.0.0)
xcpretty (~> 0.2, >= 0.0.7)
PLATFORMS
ruby
DEPENDENCIES
fastlane
fastlane-plugin-huawei_appgallery_connect
BUNDLED WITH
2.1.4
+22 -36
View File
@@ -8,7 +8,7 @@ import com.github.spotbugs.snom.SpotBugsTask
// its root folder, another one for the app module in subfolder of root.
buildscript {
ext.kotlin_version = '1.4.0'
ext.kotlin_version = '1.3.72'
repositories {
google()
jcenter()
@@ -23,9 +23,9 @@ buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:4.0.1'
classpath('com.hiya:jacoco-android:0.2')
classpath 'gradle.plugin.com.github.spotbugs.snom:spotbugs-gradle-plugin:4.5.0'
classpath 'gradle.plugin.com.github.spotbugs.snom:spotbugs-gradle-plugin:4.4.4'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.11.2"
classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.10.0"
classpath "commons-httpclient:commons-httpclient:3.1@jar" // remove after entire switch to lib v2
classpath 'com.karumi:shot:4.3.0'
}
@@ -59,10 +59,9 @@ configurations {
ext {
jacocoVersion = "0.8.2"
daggerVersion = "2.28.3"
markwonVersion = "4.5.1"
daggerVersion = "2.28.1"
markwonVersion = "4.4.0"
prismVersion = "2.0.0"
butterknifeVersion = "10.2.3"
androidLibraryVersion = "master-SNAPSHOT"
travisBuild = System.getenv("TRAVIS") == "true"
@@ -84,7 +83,7 @@ repositories {
// semantic versioning for version code
def versionMajor = 3
def versionMinor = 14
def versionMinor = 13
def versionPatch = 0
def versionBuild = 0 // 0-50=Alpha / 51-98=RC / 90-99=stable
@@ -286,24 +285,24 @@ dependencies {
compileOnly 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2' // remove after entire switch to lib v2
implementation "commons-httpclient:commons-httpclient:3.1@jar" // remove after entire switch to lib v2
implementation 'org.apache.jackrabbit:jackrabbit-webdav:2.13.1' // remove after entire switch to lib v2
implementation 'androidx.constraintlayout:constraintlayout:2.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.2.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'com.jakewharton:disklrucache:2.0.2'
implementation 'androidx.appcompat:appcompat:1.2.0-rc01'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.exifinterface:exifinterface:1.2.0'
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
implementation "androidx.work:work-runtime:2.4.0"
implementation "androidx.work:work-runtime-ktx:2.4.0"
implementation "androidx.work:work-runtime:2.3.4"
implementation "androidx.work:work-runtime-ktx:2.3.4"
implementation "androidx.fragment:fragment:1.2.5"
implementation 'com.github.albfernandez:juniversalchardet:2.0.3' // need this version for Android <7
compileOnly 'com.google.code.findbugs:annotations:2.0.1'
implementation 'commons-io:commons-io:2.7'
implementation "com.jakewharton:butterknife:$butterknifeVersion"
kapt "com.jakewharton:butterknife-compiler:$butterknifeVersion"
implementation 'com.jakewharton:butterknife:10.2.1'
kapt 'com.jakewharton:butterknife-compiler:10.2.1'
implementation 'org.greenrobot:eventbus:3.2.0'
implementation 'com.googlecode.ez-vcard:ez-vcard:0.11.0'
implementation 'com.googlecode.ez-vcard:ez-vcard:0.10.6'
implementation 'org.lukhnos:nnio:0.2'
implementation 'org.bouncycastle:bcpkix-jdk15on:1.65'
implementation 'com.google.code.gson:gson:2.8.6'
@@ -321,8 +320,7 @@ dependencies {
implementation 'androidx.annotation:annotation:1.1.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.github.cotechde.hwsecurity:hwsecurity-fido:4.1.0'
implementation 'com.github.cotechde.hwsecurity:hwsecurity-fido2:4.1.0'
implementation 'com.github.cotechde.hwsecurity:hwsecurity-fido:2.5.1'
spotbugsPlugins 'com.h3xstream.findsecbugs:findsecbugs-plugin:1.10.1'
spotbugsPlugins 'com.mebigfatguy.fb-contrib:fb-contrib:7.4.7'
@@ -333,8 +331,8 @@ dependencies {
kapt "com.google.dagger:dagger-compiler:$daggerVersion"
kapt "com.google.dagger:dagger-android-processor:$daggerVersion"
ktlint "com.pinterest:ktlint:0.38.1"
implementation 'org.conscrypt:conscrypt-android:2.5.0'
ktlint "com.pinterest:ktlint:0.37.2"
implementation 'org.conscrypt:conscrypt-android:2.4.0'
// Shimmer animation
implementation 'com.elyeproj.libraries:loaderviewlibrary:2.0.0'
@@ -352,16 +350,14 @@ dependencies {
// dependencies for local unit tests
testImplementation 'junit:junit:4.13'
testImplementation 'org.mockito:mockito-core:3.4.6'
testImplementation 'org.mockito:mockito-core:3.4.2'
testImplementation 'androidx.test:core:1.2.0'
testImplementation 'org.powermock:powermock-core:2.0.7'
testImplementation 'org.powermock:powermock-module-junit4:2.0.7'
testImplementation 'org.powermock:powermock-api-mockito2:2.0.7'
testImplementation 'org.json:json:20200518'
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
testImplementation 'androidx.arch.core:core-testing:2.1.0'
testImplementation 'io.mockk:mockk:1.10.0'
testImplementation 'io.mockk:mockk-android:1.10.0'
testImplementation "androidx.arch.core:core-testing:2.1.0"
// dependencies for instrumented tests
// JUnit4 Rules
@@ -374,20 +370,7 @@ dependencies {
// Espresso core
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-web:3.2.0'
// Mocking support
androidTestImplementation 'com.github.tmurakami:dexopener:2.0.5' // required to allow mocking on API 27 and older
androidTestImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
androidTestImplementation 'org.mockito:mockito-core:3.4.4'
androidTestImplementation("org.mockito:mockito-android:3.4.6") {
exclude group: "net.bytebuddy", module: "byte-buddy-android"
}
androidTestImplementation 'net.bytebuddy:byte-buddy:1.10.14'
androidTestImplementation "net.bytebuddy:byte-buddy-android:1.10.14"
androidTestImplementation "io.mockk:mockk-android:1.10.0"
androidTestImplementation 'androidx.arch.core:core-testing:2.0.1'
androidTestImplementation 'org.mockito:mockito-core:3.4.0'
// 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
@@ -405,6 +388,9 @@ dependencies {
// androidJacocoAnt "org.jacoco:org.jacoco.agent:${jacocoVersion}"
implementation "com.github.stateless4j:stateless4j:2.6.0"
androidTestImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
androidTestImplementation "org.mockito:mockito-android:3.4.2"
androidTestImplementation 'net.bytebuddy:byte-buddy:1.10.13'
}
spotbugs {
+6 -6
View File
@@ -83,14 +83,14 @@ complexity:
ignoreStringsRegex: '$^'
TooManyFunctions:
active: true
thresholdInFiles: 15
thresholdInClasses: 15
thresholdInInterfaces: 15
thresholdInObjects: 15
thresholdInFiles: 11
thresholdInClasses: 11
thresholdInInterfaces: 11
thresholdInObjects: 11
thresholdInEnums: 11
ignoreDeprecated: true
ignoreDeprecated: false
ignorePrivate: false
ignoreOverridden: true
ignoreOverridden: false
empty-blocks:
active: true
+8 -25
View File
@@ -8,9 +8,6 @@ fastlane_version "2.58.0"
# export FASTLANE_NEXTCLOUD_KEY_ALIAS=""
# export FASTLANE_NEXTCLOUD_KEY_PASSWORD=""
# export FASTLANE_NEXTCLOUD_GITHUB_API_TOKEN=""
# export FASTLANE_NEXTCLOUD_HUAWEI_CLIENT_ID=""
# export FASTLANE_NEXTCLOUD_HUAWEI_CLIENT_SECRET=""
# export FASTLANE_NEXTCLOUD_HUAWEI_APP_ID=""
skip_docs
@@ -39,14 +36,19 @@ lane :screenshotsTablet do
end
desc "Release phase 1: make gplay/generic for RC, then test it"
lane :RC_releasePhase1 do
lane :releasePhase1_RC do
disableLogger()
makeReleases()
enableLogger()
end
desc "Release phase 1: make gplay/generic for FINAL, then test it"
lane :releasePhase1_Final do
makeReleases()
end
desc "Release phase 2 for RC: checks, tag, upload gplay to playstore with values from build.gradle"
lane :RC_releasePhase2 do |options|
lane :releasePhase2_RC do |options|
info = androidVersion
checkChangelog(info)
checkLibrary_RC()
@@ -59,13 +61,8 @@ lane :RC_releasePhase2 do |options|
createChangelogPullRequest_RC(info)
end
desc "Release phase 1: make gplay/generic for FINAL, then test it"
lane :Final_releasePhase1 do
makeReleases()
end
desc "Release phase 2 for FINAL: checks, tag, upload gplay to playstore with values from build.gradle"
lane :Final_releasePhase2 do |options|
lane :releasePhase2_Final do |options|
info = androidVersion
checkChangelog(info)
checkLibrary_Final()
@@ -73,7 +70,6 @@ lane :Final_releasePhase2 do |options|
checkIfAPKexists()
tag(info)
uploadToPlaystore_Final(info)
uploadToHuawei_Final(info)
createGithubRelease_Final(info)
fdroidMergeRequest_Final(info)
createChangelogPullRequest_Final(info)
@@ -120,19 +116,6 @@ lane :beautifyPhone do
sh("adb shell am broadcast -a com.android.systemui.demo -e command battery -e plugged false -e level 100")
end
# to install
# bundle exec fastlane add_plugin huawei_appgallery_connect
# bundle install --path build/vendor/bundle
private_lane :uploadToHuawei_Final do |options|
huawei_appgallery_connect(
client_id: ENV["FASTLANE_NEXTCLOUD_HUAWEI_CLIENT_ID"],
client_secret: ENV["FASTLANE_NEXTCLOUD_HUAWEI_CLIENT_SECRET"],
app_id: ENV["FASTLANE_NEXTCLOUD_HUAWEI_APP_ID"],
apk_path: "release/nextcloud-" + options["versionCode"] + ".apk",
submit_for_review: true,
)
end
## private lanes
desc "Build debug and test APK for screenshots"
-6
View File
@@ -1,6 +0,0 @@
# Autogenerated by fastlane
#
# Ensure this file is checked in to source control!
gem 'fastlane-plugin-huawei_appgallery_connect'
gem 'fastlane-plugin-huawei_appgallery_connect'
+3 -4
View File
@@ -58,9 +58,8 @@
<issue id="ObsoleteLintCustomCheck" severity="warning">
<ignore path="**/fragment-1.2.5/**/lint.jar" />
<ignore path="**/work-runtime-2.**/**/lint.jar" />
<ignore path="**/jetified-butterknife-runtime-10.**/**/lint.jar" />
<ignore path="**/jetified-dagger-lint-aar-2.28.**/**/lint.jar" />
<ignore path="**/jetified-annotation-experimental-1.**/**/lint.jar" />
<ignore path="**/work-runtime-2.3.4/**/lint.jar" />
<ignore path="**/jetified-butterknife-runtime-10.2.1/**/lint.jar" />
<ignore path="**/jetified-dagger-lint-aar-2.28.1/**/lint.jar" />
</issue>
</lint>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

+1 -1
View File
@@ -1,2 +1,2 @@
DO NOT TOUCH; GENERATED BY DRONE
<span class="mdl-layout-title">Lint Report: 81 warnings</span>
<span class="mdl-layout-title">Lint Report: 83 warnings</span>
+5 -37
View File
@@ -3,9 +3,7 @@
if [ $# -lt 2 ]; then
echo "1: record: true/false
2: class name
3: method name
4: darkMode / \"all\" to run all screenshot combinations
5: color"
3: method name"
exit
fi
@@ -16,12 +14,7 @@ emulator -writable-system -avd uiComparison -no-snapshot -gpu swiftshader_indire
cd src/androidTest/java
class=$(find | grep $2 | grep -E "java$|kt$" | head -n1|sed s'/\//\./'g | sed s'#^\.\.##' | sed s'#\.java##'| sed s'#\.kt##')
if [[ -z $class ]]; then
echo "Class not found!"
exit 1
fi
class=$(find | grep $2 | grep java | head -n1|sed s'/\//\./'g | sed s'#^\.\.##' | sed s'#\.java##')
cd ../../../
@@ -35,35 +28,10 @@ if [ -e $3 ] ; then
method=""
else
method="#$3"
# check if method exists
if [[ $(grep -c $3 $(find | grep $2 | grep -E "java$|kt$" | head -n1)) -eq 0 ]]; then
echo "Method not found!"
exit 1
fi
fi
if [ -e $4 ] ; then
darkMode=""
else
darkMode="-Pandroid.testInstrumentationRunnerArguments.DARKMODE=$4"
fi
if [ -e $5 ] ; then
color=""
else
color="-Pandroid.testInstrumentationRunnerArguments.COLOR=$5"
fi
if [[ $4 = "all" ]]; then
scripts/runAllScreenshotCombinations "noCI" "$1" "-Pandroid.testInstrumentationRunnerArguments.class=$class$method"
else
./gradlew gplayDebugExecuteScreenshotTests $record \
-Pandroid.testInstrumentationRunnerArguments.annotation=com.owncloud.android.utils.ScreenshotTest \
-Pandroid.testInstrumentationRunnerArguments.class=$class$method \
$darkMode \
$color
fi
./gradlew gplayDebugExecuteScreenshotTests $record \
-Pandroid.testInstrumentationRunnerArguments.annotation=com.owncloud.android.utils.ScreenshotTest \
-Pandroid.testInstrumentationRunnerArguments.class=$class$method
sed -i s'#<bool name="is_beta">true</bool>#<bool name="is_beta">false</bool>#'g src/main/res/values/setup.xml
-43
View File
@@ -1,43 +0,0 @@
#!/bin/bash
## $1 noCI/stable/master: wether to run deleteOutdatedComments.sh or uploadReport.sh
## $2 true/false: record or verify screenshots
## $3 classMethod: piped from androidScreenshotTest
if [[ $2 = "true" ]]; then
record="-Precord"
else
record=""
fi
classMethod=$3
while read line
do
darkMode=$(echo "$line" | cut -d" " -f1)
color=$(echo "$line" | cut -d" " -f2)
echo "Run $color on $darkMode mode"
if [[ $1 = "noCI" ]]; then
./gradlew --console plain gplayDebugExecuteScreenshotTests \
$record \
-Pandroid.testInstrumentationRunnerArguments.annotation=com.owncloud.android.utils.ScreenshotTest \
-Pandroid.testInstrumentationRunnerArguments.COLOR="$color" \
-Pandroid.testInstrumentationRunnerArguments.DARKMODE="$darkMode" \
$classMethod </dev/null > /dev/null
if [[ $? -ne 0 ]]; then
exit
fi
else
./gradlew gplayDebugExecuteScreenshotTests \
$record \
-Pandroid.testInstrumentationRunnerArguments.annotation=com.owncloud.android.utils.ScreenshotTest \
-Pandroid.testInstrumentationRunnerArguments.COLOR="$color" \
-Pandroid.testInstrumentationRunnerArguments.DARKMODE="$darkMode" \
&& scripts/deleteOutdatedComments.sh "$1-$darkMode-$color" "Screenshot" "$DRONE_PULL_REQUEST" \
"$GIT_USERNAME" "$GIT_TOKEN" \
|| scripts/uploadReport.sh "$LOG_USERNAME" "$LOG_PASSWORD" "$DRONE_BUILD_NUMBER" \
"$1-$darkMode-$color" "Screenshot" "$DRONE_PULL_REQUEST" "$GIT_USERNAME" "$GIT_TOKEN"
fi
done < scripts/screenshotCombinations
-1
View File
@@ -1 +0,0 @@
light blue
-17
View File
@@ -1,17 +0,0 @@
BEGIN:VCARD
VERSION:3.0
N:Mustermann;Erika;;Dr.;
FN:Dr. Erika Mustermann
ORG:Wikimedia
ROLE:Kommunikation
TITLE:Redaktion & Gestaltung
PHOTO;VALUE=URL;TYPE=JPEG:http://commons.wikimedia.org/wiki/File:Erika_Mustermann_2010.jpg
TEL;TYPE=WORK,VOICE:+49 221 9999123
TEL;TYPE=HOME,VOICE:+49 221 1234567
ADR;TYPE=HOME:;;Heidestraße 17;Köln;;51147;Germany
EMAIL;TYPE=PREF,INTERNET:[email protected]
URL:http://de.wikipedia.org/
REV:2014-03-01T22:11:10Z
END:VCARD
## from https://de.wikipedia.org/wiki/VCard#vCard_3.0 on 27.07.2020
@@ -25,6 +25,7 @@ package com.nextcloud.client;
import android.Manifest;
import android.view.View;
import com.facebook.testing.screenshot.Screenshot;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.R;
import com.owncloud.android.ui.activities.ActivitiesActivity;
@@ -59,13 +60,16 @@ public class ActivitiesActivityIT extends AbstractIT {
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
sut.runOnUiThread(() -> {
sut.emptyContentContainer.setVisibility(View.VISIBLE);
sut.recyclerView.setVisibility(View.INVISIBLE);
sut.runOnUiThread(new Runnable() {
@Override
public void run() {
sut.emptyContentContainer.setVisibility(View.VISIBLE);
sut.recyclerView.setVisibility(View.INVISIBLE);
}
});
waitForIdleSync();
screenshot(sut);
Screenshot.snapActivity(sut).record();
}
}
@@ -28,20 +28,14 @@ import com.owncloud.android.AbstractOnServerIT;
import com.owncloud.android.datamodel.ArbitraryDataProvider;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.db.OCUpload;
import com.owncloud.android.files.services.FileUploader;
import com.owncloud.android.lib.common.accounts.AccountUtils;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.e2ee.ToggleEncryptionRemoteOperation;
import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation;
import com.owncloud.android.lib.resources.status.OCCapability;
import com.owncloud.android.lib.resources.status.OwnCloudVersion;
import com.owncloud.android.lib.resources.users.GetPrivateKeyOperation;
import com.owncloud.android.lib.resources.users.GetPublicKeyOperation;
import com.owncloud.android.lib.resources.users.SendCSROperation;
import com.owncloud.android.lib.resources.users.StorePrivateKeyOperation;
import com.owncloud.android.operations.DownloadFileOperation;
import com.owncloud.android.operations.GetCapabilitiesOperation;
import com.owncloud.android.operations.RemoveFileOperation;
import com.owncloud.android.utils.CsrHelper;
import com.owncloud.android.utils.EncryptionUtils;
@@ -58,12 +52,9 @@ import java.io.IOException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static com.owncloud.android.lib.resources.status.OwnCloudVersion.nextcloud_19;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assume.assumeTrue;
@@ -73,9 +64,7 @@ public class EndToEndRandomIT extends AbstractOnServerIT {
CREATE_FOLDER,
GO_INTO_FOLDER,
GO_UP,
UPLOAD_FILE,
DOWNLOAD_FILE,
DELETE_FILE,
UPLOAD_FILE
}
private static ArbitraryDataProvider arbitraryDataProvider;
@@ -90,13 +79,7 @@ public class EndToEndRandomIT extends AbstractOnServerIT {
}
@Before
public void before() throws IOException {
OCCapability capability = getStorageManager().getCapability(account.name);
if (capability.getVersion().equals(new OwnCloudVersion("0.0.0"))) {
// fetch new one
assertTrue(new GetCapabilitiesOperation().execute(client, getStorageManager()).isSuccess());
}
public void before() {
// tests only for NC19+
assumeTrue(getStorageManager()
.getCapability(account.name)
@@ -104,8 +87,6 @@ public class EndToEndRandomIT extends AbstractOnServerIT {
.isNewerOrEqual(nextcloud_19)
);
// make sure that every file is available, even after tests that remove source file
createDummyFiles();
}
@Test
@@ -132,14 +113,6 @@ public class EndToEndRandomIT extends AbstractOnServerIT {
uploadFile(i);
break;
case DOWNLOAD_FILE:
downloadFile(i);
break;
case DELETE_FILE:
deleteFile(i);
break;
default:
Log_OC.d(this, "[" + i + "/" + actionCount + "]" + " Unknown action: " + nextAction);
break;
@@ -225,14 +198,6 @@ public class EndToEndRandomIT extends AbstractOnServerIT {
deleteFile(1);
}
@Test
public void downloadFile() throws Exception {
init();
uploadFile(1);
downloadFile(1);
}
private void init() throws Exception {
// create folder
createFolder(rootEncFolder);
@@ -295,149 +260,17 @@ public class EndToEndRandomIT extends AbstractOnServerIT {
private void uploadFile(int i) throws IOException {
String fileName = RandomString.make(5) + ".txt";
File file;
if (new Random().nextBoolean()) {
file = createFile(fileName, new Random().nextInt(50000));
} else {
file = createFile(fileName, 500000 + new Random().nextInt(50000));
}
String remotePath = currentFolder.getRemotePath() + fileName;
createFile(fileName, new Random().nextInt(50000));
String path = currentFolder.getRemotePath() + fileName;
Log_OC.d(this,
"[" + i + "/" + actionCount + "] " +
"Upload file to: " + currentFolder.getDecryptedRemotePath() + fileName);
OCUpload ocUpload = new OCUpload(file.getAbsolutePath(),
remotePath,
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + File.separator + fileName,
path,
account.name);
uploadOCUpload(ocUpload);
shortSleep();
OCFile parentFolder = getStorageManager()
.getFileByEncryptedRemotePath(new File(ocUpload.getRemotePath()).getParent() + "/");
String uploadedFileName = new File(ocUpload.getRemotePath()).getName();
String decryptedPath = parentFolder.getDecryptedRemotePath() + uploadedFileName;
OCFile uploadedFile = getStorageManager().getFileByDecryptedRemotePath(decryptedPath);
verifyStoragePath(uploadedFile);
// verify storage path
refreshFolder(currentFolder.getRemotePath());
uploadedFile = getStorageManager().getFileByDecryptedRemotePath(decryptedPath);
verifyStoragePath(uploadedFile);
// verify that encrypted file is on server
assertTrue(new ReadFileRemoteOperation(currentFolder.getRemotePath() + uploadedFile.getEncryptedFileName())
.execute(client)
.isSuccess());
// verify that unencrypted file is not on server
assertFalse(new ReadFileRemoteOperation(currentFolder.getDecryptedRemotePath() + fileName)
.execute(client)
.isSuccess());
}
private void downloadFile(int i) {
ArrayList<OCFile> files = new ArrayList<>();
for (OCFile file : getStorageManager().getFolderContent(currentFolder, false)) {
if (!file.isFolder()) {
files.add(file);
}
}
if (files.isEmpty()) {
Log_OC.d(this, "[" + i + "/" + actionCount + "] No files in: " + currentFolder.getDecryptedRemotePath());
return;
}
OCFile fileToDownload = files.get(new Random().nextInt(files.size()));
assertNotNull(fileToDownload.getRemoteId());
Log_OC.d(this,
"[" + i + "/" + actionCount + "] " + "Download file: " +
currentFolder.getDecryptedRemotePath() + fileToDownload.getDecryptedFileName());
assertTrue(new DownloadFileOperation(account, fileToDownload, targetContext)
.execute(client)
.isSuccess());
assertTrue(new File(fileToDownload.getStoragePath()).exists());
verifyStoragePath(fileToDownload);
}
@Test
public void testUploadWithCopy() throws Exception {
init();
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
currentFolder.getRemotePath() + "nonEmpty.txt",
account.name);
uploadOCUpload(ocUpload, FileUploader.LOCAL_BEHAVIOUR_COPY);
File originalFile = new File(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt");
OCFile uploadedFile = fileDataStorageManager.getFileByDecryptedRemotePath(currentFolder.getRemotePath() +
"nonEmpty.txt");
assertTrue(originalFile.exists());
assertTrue(new File(uploadedFile.getStoragePath()).exists());
}
@Test
public void testUploadWithMove() throws Exception {
init();
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
currentFolder.getRemotePath() + "nonEmpty.txt",
account.name);
uploadOCUpload(ocUpload, FileUploader.LOCAL_BEHAVIOUR_MOVE);
File originalFile = new File(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt");
OCFile uploadedFile = fileDataStorageManager.getFileByDecryptedRemotePath(currentFolder.getRemotePath() +
"nonEmpty.txt");
assertFalse(originalFile.exists());
assertTrue(new File(uploadedFile.getStoragePath()).exists());
}
@Test
public void testUploadWithForget() throws Exception {
init();
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
currentFolder.getRemotePath() + "nonEmpty.txt",
account.name);
uploadOCUpload(ocUpload, FileUploader.LOCAL_BEHAVIOUR_FORGET);
File originalFile = new File(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt");
OCFile uploadedFile = fileDataStorageManager.getFileByDecryptedRemotePath(currentFolder.getRemotePath() +
"nonEmpty.txt");
assertTrue(originalFile.exists());
assertFalse(new File(uploadedFile.getStoragePath()).exists());
}
@Test
public void testUploadWithDelete() throws Exception {
init();
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
currentFolder.getRemotePath() + "nonEmpty.txt",
account.name);
uploadOCUpload(ocUpload, FileUploader.LOCAL_BEHAVIOUR_DELETE);
File originalFile = new File(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt");
OCFile uploadedFile = fileDataStorageManager.getFileByDecryptedRemotePath(currentFolder.getRemotePath() +
"nonEmpty.txt");
assertFalse(originalFile.exists());
assertFalse(new File(uploadedFile.getStoragePath()).exists());
}
private void deleteFile(int i) {
@@ -448,13 +281,7 @@ public class EndToEndRandomIT extends AbstractOnServerIT {
}
}
if (files.isEmpty()) {
Log_OC.d(this, "[" + i + "/" + actionCount + "] No files in: " + currentFolder.getDecryptedRemotePath());
return;
}
OCFile fileToDelete = files.get(new Random().nextInt(files.size()));
assertNotNull(fileToDelete.getRemoteId());
Log_OC.d(this,
"[" + i + "/" + actionCount + "] " +
@@ -568,65 +395,4 @@ public class EndToEndRandomIT extends AbstractOnServerIT {
private String generateMnemonicString() {
return "1 2 3 4 5 6";
}
public void after() {
// remove all encrypted files
OCFile root = fileDataStorageManager.getFileByDecryptedRemotePath("/");
removeFolder(root);
// List<OCFile> files = fileDataStorageManager.getFolderContent(root, false);
//
// for (OCFile child : files) {
// removeFolder(child);
// }
assertEquals(0, fileDataStorageManager.getFolderContent(root, false).size());
super.after();
}
private void removeFolder(OCFile folder) {
Log_OC.d(this, "Start removing content of folder: " + folder.getDecryptedRemotePath());
List<OCFile> children = fileDataStorageManager.getFolderContent(folder, false);
// remove children
for (OCFile child : children) {
if (child.isFolder()) {
removeFolder(child);
// remove folder
Log_OC.d(this, "Remove folder: " + child.getDecryptedRemotePath());
if (!folder.isEncrypted() && child.isEncrypted()) {
assertTrue(new ToggleEncryptionRemoteOperation(child.getLocalId(),
child.getRemotePath(),
false)
.execute(client)
.isSuccess());
OCFile f = getStorageManager().getFileByEncryptedRemotePath(child.getRemotePath());
f.setEncrypted(false);
getStorageManager().saveFile(f);
child.setEncrypted(false);
}
} else {
Log_OC.d(this, "Remove file: " + child.getDecryptedRemotePath());
}
assertTrue(new RemoveFileOperation(child, false, account, false, targetContext)
.execute(client, getStorageManager())
.isSuccess()
);
}
Log_OC.d(this, "Finished removing content of folder: " + folder.getDecryptedRemotePath());
}
private void verifyStoragePath(OCFile file) {
assertEquals(FileStorageUtils.getSavePath(account.name) +
currentFolder.getDecryptedRemotePath() +
file.getDecryptedFileName(),
file.getStoragePath());
}
}
@@ -25,6 +25,7 @@ package com.nextcloud.client;
import android.Manifest;
import android.app.Activity;
import com.facebook.testing.screenshot.Screenshot;
import com.owncloud.android.AbstractOnServerIT;
import com.owncloud.android.R;
import com.owncloud.android.datamodel.OCFile;
@@ -125,7 +126,7 @@ public class FileDisplayActivityIT extends AbstractOnServerIT {
shortSleep();
shortSleep();
screenshot(sut);
Screenshot.snapActivity(sut).record();
}
@Test
@@ -24,6 +24,7 @@ package com.nextcloud.client;
import android.Manifest;
import com.facebook.testing.screenshot.Screenshot;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.R;
import com.owncloud.android.ui.activity.FileDisplayActivity;
@@ -54,11 +55,9 @@ public class FileDisplayActivityScreenshotIT extends AbstractIT {
FileDisplayActivity sut = activityRule.launchActivity(null);
sut.getListOfFilesFragment().setFabEnabled(false);
sut.getListOfFilesFragment().setEmptyListLoadingMessage(false);
sut.getListOfFilesFragment().setLoading(false);
waitForIdleSync();
sut.getListOfFilesFragment().setEmptyListLoadingMessage();
screenshot(sut);
Screenshot.snapActivity(sut).record();
}
@Test
@@ -69,10 +68,8 @@ public class FileDisplayActivityScreenshotIT extends AbstractIT {
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
sut.getListOfFilesFragment().setFabEnabled(false);
sut.getListOfFilesFragment().setEmptyListLoadingMessage(false);
sut.getListOfFilesFragment().setLoading(false);
waitForIdleSync();
sut.getListOfFilesFragment().setEmptyListLoadingMessage();
screenshot(sut);
Screenshot.snapActivity(sut).record();
}
}
@@ -25,6 +25,7 @@ package com.nextcloud.client;
import android.Manifest;
import android.app.Activity;
import com.facebook.testing.screenshot.Screenshot;
import com.nextcloud.client.onboarding.FirstRunActivity;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.utils.ScreenshotTest;
@@ -50,7 +51,7 @@ public class FirstRunActivityIT extends AbstractIT {
public void open() {
Activity sut = activityRule.launchActivity(null);
screenshot(sut);
Screenshot.snapActivity(sut).record();
}
}
@@ -0,0 +1,52 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.client;
import android.Manifest;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.ui.activity.NotificationsActivity;
import com.owncloud.android.utils.ScreenshotTest;
import org.junit.Rule;
import org.junit.Test;
import androidx.test.espresso.intent.rule.IntentsTestRule;
import androidx.test.rule.GrantPermissionRule;
public class NotificationsActivityIT extends AbstractIT {
@Rule public IntentsTestRule<NotificationsActivity> activityRule = new IntentsTestRule<>(NotificationsActivity.class,
true,
false);
@Rule
public final GrantPermissionRule permissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE);
@Test
@ScreenshotTest
public void openDrawer() {
super.openDrawer(activityRule);
}
}
@@ -22,33 +22,14 @@
package com.nextcloud.client;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import com.facebook.testing.screenshot.ScreenshotRunner;
import com.github.tmurakami.dexopener.DexOpener;
import androidx.test.runner.AndroidJUnitRunner;
public class ScreenshotTestRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(ClassLoader cl, String className, Context context)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
/*
* Initialize DexOpener only on API below 28 to enable mocking of Kotlin classes.
* On API 28+ the platform supports mocking natively.
*/
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
DexOpener.install(this);
}
return super.newApplication(cl, className, context);
}
@Override
public void onCreate(Bundle args) {
super.onCreate(args);
@@ -24,14 +24,10 @@ package com.nextcloud.client;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Looper;
import com.facebook.testing.screenshot.Screenshot;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.datamodel.ArbitraryDataProvider;
import com.owncloud.android.ui.activity.RequestCredentialsActivity;
import com.owncloud.android.ui.activity.SettingsActivity;
import com.owncloud.android.utils.EncryptionUtils;
import com.owncloud.android.utils.ScreenshotTest;
import org.junit.Rule;
@@ -40,8 +36,6 @@ import org.junit.Test;
import androidx.test.espresso.intent.rule.IntentsTestRule;
import androidx.test.rule.GrantPermissionRule;
import static org.junit.Assert.assertTrue;
public class SettingsActivityIT extends AbstractIT {
@Rule public IntentsTestRule<SettingsActivity> activityRule = new IntentsTestRule<>(SettingsActivity.class,
@@ -55,37 +49,8 @@ public class SettingsActivityIT extends AbstractIT {
@Test
@ScreenshotTest
public void open() {
Activity sut = activityRule.launchActivity(null);
Activity test = activityRule.launchActivity(null);
screenshot(sut);
}
@Test
@ScreenshotTest
public void showMnemonic_Error() {
SettingsActivity sut = activityRule.launchActivity(null);
sut.handleMnemonicRequest(null);
shortSleep();
waitForIdleSync();
screenshot(sut);
}
@Test
public void showMnemonic() {
if (Looper.myLooper() == null) {
Looper.prepare();
}
Intent intent = new Intent();
intent.putExtra(RequestCredentialsActivity.KEY_CHECK_RESULT, RequestCredentialsActivity.KEY_CHECK_RESULT_TRUE);
ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(targetContext.getContentResolver());
arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(), EncryptionUtils.MNEMONIC, "Secret mnemonic");
SettingsActivity sut = activityRule.launchActivity(null);
sut.handleMnemonicRequest(intent);
assertTrue(true); // if we reach this, everything is ok
Screenshot.snapActivity(test).record();
}
}
@@ -25,6 +25,7 @@ package com.nextcloud.client;
import android.Manifest;
import android.content.Intent;
import com.facebook.testing.screenshot.Screenshot;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.datamodel.MediaFolderType;
import com.owncloud.android.datamodel.SyncedFolderDisplayItem;
@@ -86,6 +87,6 @@ public class SyncedFoldersActivityIT extends AbstractIT {
getInstrumentation().waitForIdleSync();
shortSleep();
screenshot(Objects.requireNonNull(sut.requireDialog().getWindow()).getDecorView());
Screenshot.snap(Objects.requireNonNull(sut.requireDialog().getWindow()).getDecorView()).record();
}
}
@@ -1,71 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz <[email protected]>
* Copyright (C) 2020 Chris Narkiewicz
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.account
import android.os.Parcel
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotSame
import org.junit.Assert.assertTrue
import org.junit.Test
class MockUserTest {
private companion object {
const val ACCOUNT_NAME = "test_account_name"
const val ACCOUNT_TYPE = "test_account_type"
}
@Test
fun mock_user_is_parcelable() {
// GIVEN
// mock user instance
val original = MockUser(ACCOUNT_NAME, ACCOUNT_TYPE)
// WHEN
// instance is serialized into Parcel
// instance is retrieved from Parcel
val parcel = Parcel.obtain()
parcel.setDataPosition(0)
parcel.writeParcelable(original, 0)
parcel.setDataPosition(0)
val retrieved = parcel.readParcelable<User>(User::class.java.classLoader)
// THEN
// retrieved instance in distinct
// instances are equal
assertNotSame(original, retrieved)
assertTrue(retrieved is MockUser)
assertEquals(original, retrieved)
}
@Test
fun mock_user_has_platform_account() {
// GIVEN
// mock user instance
val mock = MockUser(ACCOUNT_NAME, ACCOUNT_TYPE)
// THEN
// can convert to platform account
val account = mock.toPlatformAccount()
assertEquals(ACCOUNT_NAME, account.name)
assertEquals(ACCOUNT_TYPE, account.type)
}
}
@@ -1,58 +0,0 @@
/**
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.files.downloader
import androidx.test.core.app.ApplicationProvider.getApplicationContext
import androidx.test.rule.ServiceTestRule
import com.nextcloud.client.account.MockUser
import io.mockk.MockKAnnotations
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
class DownloaderServiceTest {
@get:Rule
val service = ServiceTestRule.withTimeout(3, TimeUnit.SECONDS)
val user = MockUser()
@Before
fun setUp() {
MockKAnnotations.init(this, relaxed = true)
}
@Test(expected = TimeoutException::class)
fun cannot_bind_to_service_without_user() {
val intent = DownloaderService.createBindIntent(getApplicationContext(), user)
intent.removeExtra(DownloaderService.EXTRA_USER)
service.bindService(intent)
}
@Test
fun bind_with_user() {
val intent = DownloaderService.createBindIntent(getApplicationContext(), user)
val binder = service.bindService(intent)
assertTrue(binder is DownloaderService.Binder)
}
}
@@ -1,519 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.files.downloader
import com.nextcloud.client.account.User
import com.owncloud.android.datamodel.OCFile
import io.mockk.CapturingSlot
import io.mockk.MockKAnnotations
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.verify
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Suite
import java.util.UUID
@RunWith(Suite::class)
@Suite.SuiteClasses(
RegistryTest.Pending::class,
RegistryTest.Start::class,
RegistryTest.Progress::class,
RegistryTest.Complete::class,
RegistryTest.GetTransfers::class,
RegistryTest.IsRunning::class
)
class RegistryTest {
abstract class Base {
companion object {
const val MAX_TRANSFER_THREADS = 4
const val PROGRESS_FULL = 100
const val PROGRESS_HALF = 50
}
@MockK
lateinit var user: User
lateinit var file: OCFile
@MockK
lateinit var onTransferStart: (UUID, Request) -> Unit
@MockK
lateinit var onTransferChanged: (Transfer) -> Unit
internal lateinit var registry: Registry
@Before
fun setUpBase() {
MockKAnnotations.init(this, relaxed = true)
file = OCFile("/test/path")
registry = Registry(onTransferStart, onTransferChanged, MAX_TRANSFER_THREADS)
resetMocks()
}
fun resetMocks() {
clearAllMocks()
every { onTransferStart(any(), any()) } answers {}
every { onTransferChanged(any()) } answers {}
}
}
class Pending : Base() {
@Test
fun inserting_pending_transfer() {
// GIVEN
// registry has no pending transfers
assertEquals(0, registry.pending.size)
// WHEN
// new transfer requests added
val addedTransfersCount = 10
for (i in 0 until addedTransfersCount) {
val request = Request(user, file)
registry.add(request)
}
// THEN
// transfer is added to the pending queue
assertEquals(addedTransfersCount, registry.pending.size)
}
}
class Start : Base() {
companion object {
const val ENQUEUED_REQUESTS_COUNT = 10
}
@Before
fun setUp() {
for (i in 0 until ENQUEUED_REQUESTS_COUNT) {
registry.add(Request(user, file))
}
assertEquals(ENQUEUED_REQUESTS_COUNT, registry.pending.size)
}
@Test
fun starting_transfer() {
// WHEN
// started
registry.startNext()
// THEN
// up to max threads requests are started
// start callback is triggered
// update callback is triggered on transfer transition
// started transfers are in running state
assertEquals(
"Transfers not moved to running queue",
MAX_TRANSFER_THREADS,
registry.running.size
)
assertEquals(
"Transfers not moved from pending queue",
ENQUEUED_REQUESTS_COUNT - MAX_TRANSFER_THREADS,
registry.pending.size
)
verify(exactly = MAX_TRANSFER_THREADS) { onTransferStart(any(), any()) }
val startedTransfers = mutableListOf<Transfer>()
verify(exactly = MAX_TRANSFER_THREADS) { onTransferChanged(capture(startedTransfers)) }
assertEquals(
"Callbacks not invoked for running transfers",
MAX_TRANSFER_THREADS,
startedTransfers.size
)
startedTransfers.forEach {
assertEquals("Transfer not placed into running state", TransferState.RUNNING, it.state)
}
}
@Test
fun start_is_ignored_if_no_more_free_threads() {
// WHEN
// max number of running transfers
registry.startNext()
assertEquals(MAX_TRANSFER_THREADS, registry.running.size)
clearAllMocks()
// WHEN
// starting more transfers
registry.startNext()
// THEN
// no more transfers can be started
assertEquals(MAX_TRANSFER_THREADS, registry.running.size)
verify(exactly = 0) { onTransferStart(any(), any()) }
}
}
class Progress : Base() {
var uuid: UUID = UUID.randomUUID()
@Before
fun setUp() {
val request = Request(user, file)
uuid = registry.add(request)
registry.startNext()
assertEquals(uuid, request.uuid)
assertEquals(1, registry.running.size)
resetMocks()
}
@Test
fun transfer_progress_is_updated() {
// GIVEN
// a transfer is running
// WHEN
// transfer progress is updated
val progressHalf = 50
registry.progress(uuid, progressHalf)
// THEN
// progress is updated
// update callback is invoked
val transfer = mutableListOf<Transfer>()
verify { onTransferChanged(capture(transfer)) }
assertEquals(1, transfer.size)
assertEquals(progressHalf, transfer.first().progress)
}
@Test
fun updates_for_non_running_transfers_are_ignored() {
// GIVEN
// transfer is not running
registry.complete(uuid, true)
assertEquals(0, registry.running.size)
resetMocks()
// WHEN
// progress for a non-running transfer is updated
registry.progress(uuid, PROGRESS_HALF)
// THEN
// progress update is ignored
verify(exactly = 0) { onTransferChanged(any()) }
}
@Test
fun updates_for_non_existing_transfers_are_ignored() {
// GIVEN
// some transfer is running
// WHEN
// progress is updated for non-existing transfer
val nonExistingTransferId = UUID.randomUUID()
registry.progress(nonExistingTransferId, PROGRESS_HALF)
// THEN
// progress uppdate is ignored
verify(exactly = 0) { onTransferChanged(any()) }
}
}
class Complete : Base() {
lateinit var uuid: UUID
@Before
fun setUp() {
uuid = registry.add(Request(user, file))
registry.startNext()
registry.progress(uuid, PROGRESS_FULL)
resetMocks()
}
@Test
fun complete_successful_transfer_with_updated_file() {
// GIVEN
// a transfer is running
// WHEN
// transfer is completed
// file has been updated
val updatedFile = OCFile("/updated/file")
registry.complete(uuid, true, updatedFile)
// THEN
// transfer is completed successfully
// status carries updated file
val slot = CapturingSlot<Transfer>()
verify { onTransferChanged(capture(slot)) }
assertEquals(TransferState.COMPLETED, slot.captured.state)
assertSame(slot.captured.file, updatedFile)
}
@Test
fun complete_successful_transfer() {
// GIVEN
// a transfer is running
// WHEN
// transfer is completed
// file is not updated
registry.complete(uuid = uuid, success = true, file = null)
// THEN
// transfer is completed successfully
// status carries previous file
val slot = CapturingSlot<Transfer>()
verify { onTransferChanged(capture(slot)) }
assertEquals(TransferState.COMPLETED, slot.captured.state)
assertSame(slot.captured.file, file)
}
@Test
fun complete_failed_transfer() {
// GIVEN
// a transfer is running
// WHEN
// transfer is failed
registry.complete(uuid, false)
// THEN
// transfer is completed successfully
val slot = CapturingSlot<Transfer>()
verify { onTransferChanged(capture(slot)) }
assertEquals(TransferState.FAILED, slot.captured.state)
}
}
class GetTransfers : Base() {
val pendingTransferFile = OCFile("/pending")
val runningTransferFile = OCFile("/running")
val completedTransferFile = OCFile("/completed")
lateinit var pendingTransferId: UUID
lateinit var runningTransferId: UUID
lateinit var completedTransferId: UUID
@Before
fun setUp() {
completedTransferId = registry.add(Request(user, completedTransferFile))
registry.startNext()
registry.complete(completedTransferId, true)
runningTransferId = registry.add(Request(user, runningTransferFile))
registry.startNext()
pendingTransferId = registry.add(Request(user, pendingTransferFile))
resetMocks()
assertEquals(1, registry.pending.size)
assertEquals(1, registry.running.size)
assertEquals(1, registry.completed.size)
}
@Test
fun get_by_path_searches_pending_queue() {
// GIVEN
// file transfer is pending
// WHEN
// transfer status is retrieved
val transfer = registry.getTransfer(pendingTransferFile)
// THEN
// transfer from pending queue is returned
assertNotNull(transfer)
assertEquals(pendingTransferId, transfer?.uuid)
}
@Test
fun get_by_id_searches_pending_queue() {
// GIVEN
// file transfer is pending
// WHEN
// transfer status is retrieved
val transfer = registry.getTransfer(pendingTransferId)
// THEN
// transfer from pending queue is returned
assertNotNull(transfer)
assertEquals(pendingTransferId, transfer?.uuid)
}
@Test
fun get_by_path_searches_running_queue() {
// GIVEN
// file transfer is running
// WHEN
// transfer status is retrieved
val transfer = registry.getTransfer(runningTransferFile)
// THEN
// transfer from pending queue is returned
assertNotNull(transfer)
assertEquals(runningTransferId, transfer?.uuid)
}
@Test
fun get_by_id_searches_running_queue() {
// GIVEN
// file transfer is running
// WHEN
// transfer status is retrieved
val transfer = registry.getTransfer(runningTransferId)
// THEN
// transfer from pending queue is returned
assertNotNull(transfer)
assertEquals(runningTransferId, transfer?.uuid)
}
@Test
fun get_by_path_searches_completed_queue() {
// GIVEN
// file transfer is pending
// WHEN
// transfer status is retrieved
val transfer = registry.getTransfer(completedTransferFile)
// THEN
// transfer from pending queue is returned
assertNotNull(transfer)
assertEquals(completedTransferId, transfer?.uuid)
}
@Test
fun get_by_id_searches_completed_queue() {
// GIVEN
// file transfer is pending
// WHEN
// transfer status is retrieved
val transfer = registry.getTransfer(completedTransferId)
// THEN
// transfer from pending queue is returned
assertNotNull(transfer)
assertEquals(completedTransferId, transfer?.uuid)
}
@Test
fun not_found_by_path() {
// GIVEN
// no transfer for a file
val nonExistingTransferFile = OCFile("/non-nexisting/transfer")
// WHEN
// transfer status is retrieved for a file
val transfer = registry.getTransfer(nonExistingTransferFile)
// THEN
// no transfer is found
assertNull(transfer)
}
@Test
fun not_found_by_id() {
// GIVEN
// no transfer for an id
val nonExistingId = UUID.randomUUID()
// WHEN
// transfer status is retrieved for a file
val transfer = registry.getTransfer(nonExistingId)
// THEN
// no transfer is found
assertNull(transfer)
}
}
class IsRunning : Base() {
@Test
fun no_requests() {
// WHEN
// all queues empty
assertEquals(0, registry.pending.size)
assertEquals(0, registry.running.size)
assertEquals(0, registry.completed.size)
// THEN
// not running
assertFalse(registry.isRunning)
}
@Test
fun request_pending() {
// WHEN
// request is enqueued
registry.add(Request(user, OCFile("/path/alpha/1")))
assertEquals(1, registry.pending.size)
assertEquals(0, registry.running.size)
assertEquals(0, registry.completed.size)
// THEN
// is running
assertTrue(registry.isRunning)
}
@Test
fun request_running() {
// WHEN
// request is running
registry.add(Request(user, OCFile("/path/alpha/1")))
registry.startNext()
assertEquals(0, registry.pending.size)
assertEquals(1, registry.running.size)
assertEquals(0, registry.completed.size)
// THEN
// is running
assertTrue(registry.isRunning)
}
@Test
fun request_completed() {
// WHEN
// request is running
val id = registry.add(Request(user, OCFile("/path/alpha/1")))
registry.startNext()
registry.complete(id, true)
assertEquals(0, registry.pending.size)
assertEquals(0, registry.running.size)
assertEquals(1, registry.completed.size)
// THEN
// is not running
assertFalse(registry.isRunning)
}
}
}
@@ -1,240 +0,0 @@
/**
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.files.downloader
import android.content.ComponentName
import android.content.Context
import com.nextcloud.client.account.MockUser
import com.owncloud.android.datamodel.OCFile
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.mockk
import io.mockk.verify
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class TransferManagerConnectionTest {
lateinit var connection: TransferManagerConnection
@MockK
lateinit var context: Context
@MockK
lateinit var firstDownloadListener: (Transfer) -> Unit
@MockK
lateinit var secondDownloadListener: (Transfer) -> Unit
@MockK
lateinit var firstStatusListener: (TransferManager.Status) -> Unit
@MockK
lateinit var secondStatusListener: (TransferManager.Status) -> Unit
@MockK
lateinit var binder: DownloaderService.Binder
val file get() = OCFile("/path")
val componentName = ComponentName("", DownloaderService::class.java.simpleName)
val user = MockUser()
@Before
fun setUp() {
MockKAnnotations.init(this, relaxed = true)
connection = TransferManagerConnection(context, user)
}
@Test
fun listeners_are_set_after_connection() {
// GIVEN
// not connected
// listener is added
connection.registerTransferListener(firstDownloadListener)
connection.registerTransferListener(secondDownloadListener)
// WHEN
// service is bound
connection.onServiceConnected(componentName, binder)
// THEN
// all listeners are passed to the service
val listeners = mutableListOf<(Transfer) -> Unit>()
verify { binder.registerTransferListener(capture(listeners)) }
assertEquals(listOf(firstDownloadListener, secondDownloadListener), listeners)
}
@Test
fun listeners_are_set_immediately_when_connected() {
// GIVEN
// service is bound
connection.onServiceConnected(componentName, binder)
// WHEN
// listeners are added
connection.registerTransferListener(firstDownloadListener)
// THEN
// listener is forwarded to service
verify { binder.registerTransferListener(firstDownloadListener) }
}
@Test
fun listeners_are_removed_when_unbinding() {
// GIVEN
// service is bound
// service has some listeners
connection.onServiceConnected(componentName, binder)
connection.registerTransferListener(firstDownloadListener)
connection.registerTransferListener(secondDownloadListener)
// WHEN
// service unbound
connection.unbind()
// THEN
// listeners removed from service
verify { binder.removeTransferListener(firstDownloadListener) }
verify { binder.removeTransferListener(secondDownloadListener) }
}
@Test
fun missed_updates_are_delivered_on_connection() {
// GIVEN
// not bound
// has listeners
// download is scheduled and is progressing
connection.registerTransferListener(firstDownloadListener)
connection.registerTransferListener(secondDownloadListener)
val request1 = Request(user, file)
connection.enqueue(request1)
val download1 = Transfer(request1.uuid, TransferState.RUNNING, 50, request1.file, request1)
val request2 = Request(user, file)
connection.enqueue(request2)
val download2 = Transfer(request2.uuid, TransferState.RUNNING, 50, request2.file, request1)
every { binder.getTransfer(request1.uuid) } returns download1
every { binder.getTransfer(request2.uuid) } returns download2
// WHEN
// service is bound
connection.onServiceConnected(componentName, binder)
// THEN
// listeners receive current download state for pending downloads
val firstListenerNotifications = mutableListOf<Transfer>()
verify { firstDownloadListener(capture(firstListenerNotifications)) }
assertEquals(listOf(download1, download2), firstListenerNotifications)
val secondListenerNotifications = mutableListOf<Transfer>()
verify { secondDownloadListener(capture(secondListenerNotifications)) }
assertEquals(listOf(download1, download2), secondListenerNotifications)
}
@Test
fun downloader_status_updates_are_delivered_on_connection() {
// GIVEN
// not bound
// has status listeners
val mockStatus: TransferManager.Status = mockk()
every { binder.status } returns mockStatus
connection.registerStatusListener(firstStatusListener)
connection.registerStatusListener(secondStatusListener)
// WHEN
// service is bound
connection.onServiceConnected(componentName, binder)
// THEN
// downloader status is delivered
verify { firstStatusListener(mockStatus) }
verify { secondStatusListener(mockStatus) }
}
@Test
fun downloader_status_not_requested_if_no_listeners() {
// GIVEN
// not bound
// no status listeners
// WHEN
// service is bound
connection.onServiceConnected(componentName, binder)
// THEN
// downloader status is not requested
verify(exactly = 0) { binder.status }
}
@Test
fun not_running_if_not_connected() {
// GIVEN
// downloader is running
// connection not bound
every { binder.isRunning } returns true
// THEN
// not running
assertFalse(connection.isRunning)
}
@Test
fun is_running_from_binder_if_connected() {
// GIVEN
// service bound
every { binder.isRunning } returns true
connection.onServiceConnected(componentName, binder)
// WHEN
// is runnign flag accessed
val isRunning = connection.isRunning
// THEN
// call delegated to binder
assertTrue(isRunning)
verify(exactly = 1) { binder.isRunning }
}
@Test
fun missed_updates_not_tracked_before_listeners_registered() {
// GIVEN
// not bound
// some downloads requested without listener
val request = Request(user, file)
connection.enqueue(request)
val download = Transfer(request.uuid, TransferState.RUNNING, 50, request.file, request)
connection.registerTransferListener(firstDownloadListener)
every { binder.getTransfer(request.uuid) } returns download
// WHEN
// service is bound
connection.onServiceConnected(componentName, binder)
// THEN
// missed updates not redelivered
verify(exactly = 0) { firstDownloadListener(any()) }
}
}
@@ -1,281 +0,0 @@
/**
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.files.downloader
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.nextcloud.client.account.User
import com.nextcloud.client.core.ManualAsyncRunner
import com.nextcloud.client.core.OnProgressCallback
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.lib.common.OwnCloudClient
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.mockk
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Suite
import org.mockito.MockitoAnnotations
@RunWith(Suite::class)
@Suite.SuiteClasses(
TransferManagerTest.Enqueue::class,
TransferManagerTest.TransferStatusUpdates::class
)
class TransferManagerTest {
abstract class Base {
companion object {
const val MAX_TRANSFER_THREADS = 4
}
@MockK
lateinit var user: User
@MockK
lateinit var client: OwnCloudClient
@MockK
lateinit var mockTaskFactory: DownloadTask.Factory
/**
* All task mock functions created during test run are
* stored here.
*/
lateinit var downloadTaskMocks: MutableList<DownloadTask>
lateinit var runner: ManualAsyncRunner
lateinit var transferManager: TransferManagerImpl
/**
* Response value for all download tasks
*/
var downloadTaskResult: Boolean = true
/**
* Progress values posted by all download task mocks before
* returning result value
*/
var taskProgress = listOf<Int>()
@Before
fun setUpBase() {
MockKAnnotations.init(this, relaxed = true)
MockitoAnnotations.initMocks(this)
downloadTaskMocks = mutableListOf()
runner = ManualAsyncRunner()
transferManager = TransferManagerImpl(
runner = runner,
taskFactory = mockTaskFactory,
threads = MAX_TRANSFER_THREADS
)
downloadTaskResult = true
every { mockTaskFactory.create() } answers { createMockTask() }
}
private fun createMockTask(): DownloadTask {
val task = mockk<DownloadTask>()
every { task.download(any(), any(), any()) } answers {
taskProgress.forEach {
arg<OnProgressCallback<Int>>(1).invoke(it)
}
val request = arg<Request>(0)
DownloadTask.Result(request.file, downloadTaskResult)
}
downloadTaskMocks.add(task)
return task
}
}
class Enqueue : Base() {
@Test
fun enqueued_download_is_started_immediately() {
// GIVEN
// downloader has no running downloads
// WHEN
// download is enqueued
val file = OCFile("/path")
val request = Request(user, file)
transferManager.enqueue(request)
// THEN
// download is started immediately
val download = transferManager.getTransfer(request.uuid)
assertEquals(TransferState.RUNNING, download?.state)
}
@Test
fun enqueued_downloads_are_pending_if_running_queue_is_full() {
// GIVEN
// downloader is downloading max simultaneous files
for (i in 0 until MAX_TRANSFER_THREADS) {
val file = OCFile("/running/download/path/$i")
val request = Request(user, file)
transferManager.enqueue(request)
val runningDownload = transferManager.getTransfer(request.uuid)
assertEquals(runningDownload?.state, TransferState.RUNNING)
}
// WHEN
// another download is enqueued
val file = OCFile("/path")
val request = Request(user, file)
transferManager.enqueue(request)
// THEN
// download is pending
val download = transferManager.getTransfer(request.uuid)
assertEquals(TransferState.PENDING, download?.state)
}
}
class TransferStatusUpdates : Base() {
@get:Rule
val rule = InstantTaskExecutorRule()
val file = OCFile("/path")
@Test
fun download_task_completes() {
// GIVEN
// download is running
// download is being observed
val downloadUpdates = mutableListOf<Transfer>()
transferManager.registerTransferListener { downloadUpdates.add(it) }
transferManager.enqueue(Request(user, file))
// WHEN
// download task finishes successfully
runner.runOne()
// THEN
// listener is notified about status change
assertEquals(TransferState.RUNNING, downloadUpdates[0].state)
assertEquals(TransferState.COMPLETED, downloadUpdates[1].state)
}
@Test
fun download_task_fails() {
// GIVEN
// download is running
// download is being observed
val downloadUpdates = mutableListOf<Transfer>()
transferManager.registerTransferListener { downloadUpdates.add(it) }
transferManager.enqueue(Request(user, file))
// WHEN
// download task fails
downloadTaskResult = false
runner.runOne()
// THEN
// listener is notified about status change
assertEquals(TransferState.RUNNING, downloadUpdates[0].state)
assertEquals(TransferState.FAILED, downloadUpdates[1].state)
}
@Test
fun download_progress_is_updated() {
// GIVEN
// download is running
val downloadUpdates = mutableListOf<Transfer>()
transferManager.registerTransferListener { downloadUpdates.add(it) }
transferManager.enqueue(Request(user, file))
// WHEN
// download progress updated 4 times before completion
taskProgress = listOf(25, 50, 75, 100)
runner.runOne()
// THEN
// listener receives 6 status updates
// transition to running
// 4 progress updates
// completion
assertEquals(6, downloadUpdates.size)
if (downloadUpdates.size >= 6) {
assertEquals(TransferState.RUNNING, downloadUpdates[0].state)
assertEquals(25, downloadUpdates[1].progress)
assertEquals(50, downloadUpdates[2].progress)
assertEquals(75, downloadUpdates[3].progress)
assertEquals(100, downloadUpdates[4].progress)
assertEquals(TransferState.COMPLETED, downloadUpdates[5].state)
}
}
@Test
fun download_task_is_created_only_for_running_downloads() {
// WHEN
// multiple downloads are enqueued
for (i in 0 until MAX_TRANSFER_THREADS * 2) {
transferManager.enqueue(Request(user, file))
}
// THEN
// download task is created only for running downloads
assertEquals(MAX_TRANSFER_THREADS, downloadTaskMocks.size)
}
}
class RunningStatusUpdates : Base() {
@get:Rule
val rule = InstantTaskExecutorRule()
@Test
fun is_running_flag_on_enqueue() {
// WHEN
// download is enqueued
val file = OCFile("/path/to/file")
val request = Request(user, file)
transferManager.enqueue(request)
// THEN
// is running changes
assertTrue(transferManager.isRunning)
}
@Test
fun is_running_flag_on_completion() {
// GIVEN
// a download is in progress
val file = OCFile("/path/to/file")
val request = Request(user, file)
transferManager.enqueue(request)
assertTrue(transferManager.isRunning)
// WHEN
// download is processed
runner.runOne()
// THEN
// downloader is not running
assertFalse(transferManager.isRunning)
}
}
}
@@ -1,96 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.jobs
import android.Manifest
import androidx.test.rule.GrantPermissionRule
import androidx.work.WorkManager
import com.nextcloud.client.core.ClockImpl
import com.owncloud.android.AbstractIT
import com.owncloud.android.AbstractOnServerIT
import com.owncloud.android.R
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.operations.DownloadFileOperation
import ezvcard.Ezvcard
import ezvcard.VCard
import junit.framework.Assert.assertEquals
import junit.framework.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import java.io.File
class ContactsBackupIT : AbstractOnServerIT() {
val workmanager = WorkManager.getInstance(targetContext)
private val backgroundJobManager = BackgroundJobManagerImpl(workmanager, ClockImpl())
@get:Rule
val writeContactsRule = GrantPermissionRule.grant(Manifest.permission.WRITE_CONTACTS)
@get:Rule
val readContactsRule = GrantPermissionRule.grant(Manifest.permission.READ_CONTACTS)
private val vcard: String = "vcard.vcf"
@Test
fun importExport() {
val intArray = IntArray(1)
intArray[0] = 0
// import file to local contacts
backgroundJobManager.startImmediateContactsImport(null, null, getFile(vcard).absolutePath, intArray)
shortSleep()
// export contact
backgroundJobManager.startImmediateContactsBackup(user)
longSleep()
val backupFolder: String = targetContext.resources.getString(R.string.contacts_backup_folder) +
OCFile.PATH_SEPARATOR
refreshFolder("/")
longSleep()
refreshFolder(backupFolder)
longSleep()
val backupOCFile = storageManager.getFolderContent(
storageManager.getFileByDecryptedRemotePath(backupFolder),
false
)[0]
assertTrue(DownloadFileOperation(account, backupOCFile, AbstractIT.targetContext).execute(client).isSuccess)
val backupFile = File(backupOCFile.storagePath)
// verify same
val originalCards: ArrayList<VCard> = ArrayList()
originalCards.addAll(Ezvcard.parse(getFile(vcard)).all())
val backupCards: ArrayList<VCard> = ArrayList()
backupCards.addAll(Ezvcard.parse(backupFile).all())
assertEquals(originalCards.size, backupCards.size)
assertEquals(originalCards[0].formattedName.toString(), backupCards[0].formattedName.toString())
}
}
@@ -7,12 +7,9 @@ import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import com.facebook.testing.screenshot.Screenshot;
import com.facebook.testing.screenshot.internal.TestNameDetector;
import com.nextcloud.client.RetryTestRule;
import com.nextcloud.client.account.User;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.account.UserAccountManagerImpl;
@@ -20,8 +17,6 @@ import com.nextcloud.client.device.BatteryStatus;
import com.nextcloud.client.device.PowerManagementService;
import com.nextcloud.client.network.Connectivity;
import com.nextcloud.client.network.ConnectivityService;
import com.nextcloud.client.preferences.AppPreferencesImpl;
import com.nextcloud.client.preferences.DarkMode;
import com.nextcloud.java.util.Optional;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
@@ -32,7 +27,6 @@ import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.OwnCloudClientFactory;
import com.owncloud.android.lib.common.accounts.AccountUtils;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.resources.status.OCCapability;
import com.owncloud.android.operations.CreateFolderOperation;
import com.owncloud.android.operations.UploadFileOperation;
import com.owncloud.android.utils.FileStorageUtils;
@@ -41,6 +35,7 @@ import junit.framework.TestCase;
import org.apache.commons.io.FileUtils;
import org.junit.BeforeClass;
import org.junit.Rule;
import java.io.File;
import java.io.FileWriter;
@@ -66,14 +61,12 @@ import static org.junit.Assert.assertTrue;
*/
public abstract class AbstractIT {
//@Rule public RetryTestRule retryTestRule = new RetryTestRule();
@Rule public RetryTestRule retryTestRule = new RetryTestRule();
protected static OwnCloudClient client;
protected static Account account;
protected static User user;
protected static Context targetContext;
protected static String DARK_MODE = "";
protected static String COLOR = "";
protected Activity currentActivity;
@@ -88,9 +81,7 @@ public abstract class AbstractIT {
AccountManager platformAccountManager = AccountManager.get(targetContext);
for (Account account : platformAccountManager.getAccounts()) {
if (account.type.equalsIgnoreCase("nextcloud")) {
platformAccountManager.removeAccountExplicitly(account);
}
platformAccountManager.removeAccountExplicitly(account);
}
Account temp = new Account("test@https://server.com", MainApp.getAccountType(targetContext));
@@ -118,63 +109,6 @@ public abstract class AbstractIT {
} catch (AccountUtils.AccountNotFoundException e) {
e.printStackTrace();
}
Bundle arguments = androidx.test.platform.app.InstrumentationRegistry.getArguments();
// color
String colorParameter = arguments.getString("COLOR");
if (!TextUtils.isEmpty(colorParameter)) {
FileDataStorageManager fileDataStorageManager = new FileDataStorageManager(account,
targetContext.getContentResolver());
String colorHex = null;
COLOR = colorParameter;
switch (colorParameter) {
case "red":
colorHex = "#7c0000";
break;
case "green":
colorHex = "#00ff00";
break;
case "white":
colorHex = "#ffffff";
break;
case "black":
colorHex = "#000000";
break;
default:
break;
}
if (colorHex != null) {
OCCapability capability = fileDataStorageManager.getCapability(account.name);
capability.setServerColor(colorHex);
fileDataStorageManager.saveCapabilities(capability);
}
}
// dark / light
String darkModeParameter = arguments.getString("DARKMODE");
if (darkModeParameter != null) {
if (darkModeParameter.equalsIgnoreCase("dark")) {
DARK_MODE = "dark";
AppPreferencesImpl.fromContext(targetContext).setDarkThemeMode(DarkMode.DARK);
MainApp.setAppTheme(DarkMode.DARK);
} else {
DARK_MODE = "light";
}
}
if (DARK_MODE.equalsIgnoreCase("light") && COLOR.equalsIgnoreCase("blue")) {
// use already existing names
DARK_MODE = "";
COLOR = "";
}
}
protected FileDataStorageManager getStorageManager() {
@@ -185,48 +119,8 @@ public abstract class AbstractIT {
return AccountManager.get(targetContext).getAccounts();
}
protected static void createDummyFiles() throws IOException {
File tempPath = new File(FileStorageUtils.getTemporalPath(account.name));
if (!tempPath.exists()) {
assertTrue(tempPath.mkdirs());
}
assertTrue(tempPath.exists());
createFile("empty.txt", 0);
createFile("nonEmpty.txt", 100);
createFile("chunkedFile.txt", 500000);
}
protected static File getDummyFile(String name) throws IOException {
File file = new File(FileStorageUtils.getTemporalPath(account.name) + File.pathSeparator + name);
if (file.exists()) {
return file;
} else {
switch (name) {
case "empty.txt":
return createFile("empty.txt", 0);
case "nonEmpty.txt":
return createFile("nonEmpty.txt", 100);
case "chunkedFile.txt":
return createFile("chunkedFile.txt", 500000);
default:
return createFile(name, 0);
}
}
}
public static File createFile(String name, int iteration) throws IOException {
File tempPath = new File(FileStorageUtils.getTemporalPath(account.name));
if (!tempPath.exists()) {
assertTrue(tempPath.mkdirs());
}
File file = new File(FileStorageUtils.getTemporalPath(account.name) + File.separator + name);
public static void createFile(String name, int iteration) throws IOException {
File file = new File(FileStorageUtils.getSavePath(account.name) + File.separator + name);
file.createNewFile();
FileWriter writer = new FileWriter(file);
@@ -236,8 +130,6 @@ public abstract class AbstractIT {
}
writer.flush();
writer.close();
return file;
}
protected File getFile(String filename) throws IOException {
@@ -261,7 +153,7 @@ public abstract class AbstractIT {
waitForIdleSync();
screenshot(sut);
Screenshot.snapActivity(sut).record();
}
protected Activity getCurrentActivity() {
@@ -359,26 +251,4 @@ public abstract class AbstractIT {
RemoteOperationResult result = newUpload.execute(client, getStorageManager());
assertTrue(result.getLogMessage(), result.isSuccess());
}
protected void screenshot(View view) {
Screenshot.snap(view).setName(createName()).record();
}
protected void screenshot(Activity sut) {
Screenshot.snapActivity(sut).setName(createName()).record();
}
private String createName() {
String name = TestNameDetector.getTestClass() + "_" + TestNameDetector.getTestName();
if (!DARK_MODE.isEmpty()) {
name = name + "_" + DARK_MODE;
}
if (!COLOR.isEmpty()) {
name = name + "_" + COLOR;
}
return name;
}
}
@@ -16,7 +16,6 @@ import com.nextcloud.client.device.PowerManagementService;
import com.nextcloud.client.network.Connectivity;
import com.nextcloud.client.network.ConnectivityService;
import com.nextcloud.java.util.Optional;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.datamodel.UploadsStorageManager;
import com.owncloud.android.db.OCUpload;
import com.owncloud.android.files.services.FileUploader;
@@ -28,8 +27,8 @@ import com.owncloud.android.lib.resources.e2ee.ToggleEncryptionRemoteOperation;
import com.owncloud.android.lib.resources.files.ReadFolderRemoteOperation;
import com.owncloud.android.lib.resources.files.RemoveFileRemoteOperation;
import com.owncloud.android.lib.resources.files.model.RemoteFile;
import com.owncloud.android.operations.RefreshFolderOperation;
import com.owncloud.android.operations.UploadFileOperation;
import com.owncloud.android.utils.FileStorageUtils;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
@@ -38,12 +37,12 @@ import org.junit.Assert;
import org.junit.BeforeClass;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import androidx.annotation.NonNull;
import androidx.test.platform.app.InstrumentationRegistry;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@@ -60,9 +59,7 @@ public abstract class AbstractOnServerIT extends AbstractIT {
AccountManager platformAccountManager = AccountManager.get(targetContext);
for (Account account : platformAccountManager.getAccounts()) {
if (account.type.equalsIgnoreCase("nextcloud")) {
platformAccountManager.removeAccountExplicitly(account);
}
platformAccountManager.removeAccountExplicitly(account);
}
Bundle arguments = androidx.test.platform.app.InstrumentationRegistry.getArguments();
@@ -140,6 +137,27 @@ public abstract class AbstractOnServerIT extends AbstractIT {
}
}
private static void createDummyFiles() throws IOException {
new File(FileStorageUtils.getSavePath(account.name)).mkdirs();
createFile("empty.txt", 0);
createFile("nonEmpty.txt", 100);
createFile("chunkedFile.txt", 500000);
}
public static void createFile(String name, int iteration) throws IOException {
File file = new File(FileStorageUtils.getSavePath(account.name) + File.separator + name);
file.createNewFile();
FileWriter writer = new FileWriter(file);
for (int i = 0; i < iteration; i++) {
writer.write("123123123123123123123123123\n");
}
writer.flush();
writer.close();
}
private static void waitForServer(OwnCloudClient client, Uri baseUrl) {
GetMethod get = new GetMethod(baseUrl + "/status.php");
@@ -163,10 +181,6 @@ public abstract class AbstractOnServerIT extends AbstractIT {
}
public void uploadOCUpload(OCUpload ocUpload) {
uploadOCUpload(ocUpload, FileUploader.LOCAL_BEHAVIOUR_COPY);
}
public void uploadOCUpload(OCUpload ocUpload, int localBehaviour) {
ConnectivityService connectivityServiceMock = new ConnectivityService() {
@Override
public boolean isInternetWalled() {
@@ -209,7 +223,7 @@ public abstract class AbstractOnServerIT extends AbstractIT {
null,
ocUpload,
FileUploader.NameCollisionPolicy.DEFAULT,
localBehaviour,
FileUploader.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false
@@ -222,29 +236,5 @@ public abstract class AbstractOnServerIT extends AbstractIT {
RemoteOperationResult result = newUpload.execute(client, getStorageManager());
assertTrue(result.getLogMessage(), result.isSuccess());
OCFile parentFolder = getStorageManager()
.getFileByEncryptedRemotePath(new File(ocUpload.getRemotePath()).getParent() + "/");
String uploadedFileName = new File(ocUpload.getRemotePath()).getName();
OCFile uploadedFile = getStorageManager().
getFileByDecryptedRemotePath(parentFolder.getDecryptedRemotePath() + uploadedFileName);
assertNotNull(uploadedFile.getRemoteId());
if (localBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY ||
localBehaviour == FileUploader.LOCAL_BEHAVIOUR_MOVE) {
assertTrue(new File(uploadedFile.getStoragePath()).exists());
}
}
protected void refreshFolder(String path) {
assertTrue(new RefreshFolderOperation(getStorageManager().getFileByEncryptedRemotePath(path),
System.currentTimeMillis(),
false,
false,
getStorageManager(),
account,
targetContext
).execute(client).isSuccess());
}
}
@@ -1,121 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android;
import android.net.Uri;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.db.OCUpload;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.operations.DownloadFileOperation;
import com.owncloud.android.operations.RefreshFolderOperation;
import com.owncloud.android.operations.RemoveFileOperation;
import com.owncloud.android.utils.FileStorageUtils;
import org.junit.After;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
/**
* Tests related to file uploads
*/
public class DownloadIT extends AbstractOnServerIT {
private static final String FOLDER = "/testUpload/";
@After
public void after() {
RemoteOperationResult result = new RefreshFolderOperation(getStorageManager().getFileByPath("/"),
System.currentTimeMillis() / 1000L,
false,
true,
getStorageManager(),
account,
targetContext)
.execute(client);
// cleanup only if folder exists
if (result.isSuccess() && getStorageManager().getFileByDecryptedRemotePath(FOLDER) != null) {
new RemoveFileOperation(getStorageManager().getFileByDecryptedRemotePath(FOLDER),
false,
account,
false,
targetContext)
.execute(client, getStorageManager());
}
}
@Test
public void verifyDownload() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
FOLDER + "nonEmpty.txt",
account.name);
uploadOCUpload(ocUpload);
OCUpload ocUpload2 = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
FOLDER + "nonEmpty2.txt",
account.name);
uploadOCUpload(ocUpload2);
refreshFolder("/");
refreshFolder(FOLDER);
OCFile file1 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt");
OCFile file2 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty2.txt");
verifyDownload(file1, file2);
assertTrue(new DownloadFileOperation(account, file1, targetContext).execute(client).isSuccess());
assertTrue(new DownloadFileOperation(account, file2, targetContext).execute(client).isSuccess());
refreshFolder(FOLDER);
file1 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt");
file2 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty2.txt");
verifyDownload(file1, file2);
}
private void verifyDownload(OCFile file1, OCFile file2) {
assertNotNull(file1);
assertNotNull(file2);
assertNotSame(file1.getStoragePath(), file2.getStoragePath());
assertTrue(new File(file1.getStoragePath()).exists());
assertTrue(new File(file2.getStoragePath()).exists());
// test against hardcoded path to make sure that it is correct
assertEquals("/storage/emulated/0/Android/media/com.nextcloud.client/nextcloud/" +
Uri.encode(account.name, "@") + "/testUpload/nonEmpty.txt",
file1.getStoragePath());
assertEquals("/storage/emulated/0/Android/media/com.nextcloud.client/nextcloud/" +
Uri.encode(account.name, "@") + "/testUpload/nonEmpty2.txt",
file2.getStoragePath());
}
}
@@ -7,7 +7,6 @@ import com.owncloud.android.operations.CreateFolderOperation;
import com.owncloud.android.operations.common.SyncOperation;
import com.owncloud.android.ui.activity.FileDisplayActivity;
import com.owncloud.android.ui.activity.SettingsActivity;
import com.owncloud.android.ui.activity.SyncedFoldersActivity;
import org.junit.Assert;
import org.junit.BeforeClass;
@@ -32,6 +31,7 @@ import static androidx.test.espresso.Espresso.onData;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.Espresso.pressBack;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.swipeUp;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.core.AnyOf.anyOf;
@@ -72,7 +72,7 @@ public class ScreenshotsIT extends AbstractOnServerIT {
String path = "/Camera/";
// folder does not exist yet
if (getStorageManager().getFileByEncryptedRemotePath(path) == null) {
if (getStorageManager().getFileByPath(path) == null) {
SyncOperation syncOp = new CreateFolderOperation(path, user, targetContext);
RemoteOperationResult result = syncOp.execute(client, getStorageManager());
@@ -117,7 +117,11 @@ public class ScreenshotsIT extends AbstractOnServerIT {
@Test
public void autoUploadScreenshot() {
ActivityScenario.launch(SyncedFoldersActivity.class);
ActivityScenario.launch(FileDisplayActivity.class);
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(swipeUp());
onView(anyOf(withText(R.string.drawer_synced_folders), withId(R.id.nav_synced_folders))).perform(click());
Screengrab.screenshot("05_autoUpload");
@@ -26,22 +26,24 @@ import com.nextcloud.client.device.BatteryStatus;
import com.nextcloud.client.device.PowerManagementService;
import com.nextcloud.client.network.Connectivity;
import com.nextcloud.client.network.ConnectivityService;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.datamodel.UploadsStorageManager;
import com.owncloud.android.db.OCUpload;
import com.owncloud.android.files.services.FileUploader;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation;
import com.owncloud.android.lib.resources.files.model.RemoteFile;
import com.owncloud.android.operations.RefreshFolderOperation;
import com.owncloud.android.operations.RemoveFileOperation;
import com.owncloud.android.operations.UploadFileOperation;
import com.owncloud.android.utils.FileStorageUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import androidx.annotation.NonNull;
@@ -90,12 +92,6 @@ public class UploadIT extends AbstractOnServerIT {
}
};
@Before
public void before() throws IOException {
// make sure that every file is available, even after tests that remove source file
createDummyFiles();
}
@After
public void after() {
RemoteOperationResult result = new RefreshFolderOperation(getStorageManager().getFileByPath("/"),
@@ -120,7 +116,7 @@ public class UploadIT extends AbstractOnServerIT {
@Test
public void testEmptyUpload() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt",
FOLDER + "empty.txt",
account.name);
@@ -129,95 +125,54 @@ public class UploadIT extends AbstractOnServerIT {
@Test
public void testNonEmptyUpload() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt",
FOLDER + "nonEmpty.txt",
account.name);
uploadOCUpload(ocUpload);
}
@Test
public void testUploadWithCopy() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
FOLDER + "nonEmpty.txt",
account.name);
uploadOCUpload(ocUpload, FileUploader.LOCAL_BEHAVIOUR_COPY);
File originalFile = new File(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt");
OCFile uploadedFile = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt");
assertTrue(originalFile.exists());
assertTrue(new File(uploadedFile.getStoragePath()).exists());
verifyStoragePath(uploadedFile);
}
@Test
public void testUploadWithMove() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
FOLDER + "nonEmpty.txt",
account.name);
uploadOCUpload(ocUpload, FileUploader.LOCAL_BEHAVIOUR_MOVE);
File originalFile = new File(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt");
OCFile uploadedFile = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt");
assertFalse(originalFile.exists());
assertTrue(new File(uploadedFile.getStoragePath()).exists());
verifyStoragePath(uploadedFile);
}
@Test
public void testUploadWithForget() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
FOLDER + "nonEmpty.txt",
account.name);
uploadOCUpload(ocUpload, FileUploader.LOCAL_BEHAVIOUR_FORGET);
File originalFile = new File(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt");
OCFile uploadedFile = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt");
assertTrue(originalFile.exists());
assertFalse(new File(uploadedFile.getStoragePath()).exists());
assertTrue(uploadedFile.getStoragePath().isEmpty());
}
@Test
public void testUploadWithDelete() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
FOLDER + "nonEmpty.txt",
account.name);
uploadOCUpload(ocUpload, FileUploader.LOCAL_BEHAVIOUR_DELETE);
File originalFile = new File(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt");
OCFile uploadedFile = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt");
assertFalse(originalFile.exists());
assertFalse(new File(uploadedFile.getStoragePath()).exists());
assertTrue(uploadedFile.getStoragePath().isEmpty());
}
@Test
public void testChunkedUpload() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/chunkedFile.txt",
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/chunkedFile.txt",
FOLDER + "chunkedFile.txt", account.name);
uploadOCUpload(ocUpload);
}
public RemoteOperationResult testUpload(OCUpload ocUpload) {
UploadFileOperation newUpload = new UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
user,
null,
ocUpload,
FileUploader.NameCollisionPolicy.DEFAULT,
FileUploader.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false
);
newUpload.addRenameUploadListener(() -> {
// dummy
});
newUpload.setRemoteFolderToBeCreated();
return newUpload.execute(client, getStorageManager());
}
@Test
public void testUploadInNonExistingFolder() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt",
FOLDER + "2/3/4/1.txt", account.name);
uploadOCUpload(ocUpload);
}
@Test
public void testUploadOnChargingOnlyButNotCharging() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt",
FOLDER + "notCharging.txt", account.name);
ocUpload.setWhileChargingOnly(true);
@@ -263,7 +218,7 @@ public class UploadIT extends AbstractOnServerIT {
}
};
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt",
FOLDER + "charging.txt", account.name);
ocUpload.setWhileChargingOnly(true);
@@ -302,7 +257,7 @@ public class UploadIT extends AbstractOnServerIT {
return new Connectivity(true, false, false, true);
}
};
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt",
FOLDER + "noWifi.txt", account.name);
ocUpload.setUseWifiOnly(true);
@@ -330,7 +285,7 @@ public class UploadIT extends AbstractOnServerIT {
@Test
public void testUploadOnWifiOnlyAndWifi() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt",
FOLDER + "wifi.txt", account.name);
ocUpload.setWhileChargingOnly(true);
@@ -364,8 +319,22 @@ public class UploadIT extends AbstractOnServerIT {
.execute(client, getStorageManager());
}
private void verifyStoragePath(OCFile file) {
assertEquals(FileStorageUtils.getSavePath(account.name) + FOLDER + file.getDecryptedFileName(),
file.getStoragePath());
@Test
public void testUploadSameModificationDate() throws IOException {
File file = new File(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt");
BasicFileAttributes attributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
long modifiedDate = attributes.lastModifiedTime().toMillis();
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt",
FOLDER + "nonEmpty.txt",
account.name);
shortSleep();
uploadOCUpload(ocUpload);
RemoteOperationResult readFileResult = new ReadFileRemoteOperation(FOLDER + "nonEmpty.txt").execute(client);
RemoteFile remoteFile = (RemoteFile) readFileResult.getData().get(0);
assertEquals(modifiedDate, remoteFile.getModifiedTimestamp());
}
}
@@ -1,77 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.authentication
import android.graphics.Color
import org.junit.Assert
import org.junit.Test
class AuthenticatorActivityIT {
@Test(expected = IndexOutOfBoundsException::class)
fun testException() {
Color.parseColor("")
}
@Test
fun tryCatch() {
val color = try {
Color.parseColor("1")
} catch (e: Exception) {
Color.BLACK
}
Assert.assertNotNull(color)
}
@Test
fun tryCatch2() {
val color = try {
Color.parseColor("")
} catch (e: Exception) {
Color.BLACK
}
Assert.assertNotNull(color)
}
@Test
fun tryCatch3() {
val color = try {
Color.parseColor(null)
} catch (e: Exception) {
Color.BLACK
}
Assert.assertNotNull(color)
}
@Test
fun tryCatch4() {
val color = try {
Color.parseColor("abc")
} catch (e: Exception) {
Color.BLACK
}
Assert.assertNotNull(color)
}
}
@@ -26,7 +26,5 @@ public class FileDataStorageManagerContentResolverTest extends FileDataStorageMa
@Override
public void before() {
sut = new FileDataStorageManager(account, targetContext.getContentResolver());
super.before();
}
}
@@ -55,13 +55,7 @@ abstract public class FileDataStorageManagerTest extends AbstractOnServerIT {
protected FileDataStorageManager sut;
@Before
public void before() {
// make sure everything is removed
sut.deleteAllFiles();
sut.deleteVirtuals(VirtualFolderType.PHOTOS);
assertEquals(0, sut.getAllFiles().size());
}
abstract public void before();
@After
public void after() {
@@ -89,13 +83,13 @@ abstract public class FileDataStorageManagerTest extends AbstractOnServerIT {
assertTrue(new CreateFolderRemoteOperation("/1/2/", true).execute(client).isSuccess());
assertTrue(new UploadFileRemoteOperation(getDummyFile("/chunkedFile.txt").getAbsolutePath(),
assertTrue(new UploadFileRemoteOperation(FileStorageUtils.getSavePath(account.name) + "/chunkedFile.txt",
"/1/1/chunkedFile.txt",
"text/plain",
String.valueOf(System.currentTimeMillis() / 1000))
.execute(client).isSuccess());
assertTrue(new UploadFileRemoteOperation(getDummyFile("/chunkedFile.txt").getAbsolutePath(),
assertTrue(new UploadFileRemoteOperation(FileStorageUtils.getSavePath(account.name) + "/chunkedFile.txt",
"/1/1/chunkedFile2.txt",
"text/plain",
String.valueOf(System.currentTimeMillis() / 1000))
@@ -28,9 +28,9 @@ import java.io.File;
import java.util.ArrayList;
import java.util.Random;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.InstrumentationRegistry;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -49,7 +49,7 @@ public class UploadStorageManagerTest extends AbstractIT {
@Before
public void setUp() {
Context instrumentationCtx = ApplicationProvider.getApplicationContext();
Context instrumentationCtx = InstrumentationRegistry.getTargetContext();
ContentResolver contentResolver = instrumentationCtx.getContentResolver();
uploadsStorageManager = new UploadsStorageManager(currentAccountProvider, contentResolver);
@@ -94,7 +94,6 @@ public class UploadStorageManagerTest extends AbstractIT {
int size = 3000;
ArrayList<OCUpload> uploads = new ArrayList<>();
deleteAllUploads();
assertEquals(0, uploadsStorageManager.getAllStoredUploads().length);
for (int i = 0; i < size; i++) {
@@ -157,14 +156,8 @@ public class UploadStorageManagerTest extends AbstractIT {
}
private OCUpload createUpload(Account account) {
OCUpload upload = new OCUpload(File.separator + "very long long long long long long long long long long long " +
"long long long long long long long long long long long long long long " +
"long long long long long long long long long long long long long long " +
"long long long long long long long LocalPath",
OCFile.PATH_SEPARATOR + "very long long long long long long long long long " +
"long long long long long long long long long long long long long long " +
"long long long long long long long long long long long long long long " +
"long long long long long long long long long long long long RemotePath",
OCUpload upload = new OCUpload(File.separator + "very long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long LocalPath",
OCFile.PATH_SEPARATOR + "very long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long RemotePath",
account.name);
upload.setFileSize(new Random().nextInt(20000) * 10000);
@@ -182,15 +175,11 @@ public class UploadStorageManagerTest extends AbstractIT {
return upload;
}
private void deleteAllUploads() {
uploadsStorageManager.removeAllUploads();
assertEquals(0, uploadsStorageManager.getAllStoredUploads().length);
}
@After
public void tearDown() {
deleteAllUploads();
for (Account account : getAllAccounts()) {
uploadsStorageManager.removeAccountUploads(account);
}
AccountManager platformAccountManager = AccountManager.get(targetContext);
platformAccountManager.removeAccountExplicitly(account2);
@@ -35,11 +35,13 @@ import com.owncloud.android.db.OCUpload
import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation
import com.owncloud.android.lib.resources.files.model.RemoteFile
import com.owncloud.android.operations.UploadFileOperation
import com.owncloud.android.utils.FileStorageUtils.getSavePath
import junit.framework.Assert.assertEquals
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import java.io.File
class FileUploaderIT : AbstractOnServerIT() {
var uploadsStorageManager: UploadsStorageManager? = null
@@ -72,7 +74,7 @@ class FileUploaderIT : AbstractOnServerIT() {
*/
@Test
fun testKeepLocalAndOverwriteRemote() {
val file = getDummyFile("/chunkedFile.txt")
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
val ocUpload = OCUpload(file.absolutePath, "/testFile.txt", account.name)
assertTrue(
@@ -99,7 +101,7 @@ class FileUploaderIT : AbstractOnServerIT() {
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocUpload2 = OCUpload(getDummyFile("/empty.txt").absolutePath, "/testFile.txt", account.name)
val ocUpload2 = OCUpload(getSavePath(account.name) + "/empty.txt", "/testFile.txt", account.name)
assertTrue(
UploadFileOperation(
@@ -130,7 +132,7 @@ class FileUploaderIT : AbstractOnServerIT() {
*/
@Test
fun testKeepLocalAndOverwriteRemoteStatic() {
val file = getDummyFile("/chunkedFile.txt")
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
FileUploader.uploadNewFile(
targetContext,
@@ -154,7 +156,7 @@ class FileUploaderIT : AbstractOnServerIT() {
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocFile2 = OCFile("/testFile.txt")
ocFile2.setStoragePath(getDummyFile("/empty.txt").absolutePath)
ocFile2.setStoragePath(getSavePath(account.name) + "/empty.txt")
FileUploader.uploadUpdateFile(
targetContext,
@@ -179,7 +181,7 @@ class FileUploaderIT : AbstractOnServerIT() {
fun testKeepBoth() {
var renameListenerWasTriggered = false
val file = getDummyFile("/chunkedFile.txt")
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
val ocUpload = OCUpload(file.absolutePath, "/testFile.txt", account.name)
assertTrue(
@@ -206,7 +208,7 @@ class FileUploaderIT : AbstractOnServerIT() {
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val file2 = getDummyFile("empty.txt")
val file2 = File(getSavePath(account.name) + "/empty.txt")
val ocUpload2 = OCUpload(file2.absolutePath, "/testFile.txt", account.name)
assertTrue(
@@ -247,7 +249,7 @@ class FileUploaderIT : AbstractOnServerIT() {
*/
@Test
fun testKeepBothStatic() {
val file = getDummyFile("/chunkedFile.txt")
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
FileUploader.uploadNewFile(
targetContext,
@@ -271,7 +273,7 @@ class FileUploaderIT : AbstractOnServerIT() {
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocFile2 = OCFile("/testFile.txt")
ocFile2.setStoragePath(getDummyFile("/empty.txt").absolutePath)
ocFile2.setStoragePath(getSavePath(account.name) + "/empty.txt")
FileUploader.uploadUpdateFile(
targetContext,
@@ -299,7 +301,7 @@ class FileUploaderIT : AbstractOnServerIT() {
*/
@Test
fun testKeepServer() {
val file = getDummyFile("/chunkedFile.txt")
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
val ocUpload = OCUpload(file.absolutePath, "/testFile.txt", account.name)
assertTrue(
@@ -326,7 +328,7 @@ class FileUploaderIT : AbstractOnServerIT() {
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocUpload2 = OCUpload(getDummyFile("/empty.txt").absolutePath, "/testFile.txt", account.name)
val ocUpload2 = OCUpload(getSavePath(account.name) + "/empty.txt", "/testFile.txt", account.name)
assertFalse(
UploadFileOperation(
@@ -356,7 +358,7 @@ class FileUploaderIT : AbstractOnServerIT() {
*/
@Test
fun testKeepServerStatic() {
val file = getDummyFile("/chunkedFile.txt")
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
FileUploader.uploadNewFile(
targetContext,
@@ -380,7 +382,7 @@ class FileUploaderIT : AbstractOnServerIT() {
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocFile2 = OCFile("/testFile.txt")
ocFile2.setStoragePath(getDummyFile("/empty.txt").absolutePath)
ocFile2.setStoragePath(getSavePath(account.name) + "/empty.txt")
FileUploader.uploadUpdateFile(
targetContext,
@@ -1,99 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.operations;
import com.owncloud.android.AbstractOnServerIT;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.db.OCUpload;
import org.junit.Test;
import java.io.IOException;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertTrue;
public class RemoveFileOperationIT extends AbstractOnServerIT {
@Test
public void deleteFolder() {
String parent = "/test/";
String path = parent + "folder1/";
assertTrue(new CreateFolderOperation(path, user, targetContext).execute(client, getStorageManager())
.isSuccess());
OCFile folder = getStorageManager().getFileByPath(path);
assertNotNull(folder);
assertTrue(new RemoveFileOperation(folder,
false,
account,
false,
targetContext)
.execute(client, getStorageManager())
.isSuccess());
OCFile parentFolder = getStorageManager().getFileByPath(parent);
assertNotNull(parentFolder);
assertTrue(new RemoveFileOperation(parentFolder,
false,
account,
false,
targetContext)
.execute(client, getStorageManager())
.isSuccess());
}
@Test
public void deleteFile() throws IOException {
String parent = "/test/";
String path = parent + "empty.txt";
OCUpload ocUpload = new OCUpload(getDummyFile("/empty.txt").getAbsolutePath(), path, account.name);
uploadOCUpload(ocUpload);
OCFile file = getStorageManager().getFileByPath(path);
assertNotNull(file);
assertTrue(new RemoveFileOperation(file,
false,
account,
false,
targetContext)
.execute(client, getStorageManager())
.isSuccess());
OCFile parentFolder = getStorageManager().getFileByPath(parent);
assertNotNull(parentFolder);
assertTrue(new RemoveFileOperation(parentFolder,
false,
account,
false,
targetContext)
.execute(client, getStorageManager())
.isSuccess());
}
}
@@ -1,135 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui;
import android.Manifest;
import android.accounts.Account;
import android.content.Context;
import android.os.Bundle;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.account.UserAccountManagerImpl;
import com.owncloud.android.R;
import com.owncloud.android.authentication.AuthenticatorActivity;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import androidx.test.core.app.ActivityScenario;
import androidx.test.espresso.web.webdriver.DriverAtoms;
import androidx.test.espresso.web.webdriver.Locator;
import androidx.test.filters.LargeTest;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.GrantPermissionRule;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.web.sugar.Web.onWebView;
import static androidx.test.espresso.web.webdriver.DriverAtoms.findElement;
import static androidx.test.espresso.web.webdriver.DriverAtoms.webClick;
import static org.junit.Assert.assertEquals;
@LargeTest
public class LoginIT {
@Rule
public GrantPermissionRule permissionRule = GrantPermissionRule.grant(Manifest.permission.WRITE_EXTERNAL_STORAGE);
@Before
public void setUp() {
tearDown();
ActivityScenario.launch(AuthenticatorActivity.class);
}
@AfterClass
public static void tearDown() {
Context targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
if (accountManager.getAccounts().length > 0) {
accountManager.removeAllAccounts();
}
}
@Test
public void login() throws InterruptedException {
Bundle arguments = androidx.test.platform.app.InstrumentationRegistry.getArguments();
String baseUrl = arguments.getString("TEST_SERVER_URL");
String loginName = arguments.getString("TEST_SERVER_USERNAME");
String password = arguments.getString("TEST_SERVER_PASSWORD");
onView(withId(R.id.login)).perform(click());
onView(withId(R.id.host_url_input)).perform(typeText(baseUrl));
onView(withId(R.id.test_server_button)).perform(click());
Thread.sleep(3000);
onWebView().forceJavascriptEnabled();
// click on login
onWebView()
.withElement(findElement(Locator.XPATH, "//p[@id='redirect-link']/a"))
.perform(webClick());
// username
onWebView()
.withElement(findElement(Locator.XPATH, "//input[@id='user']"))
.perform(DriverAtoms.webKeys(loginName));
// password
onWebView()
.withElement(findElement(Locator.XPATH, "//input[@id='password']"))
.perform(DriverAtoms.webKeys(password));
// click login
onWebView()
.withElement(findElement(Locator.XPATH, "//input[@id='submit-form']"))
.perform(webClick());
Thread.sleep(2000);
// grant access
onWebView()
.withElement(findElement(Locator.XPATH, "//input[@type='submit']"))
.perform(webClick());
Thread.sleep(5 * 1000);
// check for account
Context targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
assertEquals(1, accountManager.getAccounts().length);
Account account = accountManager.getAccounts()[0];
// account.name is loginName@baseUrl (without protocol)
assertEquals(loginName, account.name.split("@")[0]);
assertEquals(baseUrl.split("//")[1], account.name.split("@")[1]);
}
}
@@ -24,6 +24,7 @@ package com.owncloud.android.ui.activity;
import android.content.Intent;
import com.facebook.testing.screenshot.Screenshot;
import com.nextcloud.client.account.UserAccountManagerImpl;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.R;
@@ -34,12 +35,9 @@ import com.owncloud.android.ui.dialog.ConflictsResolveDialog;
import com.owncloud.android.utils.FileStorageUtils;
import com.owncloud.android.utils.ScreenshotTest;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import java.util.Objects;
import androidx.fragment.app.DialogFragment;
import androidx.test.espresso.intent.rule.IntentsTestRule;
@@ -89,7 +87,7 @@ public class ConflictsResolveActivityIT extends AbstractIT {
shortSleep();
screenshot(Objects.requireNonNull(dialog.requireDialog().getWindow()).getDecorView());
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
}
// @Test
@@ -143,7 +141,7 @@ public class ConflictsResolveActivityIT extends AbstractIT {
// getInstrumentation().waitForIdleSync();
// shortSleep();
//
// screenshot(Objects.requireNonNull(dialog.requireDialog().getWindow()).getDecorView());
// Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
// }
@Test
@@ -224,7 +222,7 @@ public class ConflictsResolveActivityIT extends AbstractIT {
onView(withId(R.id.existing_checkbox)).perform(click());
DialogFragment dialog = (DialogFragment) sut.getSupportFragmentManager().findFragmentByTag("conflictDialog");
screenshot(Objects.requireNonNull(dialog.requireDialog().getWindow()).getDecorView());
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
onView(withText("OK")).perform(click());
@@ -243,7 +241,6 @@ public class ConflictsResolveActivityIT extends AbstractIT {
OCFile existingFile = new OCFile("/newFile.txt");
existingFile.setFileLength(1024000);
existingFile.setModificationTimestamp(1582019340);
existingFile.setRemoteId("123abc");
OCFile newFile = new OCFile("/newFile.txt");
newFile.setFileLength(56000);
@@ -270,7 +267,7 @@ public class ConflictsResolveActivityIT extends AbstractIT {
onView(withId(R.id.new_checkbox)).perform(click());
DialogFragment dialog = (DialogFragment) sut.getSupportFragmentManager().findFragmentByTag("conflictDialog");
screenshot(Objects.requireNonNull(dialog.requireDialog().getWindow()).getDecorView());
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
onView(withText("OK")).perform(click());
@@ -316,15 +313,10 @@ public class ConflictsResolveActivityIT extends AbstractIT {
onView(withId(R.id.new_checkbox)).perform(click());
DialogFragment dialog = (DialogFragment) sut.getSupportFragmentManager().findFragmentByTag("conflictDialog");
screenshot(Objects.requireNonNull(dialog.requireDialog().getWindow()).getDecorView());
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
onView(withText("OK")).perform(click());
assertTrue(returnCode);
}
@After
public void after() {
getStorageManager().deleteAllFiles();
}
}
@@ -1,65 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.activity
import android.content.Intent
import androidx.test.espresso.intent.rule.IntentsTestRule
import com.owncloud.android.AbstractIT
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.utils.ScreenshotTest
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
class ContactsPreferenceActivityIT : AbstractIT() {
@get:Rule
var activityRule = IntentsTestRule(ContactsPreferenceActivity::class.java, true, false)
@Test
@ScreenshotTest
fun openVCF() {
val file = getFile("vcard.vcf")
val vcfFile = OCFile("/contacts.vcf")
vcfFile.storagePath = file.absolutePath
assertTrue(vcfFile.isDown)
val intent = Intent()
intent.putExtra(ContactsPreferenceActivity.EXTRA_FILE, vcfFile)
intent.putExtra(ContactsPreferenceActivity.EXTRA_USER, user)
val sut = activityRule.launchActivity(intent)
shortSleep()
screenshot(sut)
}
@Test
@ScreenshotTest
fun openContactsPreference() {
val sut = activityRule.launchActivity(null)
shortSleep()
screenshot(sut)
}
}
@@ -21,9 +21,7 @@ package com.owncloud.android.ui.activity;
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import com.owncloud.android.AbstractIT;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.utils.ScreenshotTest;
import org.junit.Assert;
import org.junit.Rule;
@@ -35,7 +33,7 @@ import androidx.test.rule.ActivityTestRule;
@RunWith(AndroidJUnit4.class)
//@LargeTest
public class FolderPickerActivityIT extends AbstractIT {
public class FolderPickerActivityIT {
@Rule
public ActivityTestRule<FolderPickerActivity> activityRule =
new ActivityTestRule<>(FolderPickerActivity.class);
@@ -120,14 +118,4 @@ public class FolderPickerActivityIT extends AbstractIT {
// Assert
Assert.assertEquals(origin, target);
}
@Test
@ScreenshotTest
public void open() {
FolderPickerActivity sut = activityRule.getActivity();
OCFile origin = new OCFile("/test/file.txt");
sut.setFile(origin);
screenshot(sut);
}
}
@@ -24,6 +24,7 @@ package com.owncloud.android.ui.activity;
import android.app.Activity;
import com.facebook.testing.screenshot.Screenshot;
import com.nextcloud.client.account.User;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.utils.ScreenshotTest;
@@ -46,7 +47,7 @@ public class ManageAccountsActivityIT extends AbstractIT {
shortSleep();
screenshot(sut);
Screenshot.snapActivity(sut).record();
}
@Test
@@ -60,6 +61,6 @@ public class ManageAccountsActivityIT extends AbstractIT {
shortSleep();
shortSleep();
screenshot(getCurrentActivity());
Screenshot.snapActivity(getCurrentActivity()).record();
}
}
@@ -1,132 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.activity
import androidx.test.espresso.intent.rule.IntentsTestRule
import com.facebook.testing.screenshot.Screenshot
import com.owncloud.android.AbstractIT
import com.owncloud.android.lib.resources.notifications.models.Action
import com.owncloud.android.lib.resources.notifications.models.Notification
import com.owncloud.android.lib.resources.notifications.models.RichObject
import com.owncloud.android.utils.ScreenshotTest
import org.junit.Rule
import org.junit.Test
import java.util.GregorianCalendar
class NotificationsActivityIT : AbstractIT() {
@get:Rule
var activityRule = IntentsTestRule(NotificationsActivity::class.java, true, false)
@Test
@ScreenshotTest
fun loading() {
val sut: NotificationsActivity = activityRule.launchActivity(null)
Screenshot.snapActivity(sut).record()
}
@Test
@ScreenshotTest
fun empty() {
val sut: NotificationsActivity = activityRule.launchActivity(null)
sut.runOnUiThread { sut.populateList(ArrayList<Notification>()) }
shortSleep()
screenshot(sut)
}
@Test
@ScreenshotTest
@SuppressWarnings("MagicNumber")
fun showNotifications() {
val sut: NotificationsActivity = activityRule.launchActivity(null)
val date = GregorianCalendar()
date.set(2005, 4, 17, 10, 35, 30) // random date
val notifications = ArrayList<Notification>()
notifications.add(
Notification(
1,
"files",
"user",
date.time,
"objectType",
"objectId",
"App recommendation: Tasks",
"SubjectRich",
HashMap<String, RichObject>(),
"Sync tasks from various devices with your Nextcloud and edit them online.",
"MessageRich",
HashMap<String, RichObject>(),
"link",
"icon",
ArrayList<Action>()
)
)
val actions = ArrayList<Action>()
actions.add(Action("Send usage", "link", "url", true))
actions.add(Action("Not now", "link", "url", false))
notifications.add(
Notification(
1,
"files",
"user",
date.time,
"objectType",
"objectId",
"Help improve Nextcloud",
"SubjectRich",
HashMap<String, RichObject>(),
"Do you want to help us to improve Nextcloud" +
" by providing some anonymize data about your setup and usage?",
"MessageRich",
HashMap<String, RichObject>(),
"link",
"icon",
actions
)
)
sut.runOnUiThread { sut.populateList(notifications) }
shortSleep()
screenshot(sut)
}
@Test
@ScreenshotTest
fun error() {
val sut: NotificationsActivity = activityRule.launchActivity(null)
shortSleep()
sut.runOnUiThread { sut.setEmptyContent("Error", "Error! Please try again later!") }
screenshot(sut)
}
}
@@ -1,41 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.activity
import androidx.test.espresso.intent.rule.IntentsTestRule
import com.facebook.testing.screenshot.Screenshot
import com.owncloud.android.AbstractIT
import org.junit.Rule
import org.junit.Test
class UploadFilesActivityIT : AbstractIT() {
@get:Rule
var activityRule = IntentsTestRule(UploadFilesActivity::class.java, true, false)
@Test
// @ScreenshotTest // TODO re-enable and make sure that folder content on emulator is the same on all devices
fun open() {
val sut: UploadFilesActivity = activityRule.launchActivity(null)
Screenshot.snapActivity(sut).record()
}
}
@@ -27,10 +27,8 @@ import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Intent;
import android.os.Looper;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.testing.screenshot.Screenshot;
import com.nextcloud.client.account.RegisteredUser;
import com.nextcloud.client.account.Server;
import com.nextcloud.ui.ChooseAccountDialogFragment;
@@ -164,23 +162,6 @@ public class DialogFragmentIT extends AbstractIT {
getInstrumentation().waitForIdleSync();
shortSleep();
ViewGroup viewGroup = dialog.requireDialog().getWindow().findViewById(android.R.id.content);
hideCursors(viewGroup);
screenshot(Objects.requireNonNull(dialog.requireDialog().getWindow()).getDecorView());
}
private void hideCursors(ViewGroup viewGroup) {
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View child = viewGroup.getChildAt(i);
if (child instanceof ViewGroup) {
hideCursors((ViewGroup) child);
}
if (child instanceof TextView) {
((TextView) child).setCursorVisible(false);
}
}
Screenshot.snap(Objects.requireNonNull(dialog.requireDialog().getWindow()).getDecorView()).record();
}
}
@@ -24,6 +24,7 @@ package com.owncloud.android.ui.dialog;
import android.Manifest;
import com.facebook.testing.screenshot.Screenshot;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.ui.activity.FileDisplayActivity;
@@ -31,8 +32,6 @@ import com.owncloud.android.ui.activity.FileDisplayActivity;
import org.junit.Rule;
import org.junit.Test;
import java.util.Objects;
import androidx.test.espresso.intent.rule.IntentsTestRule;
import androidx.test.rule.GrantPermissionRule;
@@ -59,7 +58,7 @@ public class SyncFileNotEnoughSpaceDialogFragmentTest extends AbstractIT {
getInstrumentation().waitForIdleSync();
screenshot(Objects.requireNonNull(dialog.requireDialog().getWindow()).getDecorView());
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
}
@Test
@@ -73,6 +72,6 @@ public class SyncFileNotEnoughSpaceDialogFragmentTest extends AbstractIT {
getInstrumentation().waitForIdleSync();
screenshot(Objects.requireNonNull(dialog.requireDialog().getWindow()).getDecorView());
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
}
}
@@ -47,6 +47,7 @@ import com.owncloud.android.operations.CreateFolderOperation
import com.owncloud.android.operations.RefreshFolderOperation
import com.owncloud.android.operations.UploadFileOperation
import com.owncloud.android.ui.activity.FileDisplayActivity
import com.owncloud.android.utils.FileStorageUtils
import junit.framework.TestCase
import org.junit.Assert.assertTrue
import org.junit.Rule
@@ -91,7 +92,7 @@ class OCFileListFragmentIT : AbstractOnServerIT() {
assertTrue(CreateFolderOperation("/test/", user, targetContext).execute(client, storageManager).isSuccess)
val ocUpload = OCUpload(
getDummyFile("/nonEmpty.txt").absolutePath,
FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt",
"/test/Readme.md",
account.name
)
@@ -24,9 +24,11 @@ package com.owncloud.android.ui.preview;
import android.Manifest;
import com.facebook.testing.screenshot.Screenshot;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.ui.activity.FileDisplayActivity;
import com.owncloud.android.utils.FileStorageUtils;
import com.owncloud.android.utils.MimeTypeUtil;
import org.junit.Rule;
@@ -49,12 +51,12 @@ public class PreviewTextFileFragmentTest extends AbstractIT {
@Test
// @ScreenshotTest // todo run without real server
public void displaySimpleTextFile() throws IOException {
public void displaySimpleTextFile() {
FileDisplayActivity sut = activityRule.launchActivity(null);
shortSleep();
File file = getDummyFile("nonEmpty.txt");
File file = new File(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt");
OCFile test = new OCFile("/text.md");
test.setMimeType(MimeTypeUtil.MIMETYPE_TEXT_MARKDOWN);
test.setStoragePath(file.getAbsolutePath());
@@ -62,7 +64,7 @@ public class PreviewTextFileFragmentTest extends AbstractIT {
shortSleep();
screenshot(sut);
Screenshot.snapActivity(sut).record();
}
@Test
@@ -80,6 +82,6 @@ public class PreviewTextFileFragmentTest extends AbstractIT {
shortSleep();
screenshot(sut);
Screenshot.snapActivity(sut).record();
}
}
@@ -1,86 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.trashbin
import androidx.test.espresso.intent.rule.IntentsTestRule
import com.facebook.testing.screenshot.Screenshot
import com.owncloud.android.AbstractIT
import com.owncloud.android.utils.ScreenshotTest
import org.junit.Rule
import org.junit.Test
class TrashbinActivityIT : AbstractIT() {
enum class TestCase {
ERROR, EMPTY, FILES
}
@get:Rule
var activityRule = IntentsTestRule(TrashbinActivity::class.java, true, false)
@Test
@ScreenshotTest
fun error() {
val sut: TrashbinActivity = activityRule.launchActivity(null)
val trashbinRepository = TrashbinLocalRepository(TestCase.ERROR)
sut.trashbinPresenter = TrashbinPresenter(trashbinRepository, sut)
sut.runOnUiThread { sut.loadFolder() }
shortSleep()
Screenshot.snapActivity(sut).record()
}
@Test
@ScreenshotTest
fun files() {
val sut: TrashbinActivity = activityRule.launchActivity(null)
val trashbinRepository = TrashbinLocalRepository(TestCase.FILES)
sut.trashbinPresenter = TrashbinPresenter(trashbinRepository, sut)
sut.runOnUiThread { sut.loadFolder() }
shortSleep()
Screenshot.snapActivity(sut).record()
}
@Test
@ScreenshotTest
fun empty() {
val sut: TrashbinActivity = activityRule.launchActivity(null)
val trashbinRepository = TrashbinLocalRepository(TestCase.EMPTY)
sut.trashbinPresenter = TrashbinPresenter(trashbinRepository, sut)
sut.runOnUiThread { sut.loadFolder() }
shortSleep()
Screenshot.snapActivity(sut).record()
}
}
@@ -1,84 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.trashbin
import com.owncloud.android.R
import com.owncloud.android.lib.resources.trashbin.model.TrashbinFile
import com.owncloud.android.ui.trashbin.TrashbinRepository.LoadFolderCallback
class TrashbinLocalRepository(val testCase: TrashbinActivityIT.TestCase) : TrashbinRepository {
override fun emptyTrashbin(callback: TrashbinRepository.OperationCallback?) {
TODO("Not yet implemented")
}
override fun restoreFile(file: TrashbinFile?, callback: TrashbinRepository.OperationCallback?) {
TODO("Not yet implemented")
}
override fun removeTrashbinFile(file: TrashbinFile?, callback: TrashbinRepository.OperationCallback?) {
TODO("Not yet implemented")
}
@Suppress("MagicNumber")
override fun getFolder(remotePath: String?, callback: LoadFolderCallback?) {
when (testCase) {
TrashbinActivityIT.TestCase.ERROR -> callback?.onError(R.string.trashbin_loading_failed)
TrashbinActivityIT.TestCase.FILES -> {
val files = ArrayList<Any>()
files.add(
TrashbinFile(
"test.md",
"text/markdown",
"/trashbin/test.md",
"subFolder/test.md",
1395847838, // random date
1395847908 // random date
)
)
files.add(
TrashbinFile(
"image.jpg",
"image/jpeg",
"/trashbin/image.jpg",
"image.jpg",
1395841858, // random date
1395837858 // random date
)
)
files.add(
TrashbinFile(
"folder",
"DIR",
"/trashbin/folder/",
"folder",
1395347858, // random date
1395849858 // random date
)
)
callback?.onSuccess(files)
}
TrashbinActivityIT.TestCase.EMPTY -> callback?.onSuccess(ArrayList<Any>())
}
}
}
@@ -50,7 +50,6 @@ import java.security.SecureRandom;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import androidx.annotation.RequiresApi;
@@ -72,7 +71,6 @@ import static com.owncloud.android.utils.EncryptionUtils.generateKey;
import static com.owncloud.android.utils.EncryptionUtils.generateSHA512;
import static com.owncloud.android.utils.EncryptionUtils.getMD5Sum;
import static com.owncloud.android.utils.EncryptionUtils.ivDelimiter;
import static com.owncloud.android.utils.EncryptionUtils.ivDelimiterOld;
import static com.owncloud.android.utils.EncryptionUtils.ivLength;
import static com.owncloud.android.utils.EncryptionUtils.randomBytes;
import static com.owncloud.android.utils.EncryptionUtils.saltLength;
@@ -154,17 +152,7 @@ public class EncryptionTestIT {
Log_OC.d("EncryptionTestIT", i + " of " + max);
byte[] key = generateKey();
String encryptedString;
if (new Random().nextBoolean()) {
encryptedString = EncryptionUtils.encryptStringSymmetric(privateKey, key);
} else {
encryptedString = EncryptionUtils.encryptStringSymmetricOld(privateKey, key);
if (encryptedString.indexOf(ivDelimiterOld) != encryptedString.lastIndexOf(ivDelimiterOld)) {
Log_OC.d("EncryptionTestIT", "skip due to duplicated iv (old system) -> ignoring");
continue;
}
}
String encryptedString = EncryptionUtils.encryptStringSymmetric(privateKey, key);
String decryptedString = decryptStringSymmetric(encryptedString, key);
assertEquals(privateKey, decryptedString);
@@ -204,29 +192,19 @@ public class EncryptionTestIT {
@Test
public void encryptPrivateKey() throws Exception {
int max = 10;
for (int i = 0; i < max; i++) {
Log_OC.d("EncryptionTestIT", i + " of " + max);
String keyPhrase = "moreovertelevisionfactorytendencyindependenceinternationalintellectualimpress" +
String keyPhrase = "moreovertelevisionfactorytendencyindependenceinternationalintellectualimpress" +
"interestvolunteer";
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(4096, new SecureRandom());
KeyPair keyPair = keyGen.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
byte[] privateKeyBytes = privateKey.getEncoded();
String privateKeyString = encodeBytesToBase64String(privateKeyBytes);
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(4096, new SecureRandom());
KeyPair keyPair = keyGen.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
byte[] privateKeyBytes = privateKey.getEncoded();
String privateKeyString = encodeBytesToBase64String(privateKeyBytes);
String encryptedString;
if (new Random().nextBoolean()) {
encryptedString = EncryptionUtils.encryptPrivateKey(privateKeyString, keyPhrase);
} else {
encryptedString = EncryptionUtils.encryptPrivateKeyOld(privateKeyString, keyPhrase);
}
String decryptedString = decryptPrivateKey(encryptedString, keyPhrase);
String encryptedString = EncryptionUtils.encryptPrivateKey(privateKeyString, keyPhrase);
String decryptedString = decryptPrivateKey(encryptedString, keyPhrase);
assertEquals(privateKeyString, decryptedString);
}
assertEquals(privateKeyString, decryptedString);
}
@Test
@@ -1,42 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.utils
import com.owncloud.android.AbstractIT
import com.owncloud.android.utils.FileStorageUtils.pathToUserFriendlyDisplay
import org.junit.Assert.assertEquals
import org.junit.Test
class FileStorageUtilsTest : AbstractIT() {
@Test
fun testPathToUserFriendlyDisplay() {
assertEquals("/", pathToUserFriendlyDisplay("/"))
assertEquals("/sdcard/", pathToUserFriendlyDisplay("/sdcard/"))
assertEquals("/sdcard/test/1/", pathToUserFriendlyDisplay("/sdcard/test/1/"))
assertEquals("Internal storage/Movies/", pathToUserFriendlyDisplay("/storage/emulated/0/Movies/"))
assertEquals("Internal storage/", pathToUserFriendlyDisplay("/storage/emulated/0/"))
}
private fun pathToUserFriendlyDisplay(path: String): String {
return pathToUserFriendlyDisplay(path, targetContext, targetContext.resources)
}
}
-1
View File
@@ -325,7 +325,6 @@
<service android:name=".services.OperationsService" />
<service android:name=".files.services.FileDownloader" />
<service android:name="com.nextcloud.client.files.downloader.DownloaderService" />
<service android:name=".files.services.FileUploader" />
<service android:name="com.nextcloud.client.media.PlayerService"/>
@@ -1,80 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz <[email protected]>
* Copyright (C) 2020 Chris Narkiewicz
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.account
import android.accounts.Account
import android.net.Uri
import android.os.Parcel
import android.os.Parcelable
import com.owncloud.android.MainApp
import com.owncloud.android.lib.common.OwnCloudAccount
import com.owncloud.android.lib.common.OwnCloudBasicCredentials
import java.net.URI
/**
* This is a mock user object suitable for integration tests. Mocks obtained from code generators
* such as Mockito or MockK cannot be transported in Intent extras.
*/
data class MockUser(override val accountName: String, val accountType: String) : User, Parcelable {
constructor() : this(DEFAULT_MOCK_ACCOUNT_NAME, DEFAULT_MOCK_ACCOUNT_TYPE)
companion object {
@JvmField
val CREATOR: Parcelable.Creator<MockUser> = object : Parcelable.Creator<MockUser> {
override fun createFromParcel(source: Parcel): MockUser = MockUser(source)
override fun newArray(size: Int): Array<MockUser?> = arrayOfNulls(size)
}
const val DEFAULT_MOCK_ACCOUNT_NAME = "mock_account_name"
const val DEFAULT_MOCK_ACCOUNT_TYPE = "mock_account_type"
}
private constructor(source: Parcel) : this(
source.readString() as String,
source.readString() as String
)
override val server = Server(URI.create(""), MainApp.MINIMUM_SUPPORTED_SERVER_VERSION)
override val isAnonymous = false
override fun toPlatformAccount(): Account {
return Account(accountName, accountType)
}
override fun toOwnCloudAccount(): OwnCloudAccount {
return OwnCloudAccount(Uri.EMPTY, OwnCloudBasicCredentials("", ""))
}
override fun nameEquals(user: User?): Boolean {
return user?.accountName.equals(accountName, true)
}
override fun nameEquals(accountName: CharSequence?): Boolean {
return accountName?.toString().equals(this.accountType, true)
}
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeString(accountName)
writeString(accountType)
}
}
@@ -19,53 +19,23 @@
*/
package com.nextcloud.client.core
typealias OnResultCallback<T> = (result: T) -> Unit
typealias OnErrorCallback = (error: Throwable) -> Unit
typealias OnProgressCallback<P> = (progress: P) -> Unit
typealias IsCancelled = () -> Boolean
typealias TaskFunction<RESULT, PROGRESS> = (
onProgress: OnProgressCallback<PROGRESS>,
isCancelled: IsCancelled
) -> RESULT
typealias OnResultCallback<T> = (T) -> Unit
typealias OnErrorCallback = (Throwable) -> Unit
/**
* This interface allows to post background tasks that report results via callbacks invoked on main thread.
* It is provided as an alternative for heavy, platform specific and virtually untestable [android.os.AsyncTask]
*
* Please note that as of Android R, [android.os.AsyncTask] is deprecated and [java.util.concurrent] is a recommended
* alternative.
* It is provided as an alternative for heavy, platform specific and virtually untestable [android.os.AsyncTask]
*/
interface AsyncRunner {
/**
* Post a quick background task and return immediately returning task cancellation interface.
*
* Quick task is a short piece of code that does not support interruption nor progress monitoring.
*
* @param task Task function returning result T; error shall be signalled by throwing an exception.
* @param onResult Callback called when task function returns a result.
* @param onError Callback called when task function throws an exception.
* @return Cancellable interface, allowing cancellation of a running task.
*/
fun <RESULT> postQuickTask(
task: () -> RESULT,
onResult: OnResultCallback<RESULT>? = null,
onError: OnErrorCallback? = null
): Cancellable
/**
* Post a background task and return immediately returning task cancellation interface.
*
* @param task Task function returning result T; error shall be signalled by throwing an exception.
* @param onResult Callback called when task function returns a result,
* @param onError Callback called when task function throws an exception.
* @param onProgress Callback called when task function reports progress update.
* @return Cancellable interface, allowing cancellation of a running task.
* @param onResult Callback called when task function returns a result
* @param onError Callback called when task function throws an exception
* @return Cancellable interface, allowing to cancel running task.
*/
fun <RESULT, PROGRESS> postTask(
task: TaskFunction<RESULT, PROGRESS>,
onResult: OnResultCallback<RESULT>? = null,
onError: OnErrorCallback? = null,
onProgress: OnProgressCallback<PROGRESS>? = null
): Cancellable
fun <T> post(task: () -> T, onResult: OnResultCallback<T>? = null, onError: OnErrorCallback? = null): Cancellable
}
@@ -31,8 +31,8 @@ package com.nextcloud.client.core
interface Cancellable {
/**
* Cancel running task. Task termination is not guaranteed, as some
* tasks cannot be interrupted, but the result will not be delivered.
* Cancel running task. Task termination is not guaranteed, but the result
* shall not be delivered.
*/
fun cancel()
}
@@ -1,28 +0,0 @@
/**
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.core
import android.app.Service
import android.os.Binder
/**
* This is a generic binder that provides access to a locally bound service instance.
*/
abstract class LocalBinder<S : Service>(val service: S) : Binder()
@@ -1,105 +0,0 @@
/**
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.core
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
/**
* This is a local service connection providing a foundation for service
* communication logic.
*
* One can subclass it to create own service interaction API.
*/
abstract class LocalConnection<S : Service>(
protected val context: Context
) : ServiceConnection {
private var serviceBinder: LocalBinder<S>? = null
val service: S? get() = serviceBinder?.service
val isConnected: Boolean get() {
return serviceBinder != null
}
/**
* Override this method to create custom binding intent.
* Default implementation returns null, which disables binding.
*
* @see [bind]
*/
protected open fun createBindIntent(): Intent? {
return null
}
/**
* Bind local service. If [createBindIntent] returns null, it no-ops.
*/
fun bind() {
createBindIntent()?.let {
context.bindService(it, this, Context.BIND_AUTO_CREATE)
}
}
/**
* Unbind service if it is bound.
* If service is not bound, it no-ops.
*/
fun unbind() {
if (isConnected) {
onUnbind()
context.unbindService(this)
serviceBinder = null
}
}
/**
* Callback called when connection binds to a service.
* Any actions taken on service connection can be taken here.
*/
protected open fun onBound(binder: IBinder) {
// default no-op
}
/**
* Callback called when service is about to be unbound.
* Binder is still valid at this stage and can be used to
* perform cleanups. After exiting this method, service will
* no longer be available.
*/
protected open fun onUnbind() {
// default no-op
}
final override fun onServiceConnected(name: ComponentName, binder: IBinder) {
if (binder !is LocalBinder<*>) {
throw IllegalStateException("Binder is not extending ${LocalBinder::class.java.name}")
}
serviceBinder = binder as LocalBinder<S>
onBound(binder)
}
final override fun onServiceDisconnected(name: ComponentName) {
serviceBinder = null
}
}
@@ -27,35 +27,14 @@ import java.util.ArrayDeque
*/
class ManualAsyncRunner : AsyncRunner {
private val queue: ArrayDeque<Runnable> = ArrayDeque()
private val queue: ArrayDeque<Task<*>> = ArrayDeque()
override fun <T> postQuickTask(
task: () -> T,
onResult: OnResultCallback<T>?,
onError: OnErrorCallback?
): Cancellable {
return postTask(
task = { _: OnProgressCallback<Any>, _: IsCancelled -> task.invoke() },
onResult = onResult,
onError = onError,
onProgress = null
)
}
override fun <T, P> postTask(
task: TaskFunction<T, P>,
onResult: OnResultCallback<T>?,
onError: OnErrorCallback?,
onProgress: OnProgressCallback<P>?
): Cancellable {
val remove: Function1<Runnable, Boolean> = queue::remove
override fun <T> post(task: () -> T, onResult: OnResultCallback<T>?, onError: OnErrorCallback?): Cancellable {
val taskWrapper = Task(
postResult = { it.run(); true },
removeFromQueue = remove,
postResult = { it.run() },
taskBody = task,
onSuccess = onResult,
onError = onError,
onProgress = onProgress
onError = onError
)
queue.push(taskWrapper)
return taskWrapper
@@ -22,32 +22,23 @@ package com.nextcloud.client.core
import java.util.concurrent.atomic.AtomicBoolean
/**
* This is a wrapper for a task function runing in background.
* It executes task function and handles result or error delivery.
* This is a wrapper for a function run in background.
*
* Runs task function and posts result if task is not cancelled.
*/
@Suppress("LongParameterList")
internal class Task<T, P>(
private val postResult: (Runnable) -> Boolean,
private val removeFromQueue: (Runnable) -> Boolean,
private val taskBody: TaskFunction<T, P>,
internal class Task<T>(
private val postResult: (Runnable) -> Unit,
private val taskBody: () -> T,
private val onSuccess: OnResultCallback<T>?,
private val onError: OnErrorCallback?,
private val onProgress: OnProgressCallback<P>?
private val onError: OnErrorCallback?
) : Runnable, Cancellable {
val isCancelled: Boolean
get() = cancelled.get()
private val cancelled = AtomicBoolean(false)
private fun postProgress(p: P) {
postResult(Runnable { onProgress?.invoke(p) })
}
@Suppress("TooGenericExceptionCaught") // this is exactly what we want here
override fun run() {
@Suppress("TooGenericExceptionCaught") // this is exactly what we want here
try {
val result = taskBody.invoke({ postProgress(it) }, this::isCancelled)
val result = taskBody.invoke()
if (!cancelled.get()) {
postResult.invoke(
Runnable {
@@ -60,11 +51,9 @@ internal class Task<T, P>(
postResult(Runnable { onError?.invoke(t) })
}
}
removeFromQueue(this)
}
override fun cancel() {
cancelled.set(true)
removeFromQueue(this)
}
}
@@ -28,44 +28,17 @@ import java.util.concurrent.ScheduledThreadPoolExecutor
*
* Tasks are run on multi-threaded pool. If serialized execution is desired, set [corePoolSize] to 1.
*/
internal class ThreadPoolAsyncRunner(
private val uiThreadHandler: Handler,
corePoolSize: Int,
val tag: String = "default"
) : AsyncRunner {
internal class ThreadPoolAsyncRunner(private val uiThreadHandler: Handler, corePoolSize: Int) : AsyncRunner {
private val executor = ScheduledThreadPoolExecutor(corePoolSize)
override fun <T> postQuickTask(
task: () -> T,
onResult: OnResultCallback<T>?,
onError: OnErrorCallback?
): Cancellable {
val taskAdapter = { _: OnProgressCallback<Void>, _: IsCancelled -> task.invoke() }
return postTask(
taskAdapter,
onResult,
onError,
null
)
}
override fun <T, P> postTask(
task: TaskFunction<T, P>,
onResult: OnResultCallback<T>?,
onError: OnErrorCallback?,
onProgress: OnProgressCallback<P>?
): Cancellable {
val remove: Function1<Runnable, Boolean> = executor::remove
val taskWrapper = Task(
postResult = uiThreadHandler::post,
removeFromQueue = remove,
taskBody = task,
onSuccess = onResult,
onError = onError,
onProgress = onProgress
)
override fun <T> post(task: () -> T, onResult: OnResultCallback<T>?, onError: OnErrorCallback?): Cancellable {
val taskWrapper = Task(this::postResult, task, onResult, onError)
executor.execute(taskWrapper)
return taskWrapper
}
private fun postResult(r: Runnable) {
uiThreadHandler.post(r)
}
}
@@ -49,8 +49,6 @@ import com.nextcloud.client.migrations.MigrationsDb;
import com.nextcloud.client.migrations.MigrationsManager;
import com.nextcloud.client.migrations.MigrationsManagerImpl;
import com.nextcloud.client.network.ClientFactory;
import com.nextcloud.client.notifications.AppNotificationManager;
import com.nextcloud.client.notifications.AppNotificationManagerImpl;
import com.owncloud.android.datamodel.ArbitraryDataProvider;
import com.owncloud.android.datamodel.UploadsStorageManager;
import com.owncloud.android.ui.activities.data.activities.ActivitiesRepository;
@@ -65,7 +63,6 @@ import org.greenrobot.eventbus.EventBus;
import java.io.File;
import javax.inject.Named;
import javax.inject.Singleton;
import dagger.Module;
@@ -167,17 +164,9 @@ class AppModule {
@Provides
@Singleton
AsyncRunner uiAsyncRunner() {
AsyncRunner asyncRunner() {
Handler uiHandler = new Handler();
return new ThreadPoolAsyncRunner(uiHandler, 4, "ui");
}
@Provides
@Singleton
@Named("io")
AsyncRunner ioAsyncRunner() {
Handler uiHandler = new Handler();
return new ThreadPoolAsyncRunner(uiHandler, 8, "io");
return new ThreadPoolAsyncRunner(uiHandler, 4);
}
@Provides
@@ -211,10 +200,4 @@ class AppModule {
Migrations migrations) {
return new MigrationsManagerImpl(appInfo, migrationsDb, asyncRunner, migrations.getSteps());
}
@Provides
@Singleton
AppNotificationManager notificationsManager(Context context, NotificationManager platformNotificationsManager) {
return new AppNotificationManagerImpl(context, context.getResources(), platformNotificationsManager);
}
}
@@ -22,7 +22,6 @@ package com.nextcloud.client.di;
import com.nextcloud.client.etm.EtmActivity;
import com.nextcloud.client.jobs.NotificationWork;
import com.nextcloud.client.files.downloader.DownloaderService;
import com.nextcloud.client.logger.ui.LogsActivity;
import com.nextcloud.client.media.PlayerService;
import com.nextcloud.client.onboarding.FirstRunActivity;
@@ -169,5 +168,4 @@ abstract class ComponentsModule {
@ContributesAndroidInjector abstract AccountManagerService accountManagerService();
@ContributesAndroidInjector abstract OperationsService operationsService();
@ContributesAndroidInjector abstract PlayerService playerService();
@ContributesAndroidInjector abstract DownloaderService fileDownloaderService();
}
@@ -49,8 +49,7 @@ class ShowErrorActivity : AppCompatActivity() {
val snackbar = DisplayUtils.createSnackbar(
error_page_container,
R.string.error_report_issue_text,
Snackbar.LENGTH_INDEFINITE
R.string.error_report_issue_text, Snackbar.LENGTH_INDEFINITE
)
.setAction(R.string.error_report_issue_action) { reportIssue() }
@@ -21,21 +21,15 @@ package com.nextcloud.client.etm
import android.accounts.Account
import android.accounts.AccountManager
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.content.res.Resources
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.etm.pages.EtmAccountsFragment
import com.nextcloud.client.etm.pages.EtmBackgroundJobsFragment
import com.nextcloud.client.etm.pages.EtmDownloaderFragment
import com.nextcloud.client.etm.pages.EtmMigrations
import com.nextcloud.client.etm.pages.EtmPreferencesFragment
import com.nextcloud.client.files.downloader.TransferManagerConnection
import com.nextcloud.client.jobs.BackgroundJobManager
import com.nextcloud.client.jobs.JobInfo
import com.nextcloud.client.migrations.MigrationInfo
@@ -46,12 +40,9 @@ import com.owncloud.android.lib.common.accounts.AccountUtils
import javax.inject.Inject
@Suppress("LongParameterList") // Dependencies Injection
@SuppressLint("StaticFieldLeak")
class EtmViewModel @Inject constructor(
private val context: Context,
private val defaultPreferences: SharedPreferences,
private val platformAccountManager: AccountManager,
private val accountManager: UserAccountManager,
private val resources: Resources,
private val backgroundJobManager: BackgroundJobManager,
private val migrationsManager: MigrationsManager,
@@ -80,7 +71,6 @@ class EtmViewModel @Inject constructor(
*/
data class AccountData(val account: Account, val userData: Map<String, String?>)
val currentUser: User get() = accountManager.user
val currentPage: LiveData<EtmMenuEntry?> = MutableLiveData()
val pages: List<EtmMenuEntry> = listOf(
EtmMenuEntry(
@@ -102,14 +92,8 @@ class EtmViewModel @Inject constructor(
iconRes = R.drawable.ic_arrow_up,
titleRes = R.string.etm_migrations,
pageClass = EtmMigrations::class
),
EtmMenuEntry(
iconRes = R.drawable.ic_download_grey600,
titleRes = R.string.etm_downloader,
pageClass = EtmDownloaderFragment::class
)
)
val downloaderConnection = TransferManagerConnection(context, accountManager.user)
val preferences: Map<String, String> get() {
return defaultPreferences.all
@@ -1,139 +0,0 @@
package com.nextcloud.client.etm.pages
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.nextcloud.client.etm.EtmBaseFragment
import com.nextcloud.client.files.downloader.Direction
import com.nextcloud.client.files.downloader.Transfer
import com.nextcloud.client.files.downloader.TransferManager
import com.nextcloud.client.files.downloader.Request
import com.owncloud.android.R
import com.owncloud.android.datamodel.OCFile
class EtmDownloaderFragment : EtmBaseFragment() {
companion object {
private const val TEST_DOWNLOAD_DUMMY_PATH = "/test/dummy_file.txt"
}
class Adapter(private val inflater: LayoutInflater) : RecyclerView.Adapter<Adapter.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val uuid = view.findViewById<TextView>(R.id.etm_download_uuid)
val path = view.findViewById<TextView>(R.id.etm_download_path)
val user = view.findViewById<TextView>(R.id.etm_download_user)
val state = view.findViewById<TextView>(R.id.etm_download_state)
val progress = view.findViewById<TextView>(R.id.etm_download_progress)
private val progressRow = view.findViewById<View>(R.id.etm_download_progress_row)
var progressEnabled: Boolean = progressRow.visibility == View.VISIBLE
get() {
return progressRow.visibility == View.VISIBLE
}
set(value) {
field = value
progressRow.visibility = if (value) {
View.VISIBLE
} else {
View.GONE
}
}
}
private var downloads = listOf<Transfer>()
fun setStatus(status: TransferManager.Status) {
downloads = listOf(status.pending, status.running, status.completed).flatten().reversed()
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = inflater.inflate(R.layout.etm_download_list_item, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return downloads.size
}
override fun onBindViewHolder(vh: ViewHolder, position: Int) {
val download = downloads[position]
vh.uuid.text = download.uuid.toString()
vh.path.text = download.request.file.remotePath
vh.user.text = download.request.user.accountName
vh.state.text = download.state.toString()
if (download.progress >= 0) {
vh.progressEnabled = true
vh.progress.text = download.progress.toString()
} else {
vh.progressEnabled = false
}
}
}
private lateinit var adapter: Adapter
private lateinit var list: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_etm_downloader, container, false)
adapter = Adapter(inflater)
list = view.findViewById(R.id.etm_download_list)
list.layoutManager = LinearLayoutManager(context)
list.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
list.adapter = adapter
return view
}
override fun onResume() {
super.onResume()
vm.downloaderConnection.bind()
vm.downloaderConnection.registerStatusListener(this::onDownloaderStatusChanged)
}
override fun onPause() {
super.onPause()
vm.downloaderConnection.unbind()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.fragment_etm_downloader, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.etm_test_download -> {
scheduleTestDownload(); true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun scheduleTestDownload() {
val request = Request(
vm.currentUser,
OCFile(TEST_DOWNLOAD_DUMMY_PATH),
Direction.DOWNLOAD,
true
)
vm.downloaderConnection.enqueue(request)
}
private fun onDownloaderStatusChanged(status: TransferManager.Status) {
adapter.setStatus(status)
}
}
@@ -1,25 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.files.downloader
enum class Direction {
DOWNLOAD,
UPLOAD
}
@@ -1,100 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.files.downloader
import android.content.ContentResolver
import android.content.Context
import com.nextcloud.client.core.IsCancelled
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.lib.common.OwnCloudClient
import com.owncloud.android.operations.DownloadFileOperation
import com.owncloud.android.utils.MimeTypeUtil
import java.io.File
/**
* This runnable object encapsulates file download logic. It has been extracted to wrap
* network operation and storage manager interactions, as those pose testing challenges
* that cannot be addressed due to large number of dependencies.
*
* This design can be regarded as intermediary refactoring step.
*/
class DownloadTask(
val context: Context,
val contentResolver: ContentResolver,
val clientProvider: () -> OwnCloudClient
) {
data class Result(val file: OCFile, val success: Boolean)
/**
* This class is a helper factory to to keep static dependencies
* injection out of the downloader instance.
*
* @param context Context
* @param clientProvider Provide client - this must be called on background thread
* @param contentResolver content resovler used to access file storage
*/
class Factory(
private val context: Context,
private val clientProvider: () -> OwnCloudClient,
private val contentResolver: ContentResolver
) {
fun create(): DownloadTask {
return DownloadTask(context, contentResolver, clientProvider)
}
}
fun download(request: Request, progress: (Int) -> Unit, isCancelled: IsCancelled): Result {
val op = DownloadFileOperation(request.user.toPlatformAccount(), request.file, context)
val client = clientProvider.invoke()
val result = op.execute(client)
if (result.isSuccess) {
val storageManager = FileDataStorageManager(
request.user.toPlatformAccount(),
contentResolver
)
val file = saveDownloadedFile(op, storageManager)
return Result(file, true)
} else {
return Result(request.file, false)
}
}
private fun saveDownloadedFile(op: DownloadFileOperation, storageManager: FileDataStorageManager): OCFile {
val file = storageManager.getFileById(op.getFile().getFileId()) as OCFile
val syncDate = System.currentTimeMillis()
file.lastSyncDateForProperties = syncDate
file.lastSyncDateForData = syncDate
file.isUpdateThumbnailNeeded = true
file.modificationTimestamp = op.getModificationTimestamp()
file.modificationTimestampAtLastSyncForData = op.getModificationTimestamp()
file.etag = op.getEtag()
file.mimeType = op.getMimeType()
file.storagePath = op.getSavePath()
file.fileLength = File(op.getSavePath()).length()
file.remoteId = op.getFile().getRemoteId()
storageManager.saveFile(file)
if (MimeTypeUtil.isMedia(op.getMimeType())) {
FileDataStorageManager.triggerMediaScan(file.storagePath)
}
return file
}
}
@@ -1,155 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.files.downloader
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import com.nextcloud.client.account.User
import com.nextcloud.client.core.AsyncRunner
import com.nextcloud.client.core.LocalBinder
import com.nextcloud.client.logger.Logger
import com.nextcloud.client.network.ClientFactory
import com.nextcloud.client.notifications.AppNotificationManager
import dagger.android.AndroidInjection
import javax.inject.Inject
import javax.inject.Named
class DownloaderService : Service() {
companion object {
const val TAG = "DownloaderService"
const val ACTION_DOWNLOAD = "download"
const val EXTRA_REQUEST = "request"
const val EXTRA_USER = "user"
fun createBindIntent(context: Context, user: User): Intent {
return Intent(context, DownloaderService::class.java).apply {
putExtra(EXTRA_USER, user)
}
}
fun createDownloadIntent(context: Context, request: Request): Intent {
return Intent(context, DownloaderService::class.java).apply {
action = ACTION_DOWNLOAD
putExtra(EXTRA_REQUEST, request)
}
}
}
/**
* Binder forwards [TransferManager] API calls to selected instance of downloader.
*/
class Binder(
downloader: TransferManagerImpl,
service: DownloaderService
) : LocalBinder<DownloaderService>(service),
TransferManager by downloader
@Inject
lateinit var notificationsManager: AppNotificationManager
@Inject
lateinit var clientFactory: ClientFactory
@Inject
@Named("io")
lateinit var runner: AsyncRunner
@Inject
lateinit var logger: Logger
val isRunning: Boolean get() = downloaders.any { it.value.isRunning }
private val downloaders: MutableMap<String, TransferManagerImpl> = mutableMapOf()
override fun onCreate() {
AndroidInjection.inject(this)
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
if (intent.action != ACTION_DOWNLOAD) {
return START_NOT_STICKY
}
if (!isRunning) {
startForeground(
AppNotificationManager.DOWNLOAD_NOTIFICATION_ID,
notificationsManager.buildDownloadServiceForegroundNotification()
)
}
val request = intent.getParcelableExtra(EXTRA_REQUEST) as Request
val downloader = getDownloader(request.user)
downloader.enqueue(request)
logger.d(TAG, "Enqueued new download: ${request.uuid} ${request.file.remotePath}")
return START_NOT_STICKY
}
override fun onBind(intent: Intent?): IBinder? {
val user = intent?.getParcelableExtra<User>(EXTRA_USER)
if (user != null) {
return Binder(getDownloader(user), this)
} else {
return null
}
}
private fun onDownloadUpdate(transfer: Transfer) {
if (!isRunning) {
logger.d(TAG, "All downloads completed")
notificationsManager.cancelDownloadProgress()
stopForeground(true)
stopSelf()
} else {
notificationsManager.postDownloadProgress(
fileOwner = transfer.request.user,
file = transfer.request.file,
progress = transfer.progress,
allowPreview = !transfer.request.test
)
}
}
override fun onDestroy() {
super.onDestroy()
logger.d(TAG, "Stopping downloader service")
}
private fun getDownloader(user: User): TransferManagerImpl {
val existingDownloader = downloaders[user.accountName]
return if (existingDownloader != null) {
existingDownloader
} else {
val downloadTaskFactory = DownloadTask.Factory(
applicationContext,
{ clientFactory.create(user) },
contentResolver
)
val newDownloader = TransferManagerImpl(runner, downloadTaskFactory)
newDownloader.registerTransferListener(this::onDownloadUpdate)
downloaders[user.accountName] = newDownloader
newDownloader
}
}
}
@@ -1,161 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.files.downloader
import com.owncloud.android.datamodel.OCFile
import java.util.LinkedHashMap
import java.util.UUID
import kotlin.math.max
import kotlin.math.min
/**
* This class tracks status of file transfers. It serves as a state
* machine and drives the transfer background task scheduler via callbacks.
* Transfer status updates trigger change callbacks that should be used
* to notify listeners.
*
* No listener registration mechanism is provided at this level.
*
* This class is not thread-safe. All access from multiple threads shall
* be lock protected.
*
* @property onStartTransfer callback triggered when transfer is switched into running state
* @property onTransferChanged callback triggered whenever transfer status update
* @property maxRunning maximum number of allowed simultaneous transfers
*/
internal class Registry(
private val onStartTransfer: (UUID, Request) -> Unit,
private val onTransferChanged: (Transfer) -> Unit,
private val maxRunning: Int = 2
) {
private val pendingQueue = LinkedHashMap<UUID, Transfer>()
private val runningQueue = LinkedHashMap<UUID, Transfer>()
private val completedQueue = LinkedHashMap<UUID, Transfer>()
val isRunning: Boolean get() = pendingQueue.size > 0 || runningQueue.size > 0
val pending: List<Transfer> get() = pendingQueue.map { it.value }
val running: List<Transfer> get() = runningQueue.map { it.value }
val completed: List<Transfer> get() = completedQueue.map { it.value }
/**
* Insert new transfer into a pending queue.
*
* @return scheduled transfer id
*/
fun add(request: Request): UUID {
val transfer = Transfer(
uuid = request.uuid,
state = TransferState.PENDING,
progress = 0,
file = request.file,
request = request
)
pendingQueue[transfer.uuid] = transfer
return transfer.uuid
}
/**
* Move pending transfers into a running queue up
* to max allowed simultaneous transfers.
*/
fun startNext() {
val freeThreads = max(0, maxRunning - runningQueue.size)
for (i in 0 until min(freeThreads, pendingQueue.size)) {
val key = pendingQueue.keys.first()
val pendingTransfer = pendingQueue.remove(key) ?: throw IllegalStateException("Transfer $key not found")
val runningTransfer = pendingTransfer.copy(state = TransferState.RUNNING)
runningQueue[key] = runningTransfer
onStartTransfer.invoke(key, runningTransfer.request)
onTransferChanged(runningTransfer)
}
}
/**
* Update progress for a given transfer. If no transfer of a given id is currently running,
* update is ignored.
*
* @param uuid ID of the transfer to update
* @param progress progress 0-100%
*/
fun progress(uuid: UUID, progress: Int) {
val transfer = runningQueue[uuid]
if (transfer != null) {
val runningTransfer = transfer.copy(progress = progress)
runningQueue[uuid] = runningTransfer
onTransferChanged(runningTransfer)
}
}
/**
* Complete currently running transfer. If no transfer of a given id is currently running,
* update is ignored.
*
* @param uuid of the transfer to complete
* @param success if true, transfer will be marked as completed; if false - as failed
* @param file if provided, update file in transfer status; if null, existing value is retained
*/
fun complete(uuid: UUID, success: Boolean, file: OCFile? = null) {
val transfer = runningQueue.remove(uuid)
if (transfer != null) {
val status = if (success) {
TransferState.COMPLETED
} else {
TransferState.FAILED
}
val completedTransfer = transfer.copy(state = status, file = file ?: transfer.file)
completedQueue[uuid] = completedTransfer
onTransferChanged(completedTransfer)
}
}
/**
* Search for a transfer by file path. It traverses
* through all queues in order of pending, running and completed
* transfers and returns first transfer status matching
* file path.
*
* @param file Search for a file transfer
* @return transfer status if found, null otherwise
*/
fun getTransfer(file: OCFile): Transfer? {
arrayOf(pendingQueue, runningQueue, completedQueue).forEach { queue ->
queue.forEach { entry ->
if (entry.value.request.file.remotePath == file.remotePath) {
return entry.value
}
}
}
return null
}
/**
* Get transfer status by id. It traverses
* through all queues in order of pending, running and completed
* transfers and returns first transfer status matching
* file path.
*
* @param id transfer id
* @return transfer status if found, null otherwise
*/
fun getTransfer(uuid: UUID): Transfer? {
return pendingQueue[uuid] ?: runningQueue[uuid] ?: completedQueue[uuid]
}
}
@@ -1,91 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.files.downloader
import android.os.Parcel
import android.os.Parcelable
import com.nextcloud.client.account.User
import com.owncloud.android.datamodel.OCFile
import java.util.UUID
/**
* Transfer request. This class should collect all information
* required to trigger transfer operation.
*
* Class is immutable by design, although [OCFile] or other
* types might not be immutable. Clients should no modify
* contents of this object.
*
* @property user Transfer will be triggered for a given user
* @property file File to transfer
* @property uuid Unique request identifier; this identifier can be set in [Transfer]
* @property dummy if true, this requests a dummy test transfer; no real file transfer will occur
*/
class Request internal constructor(
val user: User,
val file: OCFile,
val uuid: UUID,
val type: Direction = Direction.DOWNLOAD,
val test: Boolean = false
) : Parcelable {
constructor(
user: User,
file: OCFile,
type: Direction = Direction.DOWNLOAD
) : this(user, file, UUID.randomUUID(), type)
constructor(
user: User,
file: OCFile,
type: Direction,
test: Boolean
) : this(user, file, UUID.randomUUID(), type, test)
constructor(parcel: Parcel) : this(
user = parcel.readParcelable<User>(User::class.java.classLoader) as User,
file = parcel.readParcelable<OCFile>(OCFile::class.java.classLoader) as OCFile,
uuid = parcel.readSerializable() as UUID,
type = parcel.readSerializable() as Direction,
test = parcel.readInt() != 0
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeParcelable(user, flags)
parcel.writeParcelable(file, flags)
parcel.writeSerializable(uuid)
parcel.writeSerializable(type)
parcel.writeInt(if (test) 1 else 0)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Request> {
override fun createFromParcel(parcel: Parcel): Request {
return Request(parcel)
}
override fun newArray(size: Int): Array<Request?> {
return arrayOfNulls(size)
}
}
}
@@ -1,49 +0,0 @@
/**
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.files.downloader
import com.owncloud.android.datamodel.OCFile
import java.util.UUID
/**
* This class represents current transfer (download or upload) process state.
* This object is immutable by design.
*
* NOTE: Although [OCFile] object is mutable, it is caused by shortcomings
* of legacy design; please behave like an adult and treat it as immutable value.
*
* @property uuid Unique transfer id
* @property state current transfer state
* @property progress transfer progress, 0-100 percent
* @property file transferred file
* @property request initial transfer request
*/
data class Transfer(
val uuid: UUID,
val state: TransferState,
val progress: Int,
val file: OCFile,
val request: Request
) {
/**
* True if download is no longer running, false if it is still being processed.
*/
val isFinished: Boolean get() = state == TransferState.COMPLETED || state == TransferState.FAILED
}
@@ -1,98 +0,0 @@
/**
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.files.downloader
import com.owncloud.android.datamodel.OCFile
import java.util.UUID
interface TransferManager {
/**
* Snapshot of transfer manager status. All data is immutable and can be safely shared.
*/
data class Status(
val pending: List<Transfer>,
val running: List<Transfer>,
val completed: List<Transfer>
) {
companion object {
val EMPTY = Status(emptyList(), emptyList(), emptyList())
}
}
/**
* True if transfer manager has any pending or running transfers.
*/
val isRunning: Boolean
/**
* Status snapshot of all transfers.
*/
val status: Status
/**
* Register transfer progress listener. Registration is idempotent - listener can be registered only once.
*/
fun registerTransferListener(listener: (Transfer) -> Unit)
/**
* Removes registered listener if exists.
*/
fun removeTransferListener(listener: (Transfer) -> Unit)
/**
* Register transfer manager status listener. Registration is idempotent - listener can be registered only once.
*/
fun registerStatusListener(listener: (Status) -> Unit)
/**
* Removes registered listener if exists.
*/
fun removeStatusListener(listener: (Status) -> Unit)
/**
* Adds transfer request to pending queue and returns immediately.
*
* @param request Transfer request
*/
fun enqueue(request: Request)
/**
* Find transfer status by UUID.
*
* @param uuid Download process uuid
* @return transfer status or null if not found
*/
fun getTransfer(uuid: UUID): Transfer?
/**
* Query user's transfer manager for a transfer status. It performs linear search
* of all queues and returns first transfer matching [OCFile.remotePath].
*
* Since there can be multiple transfers with identical file in the queues,
* order of search matters.
*
* It looks for pending transfers first, then running and completed queue last.
*
* @param file Downloaded file
* @return transfer status or null, if transfer does not exist
*/
fun getTransfer(file: OCFile): Transfer?
}
@@ -1,125 +0,0 @@
/**
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.files.downloader
import android.content.Context
import android.content.Intent
import android.os.IBinder
import com.nextcloud.client.account.User
import com.nextcloud.client.core.LocalConnection
import com.owncloud.android.datamodel.OCFile
import java.util.UUID
class TransferManagerConnection(
context: Context,
val user: User
) : LocalConnection<DownloaderService>(context), TransferManager {
private var transferListeners: MutableSet<(Transfer) -> Unit> = mutableSetOf()
private var statusListeners: MutableSet<(TransferManager.Status) -> Unit> = mutableSetOf()
private var binder: DownloaderService.Binder? = null
private val transfersRequiringStatusRedelivery: MutableSet<UUID> = mutableSetOf()
override val isRunning: Boolean
get() = binder?.isRunning ?: false
override val status: TransferManager.Status
get() = binder?.status ?: TransferManager.Status.EMPTY
override fun getTransfer(uuid: UUID): Transfer? = binder?.getTransfer(uuid)
override fun getTransfer(file: OCFile): Transfer? = binder?.getTransfer(file)
override fun enqueue(request: Request) {
val intent = DownloaderService.createDownloadIntent(context, request)
context.startService(intent)
if (!isConnected && transferListeners.size > 0) {
transfersRequiringStatusRedelivery.add(request.uuid)
}
}
override fun registerTransferListener(listener: (Transfer) -> Unit) {
transferListeners.add(listener)
binder?.registerTransferListener(listener)
}
override fun removeTransferListener(listener: (Transfer) -> Unit) {
transferListeners.remove(listener)
binder?.removeTransferListener(listener)
}
override fun registerStatusListener(listener: (TransferManager.Status) -> Unit) {
statusListeners.add(listener)
binder?.registerStatusListener(listener)
}
override fun removeStatusListener(listener: (TransferManager.Status) -> Unit) {
statusListeners.remove(listener)
binder?.removeStatusListener(listener)
}
override fun createBindIntent(): Intent {
return DownloaderService.createBindIntent(context, user)
}
override fun onBound(binder: IBinder) {
super.onBound(binder)
this.binder = binder as DownloaderService.Binder
transferListeners.forEach { listener ->
binder.registerTransferListener(listener)
}
statusListeners.forEach { listener ->
binder.registerStatusListener(listener)
}
deliverMissedUpdates()
}
/**
* Since binding and transfer start are both asynchronous and the order
* is not guaranteed, some transfers might already finish when service is bound,
* resulting in lost notifications.
*
* Deliver all updates for pending transfers that were scheduled
* before service was bound.
*/
private fun deliverMissedUpdates() {
val transferUpdates = transfersRequiringStatusRedelivery.mapNotNull { uuid ->
binder?.getTransfer(uuid)
}
transferListeners.forEach { listener ->
transferUpdates.forEach { update ->
listener.invoke(update)
}
}
transfersRequiringStatusRedelivery.clear()
if (statusListeners.isNotEmpty()) {
binder?.status?.let { status ->
statusListeners.forEach { it.invoke(status) }
}
}
}
override fun onUnbind() {
super.onUnbind()
transferListeners.forEach { binder?.removeTransferListener(it) }
statusListeners.forEach { binder?.removeStatusListener(it) }
}
}
@@ -1,147 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.files.downloader
import com.nextcloud.client.core.AsyncRunner
import com.nextcloud.client.core.IsCancelled
import com.nextcloud.client.core.OnProgressCallback
import com.nextcloud.client.core.TaskFunction
import com.owncloud.android.datamodel.OCFile
import java.util.UUID
/**
* Per-user file transfer manager.
*
* All notifications are performed on main thread. All transfer processes are run
* in the background.
*
* @param runner Background task runner. It is important to provide runner that is not shared with UI code.
* @param taskFactory Download task factory
* @param threads maximum number of concurrent transfer processes
*/
@Suppress("LongParameterList") // transfer operations requires those resources
class TransferManagerImpl(
private val runner: AsyncRunner,
private val taskFactory: DownloadTask.Factory,
threads: Int = 1
) : TransferManager {
companion object {
const val PROGRESS_PERCENTAGE_MAX = 100
const val PROGRESS_PERCENTAGE_MIN = 0
const val TEST_DOWNLOAD_PROGRESS_UPDATE_PERIOD_MS = 200L
}
private val registry = Registry(
onStartTransfer = this::onStartTransfer,
onTransferChanged = this::onTransferUpdate,
maxRunning = threads
)
private val transferListeners: MutableSet<(Transfer) -> Unit> = mutableSetOf()
private val statusListeners: MutableSet<(TransferManager.Status) -> Unit> = mutableSetOf()
override val isRunning: Boolean get() = registry.isRunning
override val status: TransferManager.Status
get() = TransferManager.Status(
pending = registry.pending,
running = registry.running,
completed = registry.completed
)
override fun registerTransferListener(listener: (Transfer) -> Unit) {
transferListeners.add(listener)
}
override fun removeTransferListener(listener: (Transfer) -> Unit) {
transferListeners.remove(listener)
}
override fun registerStatusListener(listener: (TransferManager.Status) -> Unit) {
statusListeners.add(listener)
}
override fun removeStatusListener(listener: (TransferManager.Status) -> Unit) {
statusListeners.remove(listener)
}
override fun enqueue(request: Request) {
registry.add(request)
registry.startNext()
}
override fun getTransfer(uuid: UUID): Transfer? = registry.getTransfer(uuid)
override fun getTransfer(file: OCFile): Transfer? = registry.getTransfer(file)
private fun onStartTransfer(uuid: UUID, request: Request) {
val transferTask = when (request.type) {
Direction.DOWNLOAD -> createDownloadTask(request)
Direction.UPLOAD -> createDownloadTask(request) // plug a hole for now - uploads are not supported
}
runner.postTask(
task = transferTask,
onProgress = { progress: Int -> registry.progress(uuid, progress) },
onResult = { result -> registry.complete(uuid, result.success, result.file); registry.startNext() },
onError = { registry.complete(uuid, false); registry.startNext() }
)
}
private fun createDownloadTask(request: Request): TaskFunction<DownloadTask.Result, Int> {
return if (request.test) {
{ progress: OnProgressCallback<Int>, isCancelled: IsCancelled ->
testDownloadTask(request.file, progress, isCancelled)
}
} else {
val downloadTask = taskFactory.create()
val wrapper: TaskFunction<DownloadTask.Result, Int> = { progress: ((Int) -> Unit), isCancelled ->
downloadTask.download(request, progress, isCancelled)
}
wrapper
}
}
private fun onTransferUpdate(transfer: Transfer) {
transferListeners.forEach { it.invoke(transfer) }
if (statusListeners.isNotEmpty()) {
val status = this.status
statusListeners.forEach { it.invoke(status) }
}
}
/**
* Test download task is used only to simulate download process without
* any network traffic. It is used for development.
*/
private fun testDownloadTask(
file: OCFile,
onProgress: OnProgressCallback<Int>,
isCancelled: IsCancelled
): DownloadTask.Result {
for (i in PROGRESS_PERCENTAGE_MIN..PROGRESS_PERCENTAGE_MAX) {
onProgress(i)
if (isCancelled()) {
return DownloadTask.Result(file, false)
}
Thread.sleep(TEST_DOWNLOAD_PROGRESS_UPDATE_PERIOD_MS)
}
return DownloadTask.Result(file, true)
}
}
@@ -1,27 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.files.downloader
enum class TransferState {
PENDING,
RUNNING,
COMPLETED,
FAILED
}
@@ -150,8 +150,7 @@ class AccountRemovalWork(
)
pushArbitraryData.isShouldBeDeleted = true
arbitraryDataProvider.storeOrUpdateKeyValue(
user.accountName,
PushUtils.KEY_PUSH,
user.accountName, PushUtils.KEY_PUSH,
gson.toJson(pushArbitraryData)
)
PushUtils.pushRegistrationToServer(userAccountManager, pushArbitraryData.getPushToken())
@@ -142,7 +142,8 @@ class BackgroundJobFactory @Inject constructor(
uploadsStorageManager = uploadsStorageManager,
connectivityService = connectivityService,
powerManagementService = powerManagementService,
clock = clock
clock = clock,
backgroundJobManager = backgroundJobManager.get()
)
}
Loaded 100 of 240 files, more files were not shown because too many files have changed in this diff. Show more