Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
44793c2ba7 | ||
|
|
9caa4ab460 | ||
|
|
0c0e586411 | ||
|
|
84de3091de | ||
|
|
ef8123369a | ||
|
|
d969a344d7 | ||
|
|
42f5469afc | ||
|
|
0b19e2129d | ||
|
|
e6f93eaead | ||
|
|
c19cdc0469 | ||
|
|
c2319d3a2c | ||
|
|
e85c272ec4 | ||
|
|
f60472c26e | ||
|
|
4ba70164be | ||
|
|
f554b0ca1f | ||
|
|
257b27309c | ||
|
|
80b1e23c0e | ||
|
|
18cdde1acd | ||
|
|
271e163c30 | ||
|
|
ac6bcb1320 | ||
|
|
9d96e1e87c | ||
|
|
606d525168 | ||
|
|
9dc695d4a1 | ||
|
|
b04c09e82b | ||
|
|
4ab6e19406 | ||
|
|
a0d583c969 | ||
|
|
796db9d195 | ||
|
|
bc2a0725ac | ||
|
|
452e93e581 | ||
|
|
9c5d1e16f6 | ||
|
|
f2c44e39c3 | ||
|
|
ec70e76d22 | ||
|
|
19a5bc2f60 | ||
|
|
78bf9d5012 | ||
|
|
7f0aa2661c | ||
|
|
791d461e51 | ||
|
|
9079a3299d | ||
|
|
78f1289cd5 | ||
|
|
1227572edd | ||
|
|
9a1dd92e5d | ||
|
|
c0c631fe64 | ||
|
|
fac23bf2ea | ||
|
|
31cd0be017 | ||
|
|
555967e774 | ||
|
|
25b8886ba2 | ||
|
|
25c24b961c | ||
|
|
1a1c42e0a7 | ||
|
|
7eb0f66079 | ||
|
|
bc2790ef10 | ||
|
|
7d2ad3afda | ||
|
|
aa2f44b92d | ||
|
|
1f805e5a57 | ||
|
|
28d35f26af | ||
|
|
1038cf507c | ||
|
|
b34bf03551 | ||
|
|
f565b6cf48 | ||
|
|
48741d990b | ||
|
|
f94a2d5561 | ||
|
|
f8428a0d1f | ||
|
|
5f30815410 | ||
|
|
95d6d6a905 | ||
|
|
7b0fd67be7 | ||
|
|
1cb680b4ff | ||
|
|
bc3d631e8b | ||
|
|
e568054e94 | ||
|
|
0c051fd72b | ||
|
|
b0943079c3 | ||
|
|
4bf40b5860 | ||
|
|
779b1b388b | ||
|
|
3f1dfed3a8 | ||
|
|
624cba1a7a | ||
|
|
5e05c072c1 | ||
|
|
179559e223 | ||
|
|
5af031151f | ||
|
|
b6d2147ed3 | ||
|
|
168505570c | ||
|
|
3a7e1ec43d | ||
|
|
ff97bcc23e | ||
|
|
a6786831c5 | ||
|
|
44166a2001 | ||
|
|
07f2e98400 | ||
|
|
9ea27802d0 | ||
|
|
0c7bec049f | ||
|
|
f36ac479a8 | ||
|
|
682ed36006 | ||
|
|
e1b0b521f9 | ||
|
|
0925f54d84 | ||
|
|
6df2d58de5 | ||
|
|
7ab1377744 | ||
|
|
c77f212fab | ||
|
|
7b5e3607aa | ||
|
|
b3153237fd | ||
|
|
510c6c26e8 | ||
|
|
909c9606ce | ||
|
|
500fdb919b | ||
|
|
48d0249e7e | ||
|
|
d604084496 | ||
|
|
2ede91bceb | ||
|
|
ed8ef97ec3 | ||
|
|
287ff2532e | ||
|
|
221d3cc327 | ||
|
|
8cd2648bd0 | ||
|
|
8cb003b78e | ||
|
|
f7ffbe689f | ||
|
|
c771db8bb5 | ||
|
|
2a57580cc7 | ||
|
|
52ba845e86 | ||
|
|
1b5d37b50c | ||
|
|
65e3c66d14 | ||
|
|
58ae52d108 | ||
|
|
7cdf890bf4 | ||
|
|
4923a8efa7 | ||
|
|
3e741eee31 | ||
|
|
4920991618 | ||
|
|
e891411a56 | ||
|
|
b97df4eb08 | ||
|
|
25a67fe4cb | ||
|
|
92dd3a0e94 | ||
|
|
43977198f2 | ||
|
|
adae2e48da | ||
|
|
4ce2729a8f | ||
|
|
d5e1209d00 | ||
|
|
9ead4432e8 | ||
|
|
3108759dac | ||
|
|
b0234d895e | ||
|
|
d741ca7724 | ||
|
|
9710a8a863 | ||
|
|
99e3843427 | ||
|
|
3996901d7c | ||
|
|
14f6353cb3 | ||
|
|
593b684d4d | ||
|
|
cedb397566 | ||
|
|
8e45d953f1 | ||
|
|
19333cef78 | ||
|
|
e32364d2fd | ||
|
|
a52277e5c0 | ||
|
|
c09264bc0f | ||
|
|
9686d38f95 | ||
|
|
a712d61386 | ||
|
|
4f7fd16470 | ||
|
|
3598ed75a3 | ||
|
|
770f5264fc | ||
|
|
8e5fc8ea9c | ||
|
|
12d4a93144 | ||
|
|
54889cb418 | ||
|
|
03c586bd94 | ||
|
|
be4efdd8ce | ||
|
|
37cc49b2d0 | ||
|
|
3cfec4e0ba | ||
|
|
7a6ae44d77 | ||
|
|
4a6f5b2da7 | ||
|
|
b960e9c9ba | ||
|
|
581c12a867 | ||
|
|
4a957714ea | ||
|
|
232c801c9f | ||
|
|
11aa3e1575 | ||
|
|
5872a973a7 | ||
|
|
1ba288e5e6 | ||
|
|
9ef27576e1 | ||
|
|
439dd4ff78 | ||
|
|
1ab8d98d85 | ||
|
|
b87bf1f10e | ||
|
|
98e4acc75a | ||
|
|
793dd901a2 | ||
|
|
b4a6ce98c1 | ||
|
|
d19e9e0556 | ||
|
|
56d7169ca2 | ||
|
|
2061207e25 | ||
|
|
bac4e9b854 | ||
|
|
c00b13df12 | ||
|
|
30ac72652e | ||
|
|
dc01b2d5ab | ||
|
|
3a77d8071d | ||
|
|
a65b208355 | ||
|
|
4f47892823 | ||
|
|
0f0173ccf3 | ||
|
|
9c10afa84e | ||
|
|
ca6a4e39c2 | ||
|
|
4d231841d0 | ||
|
|
7e595f713c | ||
|
|
185123c58f | ||
|
|
24f8bdbd29 | ||
|
|
8c2c38d916 | ||
|
|
4f0bf90433 | ||
|
|
f63502a8fa | ||
|
|
2ffb6dab5f | ||
|
|
7ca6f304ed | ||
|
|
b8c4c68275 | ||
|
|
836e51fa79 | ||
|
|
628e58e65e | ||
|
|
ae08a42f8a | ||
|
|
3ae41ec9fa | ||
|
|
de7b7f5c06 | ||
|
|
1e3c6d1080 | ||
|
|
3dde163c70 | ||
|
|
b9df3de466 | ||
|
|
01b1e719ff | ||
|
|
e5e4973c60 | ||
|
|
bd0d38227a | ||
|
|
b9ea5d44ba | ||
|
|
daf3e9aebd | ||
|
|
a341ebcc83 | ||
|
|
bd01843be7 | ||
|
|
d5fe7679da | ||
|
|
3ca46b9a19 | ||
|
|
d8ada799f3 | ||
|
|
cd794ab1c1 | ||
|
|
be11180ca9 | ||
|
|
bf7d33066b | ||
|
|
40afe563f3 | ||
|
|
391a9fe8e3 | ||
|
|
6d6d8898cd | ||
|
|
83b67b93ad | ||
|
|
db8d3a5d18 | ||
|
|
c578eccade | ||
|
|
059eb9176c | ||
|
|
4013c47b48 | ||
|
|
9938f2e421 | ||
|
|
3facd6c200 | ||
|
|
78adcfb3d6 | ||
|
|
d88dac6284 | ||
|
|
42d1dafaff | ||
|
|
a6c95934cf | ||
|
|
43dfa7a779 | ||
|
|
4481af43fc | ||
|
|
36dbdf5f6e | ||
|
|
cd893c685b | ||
|
|
8b14e8a8bc | ||
|
|
82d0ad98d7 | ||
|
|
0467cc37ca | ||
|
|
eb94a66b2f | ||
|
|
543e25667a | ||
|
|
97c53b38ce | ||
|
|
d7febee4fa | ||
|
|
a163321fa1 | ||
|
|
6ab91c959e | ||
|
|
68d6fe5557 | ||
|
|
f782e3d9fd | ||
|
|
aed8a1ade0 | ||
|
|
c6bb9744ee | ||
|
|
0b90250b69 | ||
|
|
7b049a99d0 | ||
|
|
70471b6233 | ||
|
|
bdaaf63fc3 | ||
|
|
1cc383df2a | ||
|
|
84cef3bafc | ||
|
|
ecd5379646 | ||
|
|
5969d0a6eb | ||
|
|
e1b8d525e5 | ||
|
|
92f5e07b9f | ||
|
|
de4fc2cd2b | ||
|
|
9b3f00c12d | ||
|
|
3ec795f0bf | ||
|
|
da6a29a51e | ||
|
|
2356e839d3 | ||
|
|
7305272bda | ||
|
|
be238a3f96 | ||
|
|
65548c4b4b | ||
|
|
ac6a64b672 | ||
|
|
993aa4afb2 | ||
|
|
0f1da5238b | ||
|
|
26bbfa3538 | ||
|
|
3f62afabf6 | ||
|
|
5d428fe9a2 | ||
|
|
49f3a67251 | ||
|
|
6540e3ef71 | ||
|
|
a4ff1f11d7 | ||
|
|
e77ffa00a8 | ||
|
|
91ef307e7a | ||
|
|
52d089b18a | ||
|
|
ec27f840a6 | ||
|
|
7713a28a4f | ||
|
|
6783e8ab4c | ||
|
|
213002f44e | ||
|
|
1b7bd72c49 | ||
|
|
c243453168 | ||
|
|
d178cde220 | ||
|
|
2b26a5176a | ||
|
|
a93313ca19 | ||
|
|
467104c455 | ||
|
|
c59f9c0b91 | ||
|
|
c821f192d6 | ||
|
|
389090d3e8 | ||
|
|
511a16612d | ||
|
|
4616b0d40b | ||
|
|
20b910a646 | ||
|
|
0977c37916 | ||
|
|
5c74f2b1be | ||
|
|
27fabe745b | ||
|
|
60295480b5 | ||
|
|
020e5a2c3b | ||
|
|
490b292ad9 | ||
|
|
61027524f7 | ||
|
|
7b4e1b82e3 | ||
|
|
87df2c8e1c | ||
|
|
af93382c66 | ||
|
|
0afc2645c4 | ||
|
|
68f06ea158 | ||
|
|
2d82f80e9c | ||
|
|
706ae93a32 | ||
|
|
045a7aa9e7 | ||
|
|
5cc0360855 | ||
|
|
eefeda930c | ||
|
|
7156aaff2a | ||
|
|
26d7b9c692 | ||
|
|
c2750aabda | ||
|
|
ebcbf0afac |
No files matched your search
@@ -1,4 +1,5 @@
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: generic
|
||||
|
||||
steps:
|
||||
@@ -48,6 +49,7 @@ trigger:
|
||||
|
||||
---
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: gplay
|
||||
|
||||
steps:
|
||||
@@ -102,7 +104,28 @@ steps:
|
||||
|
||||
services:
|
||||
- name: server
|
||||
image: nextcloudci/server:server-3
|
||||
image: nextcloudci/server:server-17 # also change in updateScreenshots.sh
|
||||
commands:
|
||||
- /usr/local/bin/initnc.sh
|
||||
- su www-data -c "OC_PASS=user1 php /var/www/html/occ user:add --password-from-env --display-name='User One' user1"
|
||||
- su www-data -c "OC_PASS=user2 php /var/www/html/occ user:add --password-from-env --display-name='User Two' user2"
|
||||
- su www-data -c "OC_PASS=user3 php /var/www/html/occ user:add --password-from-env --display-name='User Three' user3"
|
||||
- su www-data -c "php /var/www/html/occ user:setting user2 files quota 1G"
|
||||
- su www-data -c "php /var/www/html/occ group:add users"
|
||||
- su www-data -c "php /var/www/html/occ group:adduser users user1"
|
||||
- su www-data -c "php /var/www/html/occ group:adduser users user2"
|
||||
- su www-data -c "git clone -b master https://github.com/nextcloud/activity.git /var/www/html/apps/activity/"
|
||||
- su www-data -c "php /var/www/html/occ app:enable activity"
|
||||
- su www-data -c "git clone -b master https://github.com/nextcloud/text.git /var/www/html/apps/text/"
|
||||
- su www-data -c "php /var/www/html/occ app:enable text"
|
||||
- su www-data -c "git clone -b master https://github.com/nextcloud/circles.git /var/www/html/apps/circles/"
|
||||
- apt-get update; apt-get -y install composer
|
||||
- su www-data -c "cd /var/www/html/apps/circles; composer install"
|
||||
- su www-data -c "php /var/www/html/occ app:enable -f circles"
|
||||
- su www-data -c "php /var/www/html/occ config:app:set circles --value 1 allow_non_ssl_links"
|
||||
- su www-data -c "php /var/www/html/occ config:app:set circles --value 1 local_is_non_ssl"
|
||||
- su www-data -c "php /var/www/html/occ circles:manage:create test public publicCircle"
|
||||
- /usr/local/bin/run.sh
|
||||
|
||||
trigger:
|
||||
branch:
|
||||
@@ -112,6 +135,7 @@ trigger:
|
||||
- pull_request
|
||||
---
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: analysis
|
||||
|
||||
steps:
|
||||
@@ -161,6 +185,7 @@ trigger:
|
||||
- pull_request
|
||||
---
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: qa
|
||||
|
||||
steps:
|
||||
|
||||
@@ -16,6 +16,11 @@ labels: bug
|
||||
### Actual behaviour
|
||||
- Tell us what happens
|
||||
|
||||
### Can you reproduce this problem on https://try.nextcloud.com?
|
||||
- Please create a test demo account and see if this still happens there.
|
||||
- If yes, please open up a bug report
|
||||
- If not, please verify server setup and ask for help on forum
|
||||
|
||||
### Environment data
|
||||
Android version:
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
### Testing
|
||||
Writing tests is very important. Please try to write some tests for your PR.
|
||||
|
||||
If you need help, please do not hesitate to ask in this PR for help.
|
||||
|
||||
- [ ] [unit tests](https://github.com/nextcloud/android/blob/master/CONTRIBUTING.md#unit-tests)
|
||||
- [ ] [instrumented tests](https://github.com/nextcloud/android/blob/master/CONTRIBUTING.md#instrumented-tests)
|
||||
- [ ] [UI tests](https://github.com/nextcloud/android/blob/master/CONTRIBUTING.md#ui-tests)
|
||||
[unit tests](https://github.com/nextcloud/android/blob/master/CONTRIBUTING.md#unit-tests)
|
||||
[instrumented tests](https://github.com/nextcloud/android/blob/master/CONTRIBUTING.md#instrumented-tests)
|
||||
[UI tests](https://github.com/nextcloud/android/blob/master/CONTRIBUTING.md#ui-tests)
|
||||
|
||||
- [ ] Tests written, or not not needed
|
||||
@@ -2,19 +2,17 @@
|
||||
daysUntilStale: 28
|
||||
# Number of days of inactivity before a stale issue is closed
|
||||
daysUntilClose: 14
|
||||
# Only issues or pull requests with all of these labels are check if stale. Defaults to `[]` (disabled)
|
||||
onlyLabels:
|
||||
- bug
|
||||
- "needs info/discussion"
|
||||
# Issues with these labels will never be considered stale
|
||||
exemptLabels:
|
||||
- 1. developing
|
||||
- 2. to review
|
||||
- 3. to release
|
||||
- approved
|
||||
- enhancement
|
||||
- overview
|
||||
exemptLabels: []
|
||||
# Label to use when marking an issue as stale
|
||||
staleLabel: stale
|
||||
# Comment to post when marking an issue as stale. Set to `false` to disable
|
||||
markComment: >
|
||||
This request did not receive an update in the last 4 weeks.
|
||||
This bug report did not receive an update in the last 4 weeks.
|
||||
Please take a look again and update the issue with new details,
|
||||
otherwise the issue will be automatically closed in 2 weeks. Thank you!
|
||||
# Comment to post when closing a stale issue. Set to `false` to disable
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
name: "Validate Gradle Wrapper"
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
validation:
|
||||
name: "Validation"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: gradle/wrapper-validation-action@v1
|
||||
@@ -29,9 +29,6 @@
|
||||
</option>
|
||||
<option name="RIGHT_MARGIN" value="120" />
|
||||
<option name="WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN" value="true" />
|
||||
<AndroidXmlCodeStyleSettings>
|
||||
<option name="ARRANGEMENT_SETTINGS_MIGRATED_TO_191" value="true" />
|
||||
</AndroidXmlCodeStyleSettings>
|
||||
<JavaCodeStyleSettings>
|
||||
<option name="IMPORT_LAYOUT_TABLE">
|
||||
<value>
|
||||
@@ -73,6 +70,7 @@
|
||||
</XML>
|
||||
<codeStyleSettings language="JAVA">
|
||||
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
|
||||
<option name="ALIGN_MULTILINE_METHOD_BRACKETS" value="true" />
|
||||
<option name="WRAP_COMMENTS" value="true" />
|
||||
<option name="IF_BRACE_FORCE" value="3" />
|
||||
<option name="DOWHILE_BRACE_FORCE" value="3" />
|
||||
@@ -80,6 +78,9 @@
|
||||
<option name="FOR_BRACE_FORCE" value="3" />
|
||||
<option name="FIELD_ANNOTATION_WRAP" value="0" />
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="Markdown">
|
||||
<option name="RIGHT_MARGIN" value="120" />
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="XML">
|
||||
<indentOptions>
|
||||
<option name="CONTINUATION_INDENT_SIZE" value="4" />
|
||||
@@ -192,5 +193,8 @@
|
||||
</rules>
|
||||
</arrangement>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="kotlin">
|
||||
<option name="ALIGN_MULTILINE_METHOD_BRACKETS" value="true" />
|
||||
</codeStyleSettings>
|
||||
</code_scheme>
|
||||
</component>
|
||||
@@ -72,6 +72,7 @@ If your issue appears to be a bug, and hasn't been reported, open a new issue.
|
||||
|
||||
|
||||
### Bug workflow
|
||||
Every bug should be triaged in approved/needs info in a given time.
|
||||
* approved: at least one other is able to reproduce it
|
||||
* needs info: something unclear, or not able to reproduce
|
||||
* if no response within 1 months, bug will be closed
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import com.github.spotbugs.SpotBugsTask
|
||||
|
||||
buildscript {
|
||||
ext.kotlin_version = '1.3.61'
|
||||
ext.kotlin_version = '1.3.71'
|
||||
repositories {
|
||||
google()
|
||||
jcenter()
|
||||
@@ -20,13 +20,13 @@ buildscript {
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:3.5.3'
|
||||
classpath 'com.android.tools.build:gradle:3.6.1'
|
||||
classpath('com.dicedmelon.gradle:jacoco-android:0.1.4') {
|
||||
exclude group: 'org.codehaus.groovy', module: 'groovy-all'
|
||||
}
|
||||
classpath 'gradle.plugin.com.github.spotbugs:spotbugs-gradle-plugin:1.6.6'
|
||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
|
||||
classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.5.1"
|
||||
classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.7.0"
|
||||
classpath "commons-httpclient:commons-httpclient:3.1@jar" // remove after entire switch to lib v2
|
||||
classpath 'com.karumi:shot:3.1.0'
|
||||
}
|
||||
@@ -60,10 +60,10 @@ configurations {
|
||||
|
||||
ext {
|
||||
jacocoVersion = "0.8.2"
|
||||
daggerVersion = "2.26"
|
||||
markwonVersion = "4.2.1"
|
||||
daggerVersion = "2.27"
|
||||
markwonVersion = "4.3.0"
|
||||
prismVersion = "2.0.0"
|
||||
androidLibraryVersion ="721c01bc369955139daf218377c081d05c82f317"
|
||||
androidLibraryVersion ="c6dff086e5191ec10791aaf89962328451ba65a8"
|
||||
|
||||
travisBuild = System.getenv("TRAVIS") == "true"
|
||||
|
||||
@@ -84,7 +84,7 @@ repositories {
|
||||
|
||||
// semantic versioning for version code
|
||||
def versionMajor = 3
|
||||
def versionMinor = 11
|
||||
def versionMinor = 12
|
||||
def versionPatch = 0
|
||||
def versionBuild = 0 // 0-50=Alpha / 51-98=RC / 90-99=stable
|
||||
|
||||
@@ -129,7 +129,7 @@ android {
|
||||
compileSdkVersion 29
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion 16
|
||||
minSdkVersion 17
|
||||
targetSdkVersion 29
|
||||
|
||||
// arguments to be passed to functional tests
|
||||
@@ -177,8 +177,8 @@ android {
|
||||
versionDev {
|
||||
applicationId "com.nextcloud.android.beta"
|
||||
dimension "default"
|
||||
versionCode 20200213
|
||||
versionName "20200213"
|
||||
versionCode 20200325
|
||||
versionName "20200325"
|
||||
}
|
||||
|
||||
qa {
|
||||
@@ -274,6 +274,10 @@ android {
|
||||
dataBinding {
|
||||
enabled true
|
||||
}
|
||||
|
||||
viewBinding {
|
||||
enabled true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
@@ -289,14 +293,14 @@ dependencies {
|
||||
implementation 'org.apache.jackrabbit:jackrabbit-webdav:2.13.1' // remove after entire switch to lib v2
|
||||
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
|
||||
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
|
||||
implementation 'com.google.android.material:material:1.1.0-rc02'
|
||||
implementation 'com.google.android.material:material:1.1.0'
|
||||
implementation 'com.jakewharton:disklrucache:2.0.2'
|
||||
implementation 'androidx.appcompat:appcompat:1.2.0-alpha02'
|
||||
implementation 'androidx.appcompat:appcompat:1.2.0-alpha03'
|
||||
implementation 'androidx.cardview:cardview:1.0.0'
|
||||
implementation 'androidx.exifinterface:exifinterface:1.1.0'
|
||||
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
|
||||
implementation "androidx.work:work-runtime:2.3.0"
|
||||
implementation "androidx.work:work-runtime-ktx:2.3.1"
|
||||
implementation "androidx.work:work-runtime:2.3.3"
|
||||
implementation "androidx.work:work-runtime-ktx:2.3.3"
|
||||
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.6'
|
||||
@@ -304,13 +308,13 @@ dependencies {
|
||||
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.10.5'
|
||||
implementation 'com.googlecode.ez-vcard:ez-vcard:0.10.6'
|
||||
implementation 'org.lukhnos:nnio:0.2'
|
||||
implementation 'com.madgag.spongycastle:pkix:1.54.0.0'
|
||||
implementation 'com.google.code.gson:gson:2.8.6'
|
||||
implementation 'com.afollestad:sectioned-recyclerview:0.5.0'
|
||||
implementation 'com.github.chrisbanes:PhotoView:2.3.0'
|
||||
implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.15'
|
||||
implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.19'
|
||||
implementation 'com.github.tobiaskaminsky:qrcodescanner:0.1.2.2' // 'com.github.blikoon:QRCodeScanner:0.1.2'
|
||||
implementation 'com.google.android:flexbox:2.0.1'
|
||||
implementation 'org.parceler:parceler-api:1.1.13'
|
||||
@@ -333,11 +337,8 @@ dependencies {
|
||||
kapt "com.google.dagger:dagger-compiler:$daggerVersion"
|
||||
kapt "com.google.dagger:dagger-android-processor:$daggerVersion"
|
||||
|
||||
compileOnly "org.projectlombok:lombok:1.18.12"
|
||||
annotationProcessor "org.projectlombok:lombok:1.18.12"
|
||||
|
||||
ktlint "com.pinterest:ktlint:0.36.0"
|
||||
implementation 'org.conscrypt:conscrypt-android:2.2.1'
|
||||
implementation 'org.conscrypt:conscrypt-android:2.4.0'
|
||||
|
||||
// dependencies for markdown rendering
|
||||
implementation "io.noties.markwon:core:$markwonVersion"
|
||||
@@ -352,11 +353,11 @@ dependencies {
|
||||
|
||||
// dependencies for local unit tests
|
||||
testImplementation 'junit:junit:4.13'
|
||||
testImplementation 'org.mockito:mockito-core:3.2.4'
|
||||
testImplementation 'org.mockito:mockito-core:3.3.3'
|
||||
testImplementation 'androidx.test:core:1.2.0'
|
||||
testImplementation 'org.powermock:powermock-core:2.0.5'
|
||||
testImplementation 'org.powermock:powermock-module-junit4:2.0.5'
|
||||
testImplementation 'org.powermock:powermock-api-mockito2:2.0.5'
|
||||
testImplementation 'org.powermock:powermock-core:2.0.6'
|
||||
testImplementation 'org.powermock:powermock-module-junit4:2.0.6'
|
||||
testImplementation 'org.powermock:powermock-api-mockito2:2.0.6'
|
||||
testImplementation 'org.json:json:20190722'
|
||||
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
|
||||
testImplementation "androidx.arch.core:core-testing:2.1.0"
|
||||
@@ -372,7 +373,7 @@ dependencies {
|
||||
// Espresso core
|
||||
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
|
||||
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.2.0'
|
||||
androidTestImplementation 'org.mockito:mockito-core:3.2.4'
|
||||
androidTestImplementation 'org.mockito:mockito-core:3.3.1'
|
||||
// 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
|
||||
@@ -390,6 +391,8 @@ 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.3.3"
|
||||
}
|
||||
|
||||
configurations.all {
|
||||
|
||||
@@ -265,6 +265,7 @@ naming:
|
||||
functionPattern: '^([a-z$][a-zA-Z$0-9]*)|(`.*`)$'
|
||||
excludeClassPattern: '$^'
|
||||
ignoreOverridden: true
|
||||
excludes: "**/*Test.kt"
|
||||
FunctionParameterNaming:
|
||||
active: true
|
||||
parameterPattern: '[a-z][A-Za-z0-9]*'
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" viewBox="0 0 57 57" width="64" height="64"
|
||||
version="1.1" id="svg10" sodipodi:docname="circles.svg" inkscape:version="0.92.4 5da689c313, 2019-01-14">
|
||||
<metadata id="metadata16">
|
||||
<rdf:RDF>
|
||||
<cc:Work rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<defs id="defs14" />
|
||||
<sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10"
|
||||
gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2"
|
||||
inkscape:window-width="1920" inkscape:window-height="1141" id="namedview12" showgrid="false"
|
||||
inkscape:zoom="7.375" inkscape:cx="33.445579" inkscape:cy="41.701636" inkscape:window-x="0"
|
||||
inkscape:window-y="0" inkscape:window-maximized="1" inkscape:current-layer="svg10" />
|
||||
<path d="M7.1 28.5A21.4 21.4 0 0 1 28.5 7.1m10.7 40A21.4 21.4 0 0 1 10 39M39.2 10A21.4 21.4 0 0 1 47 39.2"
|
||||
fill="none" stroke="#fff" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" id="path2"
|
||||
style="stroke:#000000;stroke-opacity:1;stroke-width:3.99979687;stroke-miterlimit:4;stroke-dasharray:none;fill:none;fill-opacity:1" />
|
||||
<circle cx="28.5" cy="7.1" r="6.5" fill="#fff" id="circle4" style="fill:#000000" />
|
||||
<circle cx="39.2" cy="-10" r="6.5" transform="rotate(90)" fill="#fff" id="circle6" style="fill:#000000" />
|
||||
<circle cx="39.2" cy="-47" r="6.5" transform="rotate(90)" fill="#fff" id="circle8" style="fill:#000000" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.0 KiB |
@@ -1,3 +1,3 @@
|
||||
dependencies {
|
||||
implementation "com.google.firebase:firebase-messaging:17.3.0"
|
||||
implementation "com.google.firebase:firebase-messaging:20.1.3"
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
<ignore regexp="autofillHints"/>
|
||||
</issue>
|
||||
<issue id="InvalidPackage">
|
||||
<ignore path="**/freemarker-2.3.28.jar" />
|
||||
<ignore path="**/freemarker-2.*.*.jar" />
|
||||
<ignore path="**/nnio-0.2.jar"/>
|
||||
<ignore path="**/pkix-1.54.0.0.jar"/>
|
||||
</issue>
|
||||
|
||||
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 17 KiB |
@@ -1 +1 @@
|
||||
387
|
||||
385
|
||||
@@ -1,2 +1,2 @@
|
||||
DO NOT TOUCH; GENERATED BY DRONE
|
||||
<span class="mdl-layout-title">Lint Report: 77 warnings</span>
|
||||
<span class="mdl-layout-title">Lint Report: 94 warnings</span>
|
||||
@@ -1,10 +1,15 @@
|
||||
#!/bin/bash
|
||||
date=$(date +%Y%m%d)
|
||||
oldLibraryCommit=$(grep "androidLibraryVersion\ =" build.gradle)
|
||||
libraryCommit=$(curl https://api.github.com/repos/nextcloud/android-library/commits/master | jq .sha | sed s'/\"//g')
|
||||
|
||||
# use current date for version code/name
|
||||
sed -i "/versionDev/,/\}/ s/versionCode .*/versionCode $date/" build.gradle
|
||||
sed -i "/versionDev/,/\}/ s/versionName .*/versionName \"$date\"/" build.gradle
|
||||
|
||||
# change library
|
||||
sed -i s"#androidLibraryVersion\ =.*#androidLibraryVersion =\"$libraryCommit\"#" build.gradle
|
||||
|
||||
# build signed apk
|
||||
./gradlew assembleVersionDevRelease >> /tmp/dev.log 2>&1
|
||||
|
||||
@@ -32,17 +37,33 @@ mv latest.apk ~/apks/
|
||||
# remove all but the latest 5 apks
|
||||
/bin/ls -t ~/apks/*.apk | awk 'NR>6' | xargs rm -f
|
||||
|
||||
lastBuildTime=$(date --date="$(git log -1 --format=%ai $(git tag | grep dev | tail -n1))" +%s)
|
||||
changelog=$(git log --after=$lastBuildTime --pretty=oneline --abbrev-commit)
|
||||
lastBuildTag=$(git tag | grep dev | tail -n1)
|
||||
# Show only the commit subject in the changelog and filter out:
|
||||
# * Merges
|
||||
# * Dependabot commits
|
||||
# * Commits touching only non-user-facing stuff like tests
|
||||
# * Version bump commits
|
||||
# * Anything reachable from the previous dev edition tag
|
||||
changelog=$(git log --no-merges --invert-grep --author=dependabot --pretty='format:%s' HEAD "^$lastBuildTag" -- ':!src/androidTest' ':!.*' ':!scripts/' ':!screenshots' | grep -vE '^daily dev [[:digit:]]{8}$')
|
||||
# Make Transifex updates have a nicer description
|
||||
if echo "$changelog" | grep -q 'tx-robot'; then
|
||||
changelog=$(echo "$changelog" | grep -v 'tx-robot')
|
||||
# This is a funky bashism - preceding a single-quote string with $ lets you put escape chars in it
|
||||
changelog="${changelog}"$'\nUpdate translations'
|
||||
fi
|
||||
|
||||
libraryCommit=$(curl https://api.github.com/repos/nextcloud/android-library/commits/master | jq .sha | sed s'/\"//g')
|
||||
# Check if the library was updated
|
||||
if ! echo $oldLibraryCommit | grep -q $libraryCommit; then
|
||||
changelog="${changelog}"$'\nUpdate Nextcloud Android library'
|
||||
fi
|
||||
|
||||
# Collapse dependency updates into a single "Update dependencies" entry
|
||||
if git log --pretty='format:%an' HEAD "^$lastBuildTag" | grep -q dependabot; then
|
||||
changelog="${changelog}"$'\nUpdate 3rd-party dependencies'
|
||||
fi
|
||||
|
||||
# changelog
|
||||
echo "$changelog" > src/versionDev/fastlane/metadata/android/en-US/changelogs/$date.txt
|
||||
echo "library commit: $libraryCommit" >> src/versionDev/fastlane/metadata/android/en-US/changelogs/$date.txt
|
||||
|
||||
# build
|
||||
sed -i s"# androidLibraryVersion.*#androidLibraryVersion =\"$libraryCommit\"#" build.gradle
|
||||
|
||||
git add .
|
||||
git commit -m "daily dev $date" -m "$changelog"
|
||||
|
||||
@@ -6,16 +6,20 @@ if ( [[ $(grep NC_TEST_SERVER_BASEURL ~/.gradle/gradle.properties | grep -v "#
|
||||
fi
|
||||
|
||||
## emulator
|
||||
if ( [[ $(emulator -list-avds | grep uiComparison -c) -eq 0 ]] ); then
|
||||
if ( [[ ! $(emulator -list-avds | grep uiComparison -c) -eq 0 ]] ); then
|
||||
avdmanager delete avd -n uiComparison
|
||||
(sleep 5; echo "no") | avdmanager create avd -n uiComparison -c 100M -k "system-images;android-27;google_apis;x86" --abi "google_apis/x86"
|
||||
fi
|
||||
|
||||
emulator -avd uiComparison -no-snapshot -gpu swiftshader_indirect -no-window -no-audio -skin 500x833 1>/dev/null &
|
||||
if [ $1 == "debug" ]; then
|
||||
emulator -avd uiComparison -no-snapshot -gpu swiftshader_indirect -no-audio -skin 500x833 1>/dev/null &
|
||||
else
|
||||
emulator -avd uiComparison -no-snapshot -gpu swiftshader_indirect -no-window -no-audio -skin 500x833 1>/dev/null &
|
||||
fi
|
||||
PID=$(echo $!)
|
||||
|
||||
## server
|
||||
docker run --name=uiComparison nextcloudci/server 1>/dev/null &
|
||||
docker run --name=uiComparison nextcloudci/server --entrypoint '/usr/local/bin/initnc.sh' 1>/dev/null &
|
||||
sleep 5
|
||||
IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' uiComparison)
|
||||
|
||||
@@ -24,13 +28,34 @@ if [[ $IP = "" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
## wait for server to finish
|
||||
scripts/wait_for_server.sh $IP
|
||||
|
||||
## run on server
|
||||
cp gradle.properties gradle.properties_
|
||||
sed -i s"/server/$IP/" gradle.properties
|
||||
scripts/wait_for_emulator.sh
|
||||
scripts/wait_for_server.sh ${IP}
|
||||
|
||||
## update all screenshots
|
||||
# setup test server
|
||||
docker exec uiComparison /bin/sh -c "su www-data -c \"OC_PASS=user1 php /var/www/html/occ user:add --password-from-env --display-name='User One' user1\""
|
||||
docker exec uiComparison /bin/sh -c "su www-data -c \"OC_PASS=user2 php /var/www/html/occ user:add --password-from-env --display-name='User Two' user2\""
|
||||
docker exec uiComparison /bin/sh -c "su www-data -c \"OC_PASS=user3 php /var/www/html/occ user:add --password-from-env --display-name='User Three' user3\""
|
||||
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ user:setting user2 files quota 1G\""
|
||||
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ group:add users\""
|
||||
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ group:adduser users user1\""
|
||||
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ group:adduser users user2\""
|
||||
docker exec uiComparison /bin/sh -c "su www-data -c \"git clone -b master https://github.com/nextcloud/text.git /var/www/html/apps/text/\""
|
||||
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ app:enable text\""
|
||||
docker exec uiComparison /bin/sh -c "su www-data -c \"git clone -b master https://github.com/nextcloud/circles.git /var/www/html/apps/circles/\""
|
||||
docker exec uiComparison /bin/sh -c "apt-get update; apt-get -y install composer"
|
||||
docker exec uiComparison /bin/sh -c "su www-data -c \"cd /var/www/html/apps/circles; composer install\""
|
||||
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ app:enable -f circles\""
|
||||
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ config:app:set circles --value 1 allow_non_ssl_links\""
|
||||
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ config:app:set circles --value 1 local_is_non_ssl\""
|
||||
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ circles:manage:create test public publicCircle\""
|
||||
docker exec uiComparison /bin/sh -c "/usr/local/bin/run.sh"
|
||||
|
||||
## update/create all screenshots
|
||||
./gradlew executeScreenshotTests -Precord
|
||||
|
||||
## update screenshots in a class
|
||||
@@ -47,6 +72,10 @@ scripts/wait_for_server.sh ${IP}
|
||||
|
||||
mv gradle.properties_ gradle.properties
|
||||
|
||||
if [ $1 == "debug" ]; then
|
||||
exit
|
||||
fi
|
||||
|
||||
# tidy up
|
||||
kill $PID
|
||||
docker stop uiComparison
|
||||
|
||||
@@ -1,5 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
upload() {
|
||||
cd $1
|
||||
|
||||
find . -type d -exec curl -u $USER:$PASS -X MKCOL $URL/$REMOTE_FOLDER/$(echo {} | sed s#\./##) \;
|
||||
find . -type f -exec curl -u $USER:$PASS -X PUT $URL/$REMOTE_FOLDER/$(echo {} | sed s#\./##) --upload-file {} \;
|
||||
|
||||
echo "Uploaded failing tests to https://www.kaminsky.me/nc-dev/android-integrationTests/$REMOTE_FOLDER"
|
||||
|
||||
curl -u $GITHUB_USER:$GITHUB_PASSWORD -X POST https://api.github.com/repos/nextcloud/android/issues/$PR/comments \
|
||||
-d "{ \"body\" : \"$TYPE test failed: https://www.kaminsky.me/nc-dev/android-integrationTests/$REMOTE_FOLDER \" }"
|
||||
|
||||
exit 1
|
||||
}
|
||||
|
||||
#1: LOG_USERNAME
|
||||
#2: LOG_PASSWORD
|
||||
#3: DRONE_BUILD_NUMBER
|
||||
@@ -13,6 +27,9 @@ ID=$3
|
||||
USER=$1
|
||||
PASS=$2
|
||||
TYPE=$4
|
||||
PR=$5
|
||||
GITHUB_USER=$6
|
||||
GITHUB_PASSWORD=$7
|
||||
REMOTE_FOLDER=$ID-$TYPE
|
||||
|
||||
set -e
|
||||
@@ -22,27 +39,30 @@ if [ $TYPE = "IT" ]; then
|
||||
elif [ $TYPE = "Unit" ]; then
|
||||
FOLDER=build/reports/tests/testGplayDebugUnitTest
|
||||
else
|
||||
FOLDER=build/reports/shot/verification/
|
||||
FOLDER=build/reports/shot/verification
|
||||
fi
|
||||
|
||||
if [ ! -e $FOLDER ]; then
|
||||
if [ -e $FOLDER ]; then
|
||||
upload $FOLDER
|
||||
else
|
||||
echo "$TYPE test failed, but no output was generated. Maybe a preliminary stage failed."
|
||||
|
||||
curl -u $6:$7 \
|
||||
-X POST https://api.github.com/repos/nextcloud/android/issues/$5/comments \
|
||||
curl -u $GITHUB_USER:$GITHUB_PASSWORD \
|
||||
-X POST https://api.github.com/repos/nextcloud/android/issues/$PR/comments \
|
||||
-d "{ \"body\" : \"$TYPE test failed, but no output was generated. Maybe a preliminary stage failed. \" }"
|
||||
|
||||
exit 1
|
||||
if [ -e build/reports/androidTests/connected/flavors/GPLAY ] ; then
|
||||
TYPE="IT"
|
||||
upload "build/reports/androidTests/connected/flavors/GPLAY"
|
||||
fi
|
||||
|
||||
if [ -e build/reports/tests/testGplayDebugUnitTest ] ; then
|
||||
TYPE="Unit"
|
||||
upload "build/reports/tests/testGplayDebugUnitTest"
|
||||
fi
|
||||
|
||||
if [ -e build/reports/shot/verification ] ; then
|
||||
TYPE="Screenshot"
|
||||
upload "build/reports/shot/verification"
|
||||
fi
|
||||
fi
|
||||
|
||||
cd $FOLDER
|
||||
|
||||
find . -type d -exec curl -u $USER:$PASS -X MKCOL $URL/$REMOTE_FOLDER/$(echo {} | sed s#\./##) \;
|
||||
find . -type f -exec curl -u $USER:$PASS -X PUT $URL/$REMOTE_FOLDER/$(echo {} | sed s#\./##) --upload-file {} \;
|
||||
|
||||
echo "Uploaded failing tests to https://www.kaminsky.me/nc-dev/android-integrationTests/$REMOTE_FOLDER"
|
||||
|
||||
curl -u $6:$7 -X POST https://api.github.com/repos/nextcloud/android/issues/$5/comments \
|
||||
-d "{ \"body\" : \"$TYPE test failed: https://www.kaminsky.me/nc-dev/android-integrationTests/$REMOTE_FOLDER \" }"
|
||||
|
||||
exit 1
|
||||
@@ -1,18 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
counter=0
|
||||
status=""
|
||||
counter=0
|
||||
checkcounter=0
|
||||
|
||||
until [[ $status = "false" ]]; do
|
||||
status=$(curl 2>/dev/null "http://$1/status.php" | jq .maintenance)
|
||||
echo "($checkcounter) $status"
|
||||
|
||||
if [[ "$status" =~ "false" || "$status" = "" ]]; then
|
||||
let "counter += 1"
|
||||
if [[ $counter -gt 2 ]]; then
|
||||
if [[ $counter -gt 10 ]]; then
|
||||
echo "Failed to wait for server"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
let "checkcounter += 1"
|
||||
sleep 10
|
||||
done
|
||||
|
||||
echo "($checkcounter) Done"
|
||||
|
After Width: | Height: | Size: 73 KiB |
@@ -28,18 +28,37 @@ import android.app.Activity;
|
||||
import com.facebook.testing.screenshot.Screenshot;
|
||||
import com.owncloud.android.AbstractIT;
|
||||
import com.owncloud.android.R;
|
||||
import com.owncloud.android.datamodel.OCFile;
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
|
||||
import com.owncloud.android.lib.resources.files.CreateFolderRemoteOperation;
|
||||
import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
|
||||
import com.owncloud.android.lib.resources.files.SearchRemoteOperation;
|
||||
import com.owncloud.android.lib.resources.shares.CreateShareRemoteOperation;
|
||||
import com.owncloud.android.lib.resources.shares.GetShareesRemoteOperation;
|
||||
import com.owncloud.android.lib.resources.shares.OCShare;
|
||||
import com.owncloud.android.lib.resources.shares.ShareType;
|
||||
import com.owncloud.android.operations.CreateFolderOperation;
|
||||
import com.owncloud.android.ui.activity.FileDisplayActivity;
|
||||
import com.owncloud.android.ui.events.SearchEvent;
|
||||
|
||||
import org.greenrobot.eventbus.EventBus;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
import androidx.test.espresso.contrib.DrawerActions;
|
||||
import androidx.test.espresso.contrib.NavigationViewActions;
|
||||
import androidx.test.espresso.intent.rule.IntentsTestRule;
|
||||
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.matcher.ViewMatchers.withId;
|
||||
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
|
||||
|
||||
public class FileDisplayActivityIT extends AbstractIT {
|
||||
@@ -52,10 +71,10 @@ public class FileDisplayActivityIT extends AbstractIT {
|
||||
Manifest.permission.WRITE_EXTERNAL_STORAGE);
|
||||
|
||||
@Test
|
||||
public void open() throws InterruptedException {
|
||||
public void open() {
|
||||
Activity sut = activityRule.launchActivity(null);
|
||||
|
||||
Thread.sleep(3000);
|
||||
shortSleep();
|
||||
|
||||
Screenshot.snapActivity(sut).record();
|
||||
}
|
||||
@@ -69,6 +88,69 @@ public class FileDisplayActivityIT extends AbstractIT {
|
||||
Screenshot.snapActivity(sut).record();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void showShares() throws JSONException {
|
||||
assertTrue(new ExistenceCheckRemoteOperation("/shareToAdmin/", true).execute(client).isSuccess());
|
||||
assertTrue(new CreateFolderRemoteOperation("/shareToAdmin/", true).execute(client).isSuccess());
|
||||
assertTrue(new CreateFolderRemoteOperation("/shareToGroup/", true).execute(client).isSuccess());
|
||||
assertTrue(new CreateFolderRemoteOperation("/shareViaLink/", true).execute(client).isSuccess());
|
||||
assertTrue(new CreateFolderRemoteOperation("/noShare/", true).execute(client).isSuccess());
|
||||
assertTrue(new CreateFolderRemoteOperation("/shareToCircle/", true).execute(client).isSuccess());
|
||||
|
||||
// share folder to user "admin"
|
||||
assertTrue(new CreateShareRemoteOperation("/shareToAdmin/",
|
||||
ShareType.USER,
|
||||
"admin",
|
||||
false,
|
||||
"",
|
||||
OCShare.MAXIMUM_PERMISSIONS_FOR_FOLDER)
|
||||
.execute(client).isSuccess());
|
||||
|
||||
// share folder via public link
|
||||
assertTrue(new CreateShareRemoteOperation("/shareViaLink/",
|
||||
ShareType.PUBLIC_LINK,
|
||||
"",
|
||||
true,
|
||||
"",
|
||||
OCShare.READ_PERMISSION_FLAG)
|
||||
.execute(client).isSuccess());
|
||||
|
||||
// share folder to group
|
||||
Assert.assertTrue(new CreateShareRemoteOperation("/shareToGroup/",
|
||||
ShareType.GROUP,
|
||||
"users",
|
||||
false,
|
||||
"",
|
||||
OCShare.DEFAULT_PERMISSION)
|
||||
.execute(client).isSuccess());
|
||||
|
||||
// share folder to circle
|
||||
// get share
|
||||
RemoteOperationResult searchResult = new GetShareesRemoteOperation("publicCircle", 1, 50).execute(client);
|
||||
assertTrue(searchResult.getLogMessage(), searchResult.isSuccess());
|
||||
|
||||
JSONObject resultJson = (JSONObject) searchResult.getData().get(0);
|
||||
String circleId = resultJson.getJSONObject("value").getString("shareWith");
|
||||
|
||||
assertTrue(new CreateShareRemoteOperation("/shareToCircle/",
|
||||
ShareType.CIRCLE,
|
||||
circleId,
|
||||
false,
|
||||
"",
|
||||
OCShare.DEFAULT_PERMISSION)
|
||||
.execute(client).isSuccess());
|
||||
|
||||
Activity sut = activityRule.launchActivity(null);
|
||||
|
||||
getInstrumentation().waitForIdleSync();
|
||||
|
||||
EventBus.getDefault().post(new SearchEvent("", SearchRemoteOperation.SearchType.SHARED_FILTER));
|
||||
|
||||
getInstrumentation().waitForIdleSync();
|
||||
|
||||
Screenshot.snapActivity(sut).record();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void showAccounts() {
|
||||
Activity sut = activityRule.launchActivity(null);
|
||||
@@ -78,4 +160,31 @@ public class FileDisplayActivityIT extends AbstractIT {
|
||||
|
||||
Screenshot.snapActivity(sut).record();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void allFiles() {
|
||||
// ActivityScenario<FileDisplayActivity> sut = ActivityScenario.launch(FileDisplayActivity.class);
|
||||
FileDisplayActivity sut = activityRule.launchActivity(null);
|
||||
|
||||
// given test folder
|
||||
assertTrue(new CreateFolderOperation("/test/", true).execute(client, getStorageManager()).isSuccess());
|
||||
|
||||
// navigate into it
|
||||
OCFile test = getStorageManager().getFileByPath("/test/");
|
||||
sut.setFile(test);
|
||||
sut.startSyncFolderOperation(test, false);
|
||||
|
||||
assertEquals(getStorageManager().getFileByPath("/test/"), sut.getCurrentDir());
|
||||
|
||||
// open drawer
|
||||
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
|
||||
|
||||
// click "all files"
|
||||
onView(withId(R.id.nav_view))
|
||||
.perform(NavigationViewActions.navigateTo(R.id.nav_all_files));
|
||||
|
||||
// then should be in root again
|
||||
shortSleep();
|
||||
assertEquals(getStorageManager().getFileByPath("/"), sut.getCurrentDir());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
*
|
||||
* 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.util.Log
|
||||
import org.junit.rules.TestRule
|
||||
import org.junit.runner.Description
|
||||
import org.junit.runners.model.Statement
|
||||
|
||||
/**
|
||||
* C&p from https://stackoverflow.com/questions/45635833/how-can-i-use-flakytest-annotation-now on 18.03.2020
|
||||
*/
|
||||
class RetryTestRule(val retryCount: Int = 5) : TestRule {
|
||||
|
||||
private val TAG = RetryTestRule::class.java.simpleName
|
||||
|
||||
override fun apply(base: Statement, description: Description): Statement {
|
||||
return statement(base, description)
|
||||
}
|
||||
|
||||
private fun statement(base: Statement, description: Description): Statement {
|
||||
return object : Statement() {
|
||||
|
||||
override fun evaluate() {
|
||||
Log.e(TAG, "Evaluating ${description.methodName}")
|
||||
|
||||
var caughtThrowable: Throwable? = null
|
||||
|
||||
for (i in 0 until retryCount) {
|
||||
try {
|
||||
base.evaluate()
|
||||
return
|
||||
} catch (t: Throwable) {
|
||||
caughtThrowable = t
|
||||
Log.e(TAG, description.methodName + ": run " + (i + 1) + " failed")
|
||||
}
|
||||
}
|
||||
|
||||
Log.e(TAG, description.methodName + ": giving up after " + retryCount + " failures")
|
||||
if (caughtThrowable != null)
|
||||
throw caughtThrowable
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
/*
|
||||
* 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.jobs
|
||||
|
||||
import androidx.lifecycle.LiveData
|
||||
import androidx.lifecycle.MutableLiveData
|
||||
import androidx.lifecycle.Observer
|
||||
import androidx.test.annotation.UiThreadTest
|
||||
import androidx.work.Data
|
||||
import androidx.work.ExistingPeriodicWorkPolicy
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.OneTimeWorkRequest
|
||||
import androidx.work.PeriodicWorkRequest
|
||||
import androidx.work.WorkInfo
|
||||
import androidx.work.WorkManager
|
||||
import com.nextcloud.client.account.User
|
||||
import com.nextcloud.client.core.Clock
|
||||
import com.nhaarman.mockitokotlin2.KArgumentCaptor
|
||||
import com.nhaarman.mockitokotlin2.any
|
||||
import com.nhaarman.mockitokotlin2.argThat
|
||||
import com.nhaarman.mockitokotlin2.argumentCaptor
|
||||
import com.nhaarman.mockitokotlin2.eq
|
||||
import com.nhaarman.mockitokotlin2.mock
|
||||
import com.nhaarman.mockitokotlin2.verify
|
||||
import com.nhaarman.mockitokotlin2.whenever
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.junit.runners.Suite
|
||||
import org.mockito.ArgumentMatcher
|
||||
import java.util.Date
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.TimeoutException
|
||||
|
||||
/**
|
||||
* When using IDE to run enire Suite, make sure tests are run using Android Instrumentation Test
|
||||
* runner. By default IDE runs normal JUnit - this is AS problem. One must configure the
|
||||
* test run manually.
|
||||
*/
|
||||
@RunWith(Suite::class)
|
||||
@Suite.SuiteClasses(
|
||||
BackgroundJobManagerTest.Manager::class,
|
||||
BackgroundJobManagerTest.ContentObserver::class,
|
||||
BackgroundJobManagerTest.PeriodicContactsBackup::class,
|
||||
BackgroundJobManagerTest.ImmediateContactsBackup::class,
|
||||
BackgroundJobManagerTest.Tags::class
|
||||
)
|
||||
class BackgroundJobManagerTest {
|
||||
|
||||
/**
|
||||
* Used to help with ambiguous type inference
|
||||
*/
|
||||
class IsOneTimeWorkRequest : ArgumentMatcher<OneTimeWorkRequest> {
|
||||
override fun matches(argument: OneTimeWorkRequest?): Boolean = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to help with ambiguous type inference
|
||||
*/
|
||||
class IsPeriodicWorkRequest : ArgumentMatcher<PeriodicWorkRequest> {
|
||||
override fun matches(argument: PeriodicWorkRequest?): Boolean = true
|
||||
}
|
||||
|
||||
abstract class Fixture {
|
||||
companion object {
|
||||
internal const val USER_ACCOUNT_NAME = "user@nextcloud"
|
||||
internal val TIMESTAMP = System.currentTimeMillis()
|
||||
}
|
||||
internal lateinit var user: User
|
||||
internal lateinit var workManager: WorkManager
|
||||
internal lateinit var clock: Clock
|
||||
internal lateinit var backgroundJobManager: BackgroundJobManagerImpl
|
||||
|
||||
@Before
|
||||
fun setUpFixture() {
|
||||
user = mock()
|
||||
whenever(user.accountName).thenReturn(USER_ACCOUNT_NAME)
|
||||
workManager = mock()
|
||||
clock = mock()
|
||||
whenever(clock.currentTime).thenReturn(TIMESTAMP)
|
||||
whenever(clock.currentDate).thenReturn(Date(TIMESTAMP))
|
||||
backgroundJobManager = BackgroundJobManagerImpl(workManager, clock)
|
||||
}
|
||||
|
||||
fun assertHasRequiredTags(tags: Set<String>, jobName: String, user: User? = null) {
|
||||
assertTrue("""'all' tag is mandatory""", tags.contains("*"))
|
||||
assertTrue("name tag is mandatory", tags.contains(BackgroundJobManagerImpl.formatNameTag(jobName, user)))
|
||||
assertTrue("timestamp tag is mandatory", tags.contains(BackgroundJobManagerImpl.formatTimeTag(TIMESTAMP)))
|
||||
if (user != null) {
|
||||
assertTrue("user tag is mandatory", tags.contains(BackgroundJobManagerImpl.formatUserTag(user)))
|
||||
}
|
||||
}
|
||||
|
||||
fun buildWorkInfo(index: Long): WorkInfo = WorkInfo(
|
||||
UUID.randomUUID(),
|
||||
WorkInfo.State.RUNNING,
|
||||
Data.Builder().build(),
|
||||
listOf(BackgroundJobManagerImpl.formatTimeTag(1581820284000)),
|
||||
Data.Builder().build(),
|
||||
1
|
||||
)
|
||||
}
|
||||
|
||||
class Manager : Fixture() {
|
||||
|
||||
class SyncObserver<T> : Observer<T> {
|
||||
val latch = CountDownLatch(1)
|
||||
var value: T? = null
|
||||
override fun onChanged(t: T) {
|
||||
value = t
|
||||
latch.countDown()
|
||||
}
|
||||
|
||||
fun getValue(timeout: Long = 3, timeUnit: TimeUnit = TimeUnit.SECONDS): T? {
|
||||
val result = latch.await(timeout, timeUnit)
|
||||
if (!result) {
|
||||
throw TimeoutException()
|
||||
}
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@UiThreadTest
|
||||
fun get_all_job_info() {
|
||||
// GIVEN
|
||||
// work manager has 2 registered workers
|
||||
val platformWorkInfo = listOf(
|
||||
buildWorkInfo(0),
|
||||
buildWorkInfo(1),
|
||||
buildWorkInfo(2)
|
||||
)
|
||||
val lv = MutableLiveData<List<WorkInfo>>()
|
||||
lv.value = platformWorkInfo
|
||||
whenever(workManager.getWorkInfosByTagLiveData(eq("*"))).thenReturn(lv)
|
||||
|
||||
// WHEN
|
||||
// job info for all jobs is requested
|
||||
val jobs = backgroundJobManager.jobs
|
||||
|
||||
// THEN
|
||||
// live data with job info is returned
|
||||
// live data contains 2 job info instances
|
||||
// job info is sorted by timestamp from newest to oldest
|
||||
assertNotNull(jobs)
|
||||
val observer = SyncObserver<List<JobInfo>>()
|
||||
jobs.observeForever(observer)
|
||||
val jobInfo = observer.getValue()
|
||||
assertNotNull(jobInfo)
|
||||
assertEquals(platformWorkInfo.size, jobInfo?.size)
|
||||
jobInfo?.let {
|
||||
assertEquals(platformWorkInfo[2].id, it[0].id)
|
||||
assertEquals(platformWorkInfo[1].id, it[1].id)
|
||||
assertEquals(platformWorkInfo[0].id, it[2].id)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun cancel_all_jobs() {
|
||||
// WHEN
|
||||
// all jobs are cancelled
|
||||
backgroundJobManager.cancelAllJobs()
|
||||
|
||||
// THEN
|
||||
// all jobs with * tag are cancelled
|
||||
verify(workManager).cancelAllWorkByTag(BackgroundJobManagerImpl.TAG_ALL)
|
||||
}
|
||||
}
|
||||
|
||||
class ContentObserver : Fixture() {
|
||||
|
||||
private lateinit var request: OneTimeWorkRequest
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
val requestCaptor: KArgumentCaptor<OneTimeWorkRequest> = argumentCaptor()
|
||||
backgroundJobManager.scheduleContentObserverJob()
|
||||
verify(workManager).enqueueUniqueWork(
|
||||
any(),
|
||||
any(),
|
||||
requestCaptor.capture()
|
||||
)
|
||||
assertEquals(1, requestCaptor.allValues.size)
|
||||
request = requestCaptor.firstValue
|
||||
}
|
||||
|
||||
@Test
|
||||
fun job_is_unique() {
|
||||
verify(workManager).enqueueUniqueWork(
|
||||
eq(BackgroundJobManagerImpl.JOB_CONTENT_OBSERVER),
|
||||
eq(ExistingWorkPolicy.KEEP),
|
||||
argThat(IsOneTimeWorkRequest())
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun job_request_has_mandatory_tags() {
|
||||
assertHasRequiredTags(request.tags, BackgroundJobManagerImpl.JOB_CONTENT_OBSERVER)
|
||||
}
|
||||
}
|
||||
|
||||
class PeriodicContactsBackup : Fixture() {
|
||||
private lateinit var request: PeriodicWorkRequest
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
val requestCaptor: KArgumentCaptor<PeriodicWorkRequest> = argumentCaptor()
|
||||
backgroundJobManager.schedulePeriodicContactsBackup(user)
|
||||
verify(workManager).enqueueUniquePeriodicWork(
|
||||
any(),
|
||||
any(),
|
||||
requestCaptor.capture()
|
||||
)
|
||||
assertEquals(1, requestCaptor.allValues.size)
|
||||
request = requestCaptor.firstValue
|
||||
}
|
||||
|
||||
@Test
|
||||
fun job_is_unique_for_user() {
|
||||
verify(workManager).enqueueUniquePeriodicWork(
|
||||
eq(BackgroundJobManagerImpl.JOB_PERIODIC_CONTACTS_BACKUP),
|
||||
eq(ExistingPeriodicWorkPolicy.KEEP),
|
||||
argThat(IsPeriodicWorkRequest())
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun job_request_has_mandatory_tags() {
|
||||
assertHasRequiredTags(request.tags, BackgroundJobManagerImpl.JOB_PERIODIC_CONTACTS_BACKUP, user)
|
||||
}
|
||||
}
|
||||
|
||||
class ImmediateContactsBackup : Fixture() {
|
||||
|
||||
private lateinit var workInfo: MutableLiveData<WorkInfo>
|
||||
private lateinit var jobInfo: LiveData<JobInfo?>
|
||||
private lateinit var request: OneTimeWorkRequest
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
val requestCaptor: KArgumentCaptor<OneTimeWorkRequest> = argumentCaptor()
|
||||
workInfo = MutableLiveData()
|
||||
whenever(workManager.getWorkInfoByIdLiveData(any())).thenReturn(workInfo)
|
||||
jobInfo = backgroundJobManager.startImmediateContactsBackup(user)
|
||||
verify(workManager).enqueueUniqueWork(
|
||||
any(),
|
||||
any(),
|
||||
requestCaptor.capture()
|
||||
)
|
||||
assertEquals(1, requestCaptor.allValues.size)
|
||||
request = requestCaptor.firstValue
|
||||
}
|
||||
|
||||
@Test
|
||||
fun job_is_unique_for_user() {
|
||||
verify(workManager).enqueueUniqueWork(
|
||||
eq(BackgroundJobManagerImpl.JOB_IMMEDIATE_CONTACTS_BACKUP),
|
||||
eq(ExistingWorkPolicy.KEEP),
|
||||
argThat(IsOneTimeWorkRequest())
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun job_request_has_mandatory_tags() {
|
||||
assertHasRequiredTags(request.tags, BackgroundJobManagerImpl.JOB_IMMEDIATE_CONTACTS_BACKUP, user)
|
||||
}
|
||||
|
||||
@Test
|
||||
@UiThreadTest
|
||||
fun job_info_is_obtained_from_work_info() {
|
||||
// GIVEN
|
||||
// work info is available
|
||||
workInfo.value = buildWorkInfo(0)
|
||||
|
||||
// WHEN
|
||||
// job info has listener
|
||||
jobInfo.observeForever {}
|
||||
|
||||
// THEN
|
||||
// converted value is available
|
||||
assertNotNull(jobInfo.value)
|
||||
assertEquals(workInfo.value?.id, jobInfo.value?.id)
|
||||
}
|
||||
}
|
||||
|
||||
class Tags {
|
||||
@Test
|
||||
fun split_tag_key_and_value() {
|
||||
// GIVEN
|
||||
// valid tag
|
||||
// tag has colons in value part
|
||||
val tag = "${BackgroundJobManagerImpl.TAG_PREFIX_NAME}:value:with:colons and spaces"
|
||||
|
||||
// WHEN
|
||||
// tag is parsed
|
||||
val parsedTag = BackgroundJobManagerImpl.parseTag(tag)
|
||||
|
||||
// THEN
|
||||
// key-value pair is returned
|
||||
// key is first
|
||||
// value with colons is second
|
||||
assertNotNull(parsedTag)
|
||||
assertEquals(BackgroundJobManagerImpl.TAG_PREFIX_NAME, parsedTag?.first)
|
||||
assertEquals("value:with:colons and spaces", parsedTag?.second)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tags_with_invalid_prefixes_are_rejected() {
|
||||
// GIVEN
|
||||
// tag prefix is not on allowed prefixes list
|
||||
val tag = "invalidprefix:value"
|
||||
BackgroundJobManagerImpl.PREFIXES.forEach {
|
||||
assertFalse(tag.startsWith(it))
|
||||
}
|
||||
|
||||
// WHEN
|
||||
// tag is parsed
|
||||
val parsedTag = BackgroundJobManagerImpl.parseTag(tag)
|
||||
|
||||
// THEN
|
||||
// tag is rejected
|
||||
assertNull(parsedTag)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun strings_without_colon_are_rejected() {
|
||||
// GIVEN
|
||||
// strings that are not tags
|
||||
val tags = listOf(
|
||||
BackgroundJobManagerImpl.TAG_ALL,
|
||||
BackgroundJobManagerImpl.TAG_PREFIX_NAME,
|
||||
"simplestring",
|
||||
""
|
||||
)
|
||||
|
||||
tags.forEach {
|
||||
// WHEN
|
||||
// string is parsed
|
||||
val parsedTag = BackgroundJobManagerImpl.parseTag(it)
|
||||
|
||||
// THEN
|
||||
// tag is rejected
|
||||
assertNull(parsedTag)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
* 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.migrations
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.nhaarman.mockitokotlin2.any
|
||||
import com.nhaarman.mockitokotlin2.eq
|
||||
import com.nhaarman.mockitokotlin2.mock
|
||||
import com.nhaarman.mockitokotlin2.whenever
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
class MigrationsDbTest {
|
||||
|
||||
private lateinit var context: Context
|
||||
private lateinit var store: MockSharedPreferences
|
||||
private lateinit var db: MigrationsDb
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
context = InstrumentationRegistry.getInstrumentation().context
|
||||
store = MockSharedPreferences()
|
||||
assertTrue("State from previous test run found?", store.all.isEmpty())
|
||||
db = MigrationsDb(store)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun applied_migrations_are_returned_in_order() {
|
||||
// GIVEN
|
||||
// some migrations are marked as applied
|
||||
// migration ids are stored in random order
|
||||
val mockStore: SharedPreferences = mock()
|
||||
val storedMigrationIds = LinkedHashSet<String>()
|
||||
storedMigrationIds.apply {
|
||||
add("3")
|
||||
add("0")
|
||||
add("2")
|
||||
add("1")
|
||||
}
|
||||
whenever(mockStore.getStringSet(eq(MigrationsDb.DB_KEY_APPLIED_MIGRATIONS), any()))
|
||||
.thenReturn(storedMigrationIds)
|
||||
|
||||
// WHEN
|
||||
// applied migration ids are retrieved
|
||||
val db = MigrationsDb(mockStore)
|
||||
val ids = db.getAppliedMigrations()
|
||||
|
||||
// THEN
|
||||
// returned list is sorted
|
||||
assertEquals(ids, ids.sorted())
|
||||
}
|
||||
|
||||
@Test
|
||||
@Suppress("MagicNumber")
|
||||
fun registering_new_applied_migration_preserves_old_ids() {
|
||||
// WHEN
|
||||
// some applied migrations are registered
|
||||
val appliedMigrationIds = setOf("0", "1", "2")
|
||||
store.edit().putStringSet(MigrationsDb.DB_KEY_APPLIED_MIGRATIONS, appliedMigrationIds).apply()
|
||||
|
||||
// WHEN
|
||||
// new set of migration ids are registered
|
||||
// some ids are added again
|
||||
db.addAppliedMigration(2, 3, 4)
|
||||
|
||||
// THEN
|
||||
// new ids are appended to set of existing ids
|
||||
val expectedIds = setOf("0", "1", "2", "3", "4")
|
||||
val storedIds = store.getStringSet(MigrationsDb.DB_KEY_APPLIED_MIGRATIONS, mutableSetOf())
|
||||
assertEquals(expectedIds, storedIds)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failed_status_sets_status_flag_and_error_message() {
|
||||
// GIVEN
|
||||
// failure flag is not set
|
||||
assertFalse(db.isFailed)
|
||||
|
||||
// WHEN
|
||||
// failure status is set
|
||||
val failureReason = "error message"
|
||||
db.setFailed(0, failureReason)
|
||||
|
||||
// THEN
|
||||
// failed flag is set
|
||||
// error message is set
|
||||
assertTrue(db.isFailed)
|
||||
assertEquals(failureReason, db.failureReason)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun last_migrated_version_is_set() {
|
||||
// GIVEN
|
||||
// last migrated version is not set
|
||||
val oldVersion = db.lastMigratedVersion
|
||||
assertEquals(MigrationsDb.NO_LAST_MIGRATED_VERSION, oldVersion)
|
||||
|
||||
// WHEN
|
||||
// migrated version is set to a new value
|
||||
val newVersion = 200
|
||||
db.lastMigratedVersion = newVersion
|
||||
|
||||
// THEN
|
||||
// new value is stored
|
||||
assertEquals(newVersion, db.lastMigratedVersion)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
/*
|
||||
* 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.migrations
|
||||
|
||||
import androidx.test.annotation.UiThreadTest
|
||||
import com.nextcloud.client.appinfo.AppInfo
|
||||
import com.nextcloud.client.core.ManualAsyncRunner
|
||||
import com.nhaarman.mockitokotlin2.inOrder
|
||||
import com.nhaarman.mockitokotlin2.mock
|
||||
import com.nhaarman.mockitokotlin2.never
|
||||
import com.nhaarman.mockitokotlin2.verify
|
||||
import com.nhaarman.mockitokotlin2.whenever
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.mockito.Mock
|
||||
import org.mockito.MockitoAnnotations
|
||||
|
||||
class MigrationsManagerTest {
|
||||
|
||||
companion object {
|
||||
const val OLD_APP_VERSION = 41
|
||||
const val NEW_APP_VERSION = 42
|
||||
}
|
||||
|
||||
lateinit var migrationStep1: Runnable
|
||||
lateinit var migrationStep2: Runnable
|
||||
lateinit var migrationStep3: Runnable
|
||||
lateinit var migrations: List<Migrations.Step>
|
||||
|
||||
@Mock
|
||||
lateinit var appInfo: AppInfo
|
||||
|
||||
lateinit var migrationsDbStore: MockSharedPreferences
|
||||
lateinit var migrationsDb: MigrationsDb
|
||||
|
||||
lateinit var asyncRunner: ManualAsyncRunner
|
||||
|
||||
internal lateinit var migrationsManager: MigrationsManagerImpl
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
MockitoAnnotations.initMocks(this)
|
||||
migrationStep1 = mock()
|
||||
migrationStep2 = mock()
|
||||
migrationStep3 = mock()
|
||||
migrations = listOf(
|
||||
object : Migrations.Step(0, "first migration", true) {
|
||||
override fun run() {
|
||||
migrationStep1.run()
|
||||
}
|
||||
},
|
||||
object : Migrations.Step(1, "second optional migration", false) {
|
||||
override fun run() {
|
||||
migrationStep2.run()
|
||||
}
|
||||
},
|
||||
object : Migrations.Step(2, "third migration", true) {
|
||||
override fun run() {
|
||||
migrationStep3.run()
|
||||
}
|
||||
}
|
||||
)
|
||||
asyncRunner = ManualAsyncRunner()
|
||||
migrationsDbStore = MockSharedPreferences()
|
||||
migrationsDb = MigrationsDb(migrationsDbStore)
|
||||
|
||||
whenever(appInfo.versionCode).thenReturn(NEW_APP_VERSION)
|
||||
migrationsManager = MigrationsManagerImpl(
|
||||
appInfo = appInfo,
|
||||
migrationsDb = migrationsDb,
|
||||
asyncRunner = asyncRunner,
|
||||
migrations = migrations
|
||||
)
|
||||
}
|
||||
|
||||
private fun assertMigrationsRun(vararg migrationSteps: Runnable) {
|
||||
inOrder(migrationSteps).apply {
|
||||
migrationSteps.forEach {
|
||||
verify(it.run())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun inital_status_is_unknown() {
|
||||
// GIVEN
|
||||
// migration manager has not been used yets
|
||||
|
||||
// THEN
|
||||
// status is not set
|
||||
assertEquals(MigrationsManager.Status.UNKNOWN, migrationsManager.status.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
@UiThreadTest
|
||||
fun migrations_are_scheduled_on_background_thread() {
|
||||
// GIVEN
|
||||
// migrations can be applied
|
||||
assertEquals(0, migrationsDb.getAppliedMigrations().size)
|
||||
|
||||
// WHEN
|
||||
// migration is started
|
||||
val count = migrationsManager.startMigration()
|
||||
|
||||
// THEN
|
||||
// all migrations are scheduled on background thread
|
||||
// single task is scheduled
|
||||
assertEquals(migrations.size, count)
|
||||
assertEquals(1, asyncRunner.size)
|
||||
assertEquals(MigrationsManager.Status.RUNNING, migrationsManager.status.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
@UiThreadTest
|
||||
fun applied_migrations_are_recorded() {
|
||||
// GIVEN
|
||||
// no migrations are applied yet
|
||||
// current app version is newer then last recorded migrated version
|
||||
whenever(appInfo.versionCode).thenReturn(NEW_APP_VERSION)
|
||||
migrationsDb.lastMigratedVersion = OLD_APP_VERSION
|
||||
|
||||
// WHEN
|
||||
// migration is run
|
||||
val count = migrationsManager.startMigration()
|
||||
assertTrue(asyncRunner.runOne())
|
||||
|
||||
// THEN
|
||||
// total migrations count is returned
|
||||
// migration functions are called
|
||||
// applied migrations are recorded
|
||||
// new app version code is recorded
|
||||
assertEquals(migrations.size, count)
|
||||
inOrder(migrationStep1, migrationStep2, migrationStep3).apply {
|
||||
verify(migrationStep1).run()
|
||||
verify(migrationStep2).run()
|
||||
verify(migrationStep3).run()
|
||||
}
|
||||
val allAppliedIds = migrations.map { it.id }
|
||||
assertEquals(allAppliedIds, migrationsDb.getAppliedMigrations())
|
||||
assertEquals(NEW_APP_VERSION, migrationsDb.lastMigratedVersion)
|
||||
}
|
||||
|
||||
@Test
|
||||
@UiThreadTest
|
||||
fun migration_error_is_recorded() {
|
||||
// GIVEN
|
||||
// no migrations applied yet
|
||||
// no prior failed migrations
|
||||
assertFalse(migrationsDb.isFailed)
|
||||
assertEquals(MigrationsDb.NO_FAILED_MIGRATION_ID, migrationsDb.failedMigrationId)
|
||||
|
||||
// WHEN
|
||||
// migrations are applied
|
||||
// one migration throws
|
||||
val lastMigration = migrations.findLast { it.mandatory } ?: throw IllegalStateException("Test fixture error")
|
||||
val errorMessage = "error message"
|
||||
whenever(lastMigration.run()).thenThrow(RuntimeException(errorMessage))
|
||||
migrationsManager.startMigration()
|
||||
assertTrue(asyncRunner.runOne())
|
||||
|
||||
// THEN
|
||||
// failure is marked in the migration db
|
||||
// failure message is recorded
|
||||
// failed migration id is recorded
|
||||
assertEquals(MigrationsManager.Status.FAILED, migrationsManager.status.value)
|
||||
assertTrue(migrationsDb.isFailed)
|
||||
assertEquals(errorMessage, migrationsDb.failureReason)
|
||||
assertEquals(lastMigration.id, migrationsDb.failedMigrationId)
|
||||
}
|
||||
|
||||
@Test
|
||||
@UiThreadTest
|
||||
fun migrations_are_not_run_if_already_run_for_an_app_version() {
|
||||
// GIVEN
|
||||
// migrations were already run for the current app version
|
||||
whenever(appInfo.versionCode).thenReturn(NEW_APP_VERSION)
|
||||
migrationsDb.lastMigratedVersion = NEW_APP_VERSION
|
||||
|
||||
// WHEN
|
||||
// app is migrated again
|
||||
val migrationCount = migrationsManager.startMigration()
|
||||
|
||||
// THEN
|
||||
// migration processing is skipped entirely
|
||||
// status is set to applied
|
||||
assertEquals(0, migrationCount)
|
||||
listOf(migrationStep1, migrationStep2, migrationStep3).forEach {
|
||||
verify(it, never()).run()
|
||||
}
|
||||
assertEquals(MigrationsManager.Status.APPLIED, migrationsManager.status.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
@UiThreadTest
|
||||
fun new_app_version_is_marked_as_migrated_if_no_new_migrations_are_available() {
|
||||
// GIVEN
|
||||
// migrations were applied in previous version
|
||||
// new version has no new migrations
|
||||
whenever(appInfo.versionCode).thenReturn(NEW_APP_VERSION)
|
||||
migrationsDb.lastMigratedVersion = OLD_APP_VERSION
|
||||
migrations.forEach {
|
||||
migrationsDb.addAppliedMigration(it.id)
|
||||
}
|
||||
|
||||
// WHEN
|
||||
// migration is started
|
||||
val startedCount = migrationsManager.startMigration()
|
||||
|
||||
// THEN
|
||||
// no new migrations are run
|
||||
// new version is marked as migrated
|
||||
assertEquals(0, startedCount)
|
||||
assertEquals(
|
||||
NEW_APP_VERSION,
|
||||
migrationsDb.lastMigratedVersion
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
@UiThreadTest
|
||||
fun optional_migration_failure_does_not_trigger_a_migration_failure() {
|
||||
// GIVEN
|
||||
// pending migrations
|
||||
// mandatory migrations are passing
|
||||
// one migration is optional and fails
|
||||
assertEquals("Fixture should provide 1 optional, failing migration",
|
||||
1,
|
||||
migrations.count { !it.mandatory }
|
||||
)
|
||||
val optionalFailingMigration = migrations.first { !it.mandatory }
|
||||
whenever(optionalFailingMigration.run()).thenThrow(RuntimeException())
|
||||
|
||||
// WHEN
|
||||
// migration is started
|
||||
val startedCount = migrationsManager.startMigration()
|
||||
asyncRunner.runOne()
|
||||
assertEquals(migrations.size, startedCount)
|
||||
|
||||
// THEN
|
||||
// mandatory migrations are marked as applied
|
||||
// optional failed migration is not marked
|
||||
// no error
|
||||
// status is applied
|
||||
// failed migration is available during next migration
|
||||
val appliedMigrations = migrations.filter { it.mandatory }.map { it.id }
|
||||
assertTrue("Fixture error", appliedMigrations.isNotEmpty())
|
||||
assertEquals(appliedMigrations, migrationsDb.getAppliedMigrations())
|
||||
assertFalse(migrationsDb.isFailed)
|
||||
assertEquals(MigrationsManager.Status.APPLIED, migrationsManager.status.value)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* 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.migrations
|
||||
|
||||
import android.content.SharedPreferences
|
||||
import java.lang.UnsupportedOperationException
|
||||
import java.util.TreeMap
|
||||
|
||||
/**
|
||||
* This shared preferences implementation uses in-memory value store
|
||||
* and it can be used in tests without using global, file-backed storage,
|
||||
* improving test isolation.
|
||||
*
|
||||
* The implementation is not thread-safe.
|
||||
*/
|
||||
@Suppress("TooManyFunctions")
|
||||
class MockSharedPreferences : SharedPreferences {
|
||||
|
||||
class MockEditor(val store: MutableMap<String?, Any?>) : SharedPreferences.Editor {
|
||||
|
||||
val editorStore: MutableMap<String?, Any?> = TreeMap()
|
||||
|
||||
override fun clear(): SharedPreferences.Editor = throw UnsupportedOperationException()
|
||||
|
||||
override fun putLong(key: String?, value: Long): SharedPreferences.Editor =
|
||||
throw UnsupportedOperationException("Implement as needed")
|
||||
|
||||
override fun putInt(key: String?, value: Int): SharedPreferences.Editor {
|
||||
editorStore.put(key, value)
|
||||
return this
|
||||
}
|
||||
|
||||
override fun remove(key: String?): SharedPreferences.Editor = throw UnsupportedOperationException()
|
||||
|
||||
override fun putBoolean(key: String?, value: Boolean): SharedPreferences.Editor {
|
||||
editorStore.put(key, value)
|
||||
return this
|
||||
}
|
||||
|
||||
override fun putStringSet(key: String?, values: MutableSet<String>?): SharedPreferences.Editor {
|
||||
editorStore.put(key, values?.toMutableSet())
|
||||
return this
|
||||
}
|
||||
|
||||
override fun commit(): Boolean = true
|
||||
|
||||
override fun putFloat(key: String?, value: Float): SharedPreferences.Editor =
|
||||
throw UnsupportedOperationException("Implement as needed")
|
||||
|
||||
override fun apply() = store.putAll(editorStore)
|
||||
|
||||
override fun putString(key: String?, value: String?): SharedPreferences.Editor {
|
||||
editorStore.put(key, value)
|
||||
return this
|
||||
}
|
||||
}
|
||||
|
||||
val store: MutableMap<String?, Any?> = TreeMap()
|
||||
|
||||
override fun contains(key: String?): Boolean = store.containsKey(key)
|
||||
override fun getBoolean(key: String?, defValue: Boolean): Boolean = store.getOrDefault(key, defValue) as Boolean
|
||||
|
||||
override fun unregisterOnSharedPreferenceChangeListener(
|
||||
listener: SharedPreferences.OnSharedPreferenceChangeListener?
|
||||
) = throw UnsupportedOperationException()
|
||||
|
||||
override fun getInt(key: String?, defValue: Int): Int = store.getOrDefault(key, defValue) as Int
|
||||
|
||||
override fun getAll(): MutableMap<String?, Any?> {
|
||||
return HashMap(store)
|
||||
}
|
||||
|
||||
override fun edit(): SharedPreferences.Editor {
|
||||
return MockEditor(store)
|
||||
}
|
||||
|
||||
override fun getLong(key: String?, defValue: Long): Long {
|
||||
throw UnsupportedOperationException()
|
||||
}
|
||||
|
||||
override fun getFloat(key: String?, defValue: Float): Float {
|
||||
throw UnsupportedOperationException()
|
||||
}
|
||||
|
||||
override fun getStringSet(key: String?, defValues: MutableSet<String>?): MutableSet<String>? {
|
||||
return store.getOrDefault(key, defValues) as MutableSet<String>?
|
||||
}
|
||||
|
||||
override fun registerOnSharedPreferenceChangeListener(
|
||||
listener: SharedPreferences.OnSharedPreferenceChangeListener?
|
||||
) = throw UnsupportedOperationException()
|
||||
|
||||
override fun getString(key: String?, defValue: String?): String? = store.getOrDefault(key, defValue) as String?
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* 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.migrations
|
||||
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotSame
|
||||
import org.junit.Assert.assertTrue
|
||||
|
||||
@Suppress("MagicNumber")
|
||||
class MockSharedPreferencesTest {
|
||||
|
||||
private lateinit var mock: MockSharedPreferences
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
mock = MockSharedPreferences()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getSetStringSet() {
|
||||
val value = setOf("alpha", "bravo", "charlie")
|
||||
mock.edit().putStringSet("key", value).apply()
|
||||
val copy = mock.getStringSet("key", mutableSetOf())
|
||||
assertNotSame(value, copy)
|
||||
assertEquals(value, copy)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getSetInt() {
|
||||
val value = 42
|
||||
val editor = mock.edit()
|
||||
editor.putInt("key", value)
|
||||
assertEquals(100, mock.getInt("key", 100))
|
||||
editor.apply()
|
||||
assertEquals(42, mock.getInt("key", 100))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getSetBoolean() {
|
||||
val value = true
|
||||
val editor = mock.edit()
|
||||
editor.putBoolean("key", value)
|
||||
assertFalse(mock.getBoolean("key", false))
|
||||
editor.apply()
|
||||
assertTrue(mock.getBoolean("key", false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getSetString() {
|
||||
val value = "a value"
|
||||
val editor = mock.edit()
|
||||
editor.putString("key", value)
|
||||
assertEquals("default", mock.getString("key", "default"))
|
||||
editor.apply()
|
||||
assertEquals("a value", mock.getString("key", "default"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getAll() {
|
||||
// GIVEN
|
||||
// few properties are stored in shared preferences
|
||||
mock.edit()
|
||||
.putInt("int", 1)
|
||||
.putBoolean("bool", true)
|
||||
.putString("string", "value")
|
||||
.putStringSet("stringSet", setOf("alpha", "bravo"))
|
||||
.apply()
|
||||
assertEquals(4, mock.store.size)
|
||||
|
||||
// WHEN
|
||||
// all properties are retrieved
|
||||
val all = mock.all
|
||||
|
||||
// THEN
|
||||
// returned map is a different instance
|
||||
// map is equal to internal storage
|
||||
assertNotSame(all, mock.store)
|
||||
assertEquals(all, mock.store)
|
||||
}
|
||||
}
|
||||
@@ -11,20 +11,26 @@ import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
|
||||
import com.facebook.testing.screenshot.Screenshot;
|
||||
import com.nextcloud.client.RetryTestRule;
|
||||
import com.nextcloud.client.account.UserAccountManager;
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl;
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager;
|
||||
import com.owncloud.android.lib.common.OwnCloudClient;
|
||||
import com.owncloud.android.lib.common.OwnCloudClientFactory;
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils;
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
|
||||
import com.owncloud.android.lib.resources.files.ReadFolderRemoteOperation;
|
||||
import com.owncloud.android.lib.resources.files.RemoveFileRemoteOperation;
|
||||
import com.owncloud.android.lib.resources.files.model.RemoteFile;
|
||||
import com.owncloud.android.utils.FileStorageUtils;
|
||||
|
||||
import org.apache.commons.httpclient.HttpStatus;
|
||||
import org.apache.commons.httpclient.methods.GetMethod;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.Rule;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
@@ -34,7 +40,6 @@ import java.util.Collection;
|
||||
|
||||
import androidx.test.espresso.contrib.DrawerActions;
|
||||
import androidx.test.espresso.intent.rule.IntentsTestRule;
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry;
|
||||
import androidx.test.runner.lifecycle.Stage;
|
||||
@@ -42,14 +47,16 @@ import androidx.test.runner.lifecycle.Stage;
|
||||
import static androidx.test.InstrumentationRegistry.getInstrumentation;
|
||||
import static androidx.test.espresso.Espresso.onView;
|
||||
import static androidx.test.espresso.matcher.ViewMatchers.withId;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
|
||||
/**
|
||||
* Common base for all integration tests
|
||||
*/
|
||||
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
//@RunWith(AndroidJUnit4.class)
|
||||
public abstract class AbstractIT {
|
||||
@Rule public RetryTestRule retryTestRule = new RetryTestRule();
|
||||
|
||||
protected static OwnCloudClient client;
|
||||
protected static Account account;
|
||||
@@ -91,6 +98,8 @@ public abstract class AbstractIT {
|
||||
createDummyFiles();
|
||||
|
||||
waitForServer(client, baseUrl);
|
||||
|
||||
deleteAllFiles(); // makes sure that no file/folder is in root
|
||||
} catch (OperationCanceledException e) {
|
||||
e.printStackTrace();
|
||||
} catch (AuthenticatorException e) {
|
||||
@@ -102,7 +111,27 @@ public abstract class AbstractIT {
|
||||
}
|
||||
}
|
||||
|
||||
FileDataStorageManager getStorageManager() {
|
||||
@After
|
||||
public void after() {
|
||||
deleteAllFiles();
|
||||
}
|
||||
|
||||
public static void deleteAllFiles() {
|
||||
RemoteOperationResult result = new ReadFolderRemoteOperation("/").execute(client);
|
||||
assertTrue(result.getLogMessage(), result.isSuccess());
|
||||
|
||||
for (Object object : result.getData()) {
|
||||
RemoteFile remoteFile = (RemoteFile) object;
|
||||
|
||||
if (!remoteFile.getRemotePath().equals("/")) {
|
||||
assertTrue(new RemoveFileRemoteOperation(remoteFile.getRemotePath())
|
||||
.execute(client).isSuccess());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected FileDataStorageManager getStorageManager() {
|
||||
return new FileDataStorageManager(account, targetContext.getContentResolver());
|
||||
}
|
||||
|
||||
@@ -164,7 +193,7 @@ public abstract class AbstractIT {
|
||||
protected void openDrawer(IntentsTestRule activityRule) throws InterruptedException {
|
||||
Activity sut = activityRule.launchActivity(null);
|
||||
|
||||
Thread.sleep(3000);
|
||||
shortSleep();
|
||||
|
||||
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
|
||||
|
||||
@@ -186,4 +215,20 @@ public abstract class AbstractIT {
|
||||
|
||||
return currentActivity;
|
||||
}
|
||||
|
||||
protected void shortSleep() {
|
||||
try {
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
protected void longSleep() {
|
||||
try {
|
||||
Thread.sleep(20000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,7 @@ public class ScreenshotsIT extends AbstractIT {
|
||||
openOverflowMenu();
|
||||
onView(anyOf(withText(R.string.action_switch_grid_view), withId(R.id.action_switch_view))).perform(click());
|
||||
|
||||
Thread.sleep(1000);
|
||||
shortSleep();
|
||||
|
||||
Screengrab.screenshot("01_gridView");
|
||||
|
||||
@@ -70,12 +70,12 @@ public class ScreenshotsIT extends AbstractIT {
|
||||
Assert.assertTrue(true); // if we reach this, everything is ok
|
||||
}
|
||||
|
||||
private void openOverflowMenu() throws InterruptedException {
|
||||
private void openOverflowMenu() {
|
||||
try {
|
||||
Espresso.openContextualActionModeOverflowMenu();
|
||||
} catch (NoActivityResumedException e) {
|
||||
ActivityScenario.launch(FileDisplayActivity.class);
|
||||
Thread.sleep(1000);
|
||||
shortSleep();
|
||||
Espresso.openContextualActionModeOverflowMenu();
|
||||
}
|
||||
}
|
||||
@@ -143,12 +143,12 @@ public class ScreenshotsIT extends AbstractIT {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void davdroidScreenshot() throws InterruptedException {
|
||||
public void davdroidScreenshot() {
|
||||
ActivityScenario.launch(SettingsActivity.class);
|
||||
|
||||
onData(PreferenceMatchers.withTitle(R.string.prefs_category_more)).perform(ViewActions.scrollTo());
|
||||
|
||||
Thread.sleep(1000);
|
||||
shortSleep();
|
||||
|
||||
Screengrab.screenshot("06_davdroid");
|
||||
|
||||
|
||||
@@ -120,7 +120,7 @@ public class UploadIT extends AbstractIT {
|
||||
account,
|
||||
null,
|
||||
ocUpload,
|
||||
false,
|
||||
FileUploader.NameCollisionPolicy.DEFAULT,
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
@@ -140,17 +140,17 @@ public class UploadIT extends AbstractIT {
|
||||
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt",
|
||||
"/testUpload/2/3/4/1.txt", account.name);
|
||||
UploadFileOperation newUpload = new UploadFileOperation(
|
||||
storageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
account,
|
||||
null,
|
||||
ocUpload,
|
||||
false,
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
false
|
||||
storageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
account,
|
||||
null,
|
||||
ocUpload,
|
||||
FileUploader.NameCollisionPolicy.DEFAULT,
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
false
|
||||
);
|
||||
newUpload.addRenameUploadListener(() -> {
|
||||
// dummy
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
/*
|
||||
*
|
||||
* 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.files.services
|
||||
|
||||
import com.evernote.android.job.JobRequest
|
||||
import com.nextcloud.client.account.UserAccountManager
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl
|
||||
import com.nextcloud.client.device.PowerManagementService
|
||||
import com.nextcloud.client.network.ConnectivityService
|
||||
import com.owncloud.android.AbstractIT
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager
|
||||
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 : AbstractIT() {
|
||||
var uploadsStorageManager: UploadsStorageManager? = null
|
||||
|
||||
val connectivityServiceMock: ConnectivityService = object : ConnectivityService {
|
||||
override fun isInternetWalled(): Boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
override fun isOnlineWithWifi(): Boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
override fun getActiveNetworkType(): JobRequest.NetworkType {
|
||||
return JobRequest.NetworkType.ANY
|
||||
}
|
||||
}
|
||||
|
||||
private val powerManagementServiceMock: PowerManagementService = object : PowerManagementService {
|
||||
override val isPowerSavingEnabled: Boolean
|
||||
get() = false
|
||||
|
||||
override val isPowerSavingExclusionAvailable: Boolean
|
||||
get() = false
|
||||
|
||||
override val isBatteryCharging: Boolean
|
||||
get() = false
|
||||
}
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
val contentResolver = targetContext.contentResolver
|
||||
val accountManager: UserAccountManager = UserAccountManagerImpl.fromContext(targetContext)
|
||||
uploadsStorageManager = UploadsStorageManager(accountManager, contentResolver)
|
||||
}
|
||||
|
||||
/**
|
||||
* uploads a file, overwrites it with an empty one, check if overwritten
|
||||
*/
|
||||
@Test
|
||||
fun testKeepLocalAndOverwriteRemote() {
|
||||
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
|
||||
val ocUpload = OCUpload(file.absolutePath, "/testFile.txt", account.name)
|
||||
|
||||
assertTrue(UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
account,
|
||||
null,
|
||||
ocUpload,
|
||||
FileUploader.NameCollisionPolicy.DEFAULT,
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
false)
|
||||
.setRemoteFolderToBeCreated()
|
||||
.execute(client, storageManager).isSuccess)
|
||||
|
||||
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
|
||||
assertTrue(result.isSuccess)
|
||||
|
||||
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
|
||||
|
||||
val ocUpload2 = OCUpload(getSavePath(account.name) + "/empty.txt", "/testFile.txt", account.name)
|
||||
|
||||
assertTrue(UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
account,
|
||||
null,
|
||||
ocUpload2,
|
||||
FileUploader.NameCollisionPolicy.OVERWRITE,
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
false)
|
||||
.execute(client, storageManager).isSuccess)
|
||||
|
||||
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
|
||||
assertTrue(result2.isSuccess)
|
||||
|
||||
assertEquals(0, (result2.data[0] as RemoteFile).length)
|
||||
}
|
||||
|
||||
/**
|
||||
* uploads a file, overwrites it with an empty one, check if overwritten
|
||||
*/
|
||||
@Test
|
||||
fun testKeepLocalAndOverwriteRemoteStatic() {
|
||||
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
|
||||
|
||||
FileUploader.uploadNewFile(
|
||||
targetContext,
|
||||
account,
|
||||
file.absolutePath,
|
||||
"/testFile.txt",
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
null,
|
||||
true,
|
||||
UploadFileOperation.CREATED_BY_USER,
|
||||
false,
|
||||
false,
|
||||
FileUploader.NameCollisionPolicy.DEFAULT)
|
||||
|
||||
longSleep()
|
||||
|
||||
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
|
||||
assertTrue(result.isSuccess)
|
||||
|
||||
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
|
||||
|
||||
val ocFile2 = OCFile("/testFile.txt")
|
||||
ocFile2.setStoragePath(getSavePath(account.name) + "/empty.txt")
|
||||
|
||||
FileUploader.uploadUpdateFile(
|
||||
targetContext,
|
||||
account,
|
||||
ocFile2,
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
FileUploader.NameCollisionPolicy.OVERWRITE)
|
||||
|
||||
shortSleep()
|
||||
|
||||
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
|
||||
assertTrue(result2.isSuccess)
|
||||
|
||||
assertEquals(0, (result2.data[0] as RemoteFile).length)
|
||||
}
|
||||
|
||||
/**
|
||||
* uploads a file, uploads another one with automatically (2) added, check
|
||||
*/
|
||||
@Test
|
||||
fun testKeepBoth() {
|
||||
var renameListenerWasTriggered = false
|
||||
|
||||
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
|
||||
val ocUpload = OCUpload(file.absolutePath, "/testFile.txt", account.name)
|
||||
|
||||
assertTrue(UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
account,
|
||||
null,
|
||||
ocUpload,
|
||||
FileUploader.NameCollisionPolicy.DEFAULT,
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
false)
|
||||
.setRemoteFolderToBeCreated()
|
||||
.execute(client, storageManager).isSuccess)
|
||||
|
||||
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
|
||||
assertTrue(result.isSuccess)
|
||||
|
||||
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
|
||||
|
||||
val file2 = File(getSavePath(account.name) + "/empty.txt")
|
||||
val ocUpload2 = OCUpload(file2.absolutePath, "/testFile.txt", account.name)
|
||||
|
||||
assertTrue(UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
account,
|
||||
null,
|
||||
ocUpload2,
|
||||
FileUploader.NameCollisionPolicy.RENAME,
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
false)
|
||||
.addRenameUploadListener {
|
||||
renameListenerWasTriggered = true
|
||||
}
|
||||
.execute(client, storageManager).isSuccess)
|
||||
|
||||
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
|
||||
assertTrue(result2.isSuccess)
|
||||
|
||||
assertEquals(file.length(), (result2.data[0] as RemoteFile).length)
|
||||
|
||||
val result3 = ReadFileRemoteOperation("/testFile (2).txt").execute(client)
|
||||
assertTrue(result3.isSuccess)
|
||||
|
||||
assertEquals(file2.length(), (result3.data[0] as RemoteFile).length)
|
||||
assertTrue(renameListenerWasTriggered)
|
||||
}
|
||||
|
||||
/**
|
||||
* uploads a file, uploads another one with automatically (2) added, check
|
||||
*/
|
||||
@Test
|
||||
fun testKeepBothStatic() {
|
||||
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
|
||||
|
||||
FileUploader.uploadNewFile(
|
||||
targetContext,
|
||||
account,
|
||||
file.absolutePath,
|
||||
"/testFile.txt",
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
null,
|
||||
true,
|
||||
UploadFileOperation.CREATED_BY_USER,
|
||||
false,
|
||||
false,
|
||||
FileUploader.NameCollisionPolicy.DEFAULT)
|
||||
|
||||
longSleep()
|
||||
|
||||
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
|
||||
assertTrue(result.isSuccess)
|
||||
|
||||
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
|
||||
|
||||
val ocFile2 = OCFile("/testFile.txt")
|
||||
ocFile2.setStoragePath(getSavePath(account.name) + "/empty.txt")
|
||||
|
||||
FileUploader.uploadUpdateFile(
|
||||
targetContext,
|
||||
account,
|
||||
ocFile2,
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
FileUploader.NameCollisionPolicy.RENAME)
|
||||
|
||||
shortSleep()
|
||||
|
||||
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
|
||||
assertTrue(result2.isSuccess)
|
||||
|
||||
assertEquals(file.length(), (result2.data[0] as RemoteFile).length)
|
||||
|
||||
val result3 = ReadFileRemoteOperation("/testFile (2).txt").execute(client)
|
||||
assertTrue(result3.isSuccess)
|
||||
|
||||
assertEquals(ocFile2.fileLength, (result3.data[0] as RemoteFile).length)
|
||||
}
|
||||
|
||||
/**
|
||||
* uploads a file with "keep server" option set, so do nothing
|
||||
*/
|
||||
@Test
|
||||
fun testKeepServer() {
|
||||
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
|
||||
val ocUpload = OCUpload(file.absolutePath, "/testFile.txt", account.name)
|
||||
|
||||
assertTrue(UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
account,
|
||||
null,
|
||||
ocUpload,
|
||||
FileUploader.NameCollisionPolicy.DEFAULT,
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
false)
|
||||
.setRemoteFolderToBeCreated()
|
||||
.execute(client, storageManager).isSuccess)
|
||||
|
||||
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
|
||||
assertTrue(result.isSuccess)
|
||||
|
||||
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
|
||||
|
||||
val ocUpload2 = OCUpload(getSavePath(account.name) + "/empty.txt", "/testFile.txt", account.name)
|
||||
|
||||
assertFalse(UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
account,
|
||||
null,
|
||||
ocUpload2,
|
||||
FileUploader.NameCollisionPolicy.CANCEL,
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
false)
|
||||
.execute(client, storageManager).isSuccess)
|
||||
|
||||
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
|
||||
assertTrue(result2.isSuccess)
|
||||
|
||||
assertEquals(file.length(), (result2.data[0] as RemoteFile).length)
|
||||
}
|
||||
|
||||
/**
|
||||
* uploads a file with "keep server" option set, so do nothing
|
||||
*/
|
||||
@Test
|
||||
fun testKeepServerStatic() {
|
||||
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
|
||||
|
||||
FileUploader.uploadNewFile(
|
||||
targetContext,
|
||||
account,
|
||||
file.absolutePath,
|
||||
"/testFile.txt",
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
null,
|
||||
true,
|
||||
UploadFileOperation.CREATED_BY_USER,
|
||||
false,
|
||||
false,
|
||||
FileUploader.NameCollisionPolicy.DEFAULT)
|
||||
|
||||
longSleep()
|
||||
|
||||
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
|
||||
assertTrue(result.isSuccess)
|
||||
|
||||
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
|
||||
|
||||
val ocFile2 = OCFile("/testFile.txt")
|
||||
ocFile2.setStoragePath(getSavePath(account.name) + "/empty.txt")
|
||||
|
||||
FileUploader.uploadUpdateFile(
|
||||
targetContext,
|
||||
account,
|
||||
ocFile2,
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
FileUploader.NameCollisionPolicy.CANCEL)
|
||||
|
||||
shortSleep()
|
||||
|
||||
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
|
||||
assertTrue(result2.isSuccess)
|
||||
|
||||
assertEquals(file.length(), (result2.data[0] as RemoteFile).length)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
/*
|
||||
*
|
||||
* 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 com.facebook.testing.screenshot.Screenshot;
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl;
|
||||
import com.owncloud.android.AbstractIT;
|
||||
import com.owncloud.android.R;
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager;
|
||||
import com.owncloud.android.datamodel.OCFile;
|
||||
import com.owncloud.android.db.OCUpload;
|
||||
import com.owncloud.android.lib.resources.files.UploadFileRemoteOperation;
|
||||
import com.owncloud.android.operations.RefreshFolderOperation;
|
||||
import com.owncloud.android.ui.dialog.ConflictsResolveDialog;
|
||||
import com.owncloud.android.utils.FileStorageUtils;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import androidx.fragment.app.DialogFragment;
|
||||
import androidx.test.espresso.intent.rule.IntentsTestRule;
|
||||
|
||||
import static androidx.test.espresso.Espresso.onView;
|
||||
import static androidx.test.espresso.action.ViewActions.click;
|
||||
import static androidx.test.espresso.matcher.ViewMatchers.withId;
|
||||
import static androidx.test.espresso.matcher.ViewMatchers.withText;
|
||||
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ConflictsResolveActivityIT extends AbstractIT {
|
||||
@Rule public IntentsTestRule<ConflictsResolveActivity> activityRule =
|
||||
new IntentsTestRule<>(ConflictsResolveActivity.class, true, false);
|
||||
private boolean returnCode;
|
||||
|
||||
@Test
|
||||
public void screenshotTextFiles() {
|
||||
OCFile newFile = new OCFile("/newFile.txt");
|
||||
newFile.setFileLength(56000);
|
||||
newFile.setModificationTimestamp(1522019340);
|
||||
newFile.setStoragePath(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt");
|
||||
|
||||
OCFile existingFile = new OCFile("/newFile.txt");
|
||||
existingFile.setFileLength(1024000);
|
||||
existingFile.setModificationTimestamp(1582019340);
|
||||
|
||||
FileDataStorageManager storageManager = new FileDataStorageManager(account, targetContext.getContentResolver());
|
||||
storageManager.saveNewFile(existingFile);
|
||||
|
||||
Intent intent = new Intent(targetContext, ConflictsResolveActivity.class);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_FILE, newFile);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_EXISTING_FILE, existingFile);
|
||||
|
||||
ConflictsResolveActivity sut = activityRule.launchActivity(intent);
|
||||
|
||||
ConflictsResolveDialog dialog = ConflictsResolveDialog.newInstance(existingFile,
|
||||
newFile,
|
||||
UserAccountManagerImpl
|
||||
.fromContext(targetContext)
|
||||
.getUser()
|
||||
);
|
||||
dialog.showDialog(sut);
|
||||
|
||||
getInstrumentation().waitForIdleSync();
|
||||
|
||||
shortSleep();
|
||||
|
||||
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void screenshotImages() throws IOException {
|
||||
FileDataStorageManager storageManager = new FileDataStorageManager(account,
|
||||
targetContext.getContentResolver());
|
||||
|
||||
OCFile newFile = new OCFile("/newFile.txt");
|
||||
newFile.setFileLength(56000);
|
||||
newFile.setModificationTimestamp(1522019340);
|
||||
newFile.setStoragePath(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt");
|
||||
|
||||
File image = getFile("image.jpg");
|
||||
|
||||
assertTrue(new UploadFileRemoteOperation(image.getAbsolutePath(),
|
||||
"/image.jpg",
|
||||
"image/jpg",
|
||||
"10000000").execute(client).isSuccess());
|
||||
|
||||
assertTrue(new RefreshFolderOperation(storageManager.getFileByPath("/"),
|
||||
System.currentTimeMillis(),
|
||||
false,
|
||||
true,
|
||||
storageManager,
|
||||
account,
|
||||
targetContext
|
||||
).execute(client).isSuccess());
|
||||
|
||||
OCFile existingFile = storageManager.getFileByPath("/image.jpg");
|
||||
|
||||
Intent intent = new Intent(targetContext, ConflictsResolveActivity.class);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_FILE, newFile);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_EXISTING_FILE, existingFile);
|
||||
|
||||
ConflictsResolveActivity sut = activityRule.launchActivity(intent);
|
||||
|
||||
ConflictsResolveDialog.OnConflictDecisionMadeListener listener = decision -> {
|
||||
|
||||
};
|
||||
|
||||
ConflictsResolveDialog dialog = ConflictsResolveDialog.newInstance(existingFile,
|
||||
newFile,
|
||||
UserAccountManagerImpl
|
||||
.fromContext(targetContext)
|
||||
.getUser()
|
||||
);
|
||||
dialog.showDialog(sut);
|
||||
dialog.listener = listener;
|
||||
|
||||
getInstrumentation().waitForIdleSync();
|
||||
shortSleep();
|
||||
|
||||
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cancel() {
|
||||
returnCode = false;
|
||||
|
||||
OCUpload newUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt",
|
||||
"/newFile.txt",
|
||||
account.name);
|
||||
|
||||
OCFile existingFile = new OCFile("/newFile.txt");
|
||||
existingFile.setFileLength(1024000);
|
||||
existingFile.setModificationTimestamp(1582019340);
|
||||
|
||||
OCFile newFile = new OCFile("/newFile.txt");
|
||||
newFile.setFileLength(56000);
|
||||
newFile.setModificationTimestamp(1522019340);
|
||||
newFile.setStoragePath(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt");
|
||||
|
||||
FileDataStorageManager storageManager = new FileDataStorageManager(account, targetContext.getContentResolver());
|
||||
storageManager.saveNewFile(existingFile);
|
||||
|
||||
Intent intent = new Intent(targetContext, ConflictsResolveActivity.class);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_FILE, newFile);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_EXISTING_FILE, existingFile);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_CONFLICT_UPLOAD, newUpload);
|
||||
|
||||
ConflictsResolveActivity sut = activityRule.launchActivity(intent);
|
||||
|
||||
sut.listener = decision -> {
|
||||
assertEquals(decision, ConflictsResolveDialog.Decision.CANCEL);
|
||||
returnCode = true;
|
||||
};
|
||||
|
||||
getInstrumentation().waitForIdleSync();
|
||||
shortSleep();
|
||||
|
||||
onView(withText("Cancel")).perform(click());
|
||||
|
||||
assertTrue(returnCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void keepExisting() {
|
||||
returnCode = false;
|
||||
|
||||
OCUpload newUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt",
|
||||
"/newFile.txt",
|
||||
account.name);
|
||||
|
||||
OCFile existingFile = new OCFile("/newFile.txt");
|
||||
existingFile.setFileLength(1024000);
|
||||
existingFile.setModificationTimestamp(1582019340);
|
||||
|
||||
OCFile newFile = new OCFile("/newFile.txt");
|
||||
newFile.setFileLength(56000);
|
||||
newFile.setModificationTimestamp(1522019340);
|
||||
newFile.setStoragePath(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt");
|
||||
|
||||
FileDataStorageManager storageManager = new FileDataStorageManager(account, targetContext.getContentResolver());
|
||||
storageManager.saveNewFile(existingFile);
|
||||
|
||||
Intent intent = new Intent(targetContext, ConflictsResolveActivity.class);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_FILE, newFile);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_EXISTING_FILE, existingFile);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_CONFLICT_UPLOAD, newUpload);
|
||||
|
||||
ConflictsResolveActivity sut = activityRule.launchActivity(intent);
|
||||
|
||||
sut.listener = decision -> {
|
||||
assertEquals(decision, ConflictsResolveDialog.Decision.KEEP_SERVER);
|
||||
returnCode = true;
|
||||
};
|
||||
|
||||
getInstrumentation().waitForIdleSync();
|
||||
|
||||
onView(withId(R.id.existing_checkbox)).perform(click());
|
||||
|
||||
DialogFragment dialog = (DialogFragment) sut.getSupportFragmentManager().findFragmentByTag("conflictDialog");
|
||||
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
|
||||
|
||||
onView(withText("OK")).perform(click());
|
||||
|
||||
assertTrue(returnCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void keepNew() {
|
||||
returnCode = false;
|
||||
|
||||
OCUpload newUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt",
|
||||
"/newFile.txt",
|
||||
account.name);
|
||||
|
||||
OCFile existingFile = new OCFile("/newFile.txt");
|
||||
existingFile.setFileLength(1024000);
|
||||
existingFile.setModificationTimestamp(1582019340);
|
||||
|
||||
OCFile newFile = new OCFile("/newFile.txt");
|
||||
newFile.setFileLength(56000);
|
||||
newFile.setModificationTimestamp(1522019340);
|
||||
newFile.setStoragePath(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt");
|
||||
|
||||
FileDataStorageManager storageManager = new FileDataStorageManager(account, targetContext.getContentResolver());
|
||||
storageManager.saveNewFile(existingFile);
|
||||
|
||||
Intent intent = new Intent(targetContext, ConflictsResolveActivity.class);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_FILE, newFile);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_EXISTING_FILE, existingFile);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_CONFLICT_UPLOAD, newUpload);
|
||||
|
||||
ConflictsResolveActivity sut = activityRule.launchActivity(intent);
|
||||
|
||||
sut.listener = decision -> {
|
||||
assertEquals(decision, ConflictsResolveDialog.Decision.KEEP_LOCAL);
|
||||
returnCode = true;
|
||||
};
|
||||
|
||||
getInstrumentation().waitForIdleSync();
|
||||
|
||||
onView(withId(R.id.new_checkbox)).perform(click());
|
||||
|
||||
DialogFragment dialog = (DialogFragment) sut.getSupportFragmentManager().findFragmentByTag("conflictDialog");
|
||||
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
|
||||
|
||||
onView(withText("OK")).perform(click());
|
||||
|
||||
assertTrue(returnCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void keepBoth() {
|
||||
returnCode = false;
|
||||
|
||||
OCUpload newUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt",
|
||||
"/newFile.txt",
|
||||
account.name);
|
||||
|
||||
OCFile existingFile = new OCFile("/newFile.txt");
|
||||
existingFile.setFileLength(1024000);
|
||||
existingFile.setModificationTimestamp(1582019340);
|
||||
|
||||
OCFile newFile = new OCFile("/newFile.txt");
|
||||
newFile.setFileLength(56000);
|
||||
newFile.setModificationTimestamp(1522019340);
|
||||
newFile.setStoragePath(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt");
|
||||
|
||||
FileDataStorageManager storageManager = new FileDataStorageManager(account, targetContext.getContentResolver());
|
||||
storageManager.saveNewFile(existingFile);
|
||||
|
||||
Intent intent = new Intent(targetContext, ConflictsResolveActivity.class);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_FILE, newFile);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_EXISTING_FILE, existingFile);
|
||||
intent.putExtra(ConflictsResolveActivity.EXTRA_CONFLICT_UPLOAD, newUpload);
|
||||
|
||||
ConflictsResolveActivity sut = activityRule.launchActivity(intent);
|
||||
|
||||
sut.listener = decision -> {
|
||||
assertEquals(decision, ConflictsResolveDialog.Decision.KEEP_BOTH);
|
||||
returnCode = true;
|
||||
};
|
||||
|
||||
getInstrumentation().waitForIdleSync();
|
||||
|
||||
onView(withId(R.id.existing_checkbox)).perform(click());
|
||||
onView(withId(R.id.new_checkbox)).perform(click());
|
||||
|
||||
DialogFragment dialog = (DialogFragment) sut.getSupportFragmentManager().findFragmentByTag("conflictDialog");
|
||||
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
|
||||
|
||||
onView(withText("OK")).perform(click());
|
||||
|
||||
assertTrue(returnCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
*
|
||||
* 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.Manifest;
|
||||
import android.accounts.Account;
|
||||
import android.accounts.AccountManager;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
|
||||
import com.nextcloud.client.account.UserAccountManager;
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl;
|
||||
import com.owncloud.android.AbstractIT;
|
||||
import com.owncloud.android.MainApp;
|
||||
import com.owncloud.android.R;
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
import androidx.test.espresso.contrib.DrawerActions;
|
||||
import androidx.test.espresso.intent.rule.IntentsTestRule;
|
||||
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.matcher.ViewMatchers.withId;
|
||||
import static androidx.test.espresso.matcher.ViewMatchers.withText;
|
||||
import static org.hamcrest.Matchers.anyOf;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class DrawerActivityIT extends AbstractIT {
|
||||
@Rule public IntentsTestRule<FileDisplayActivity> activityRule = new IntentsTestRule<>(FileDisplayActivity.class,
|
||||
true,
|
||||
false);
|
||||
|
||||
@Rule
|
||||
public final GrantPermissionRule permissionRule = GrantPermissionRule.grant(
|
||||
Manifest.permission.WRITE_EXTERNAL_STORAGE);
|
||||
private static Account account2;
|
||||
private static String account2Name;
|
||||
private static String account2DisplayName;
|
||||
|
||||
@BeforeClass
|
||||
public static void beforeClass() {
|
||||
Bundle arguments = androidx.test.platform.app.InstrumentationRegistry.getArguments();
|
||||
Uri baseUrl = Uri.parse(arguments.getString("TEST_SERVER_URL"));
|
||||
String loginName = "user1";
|
||||
String password = "user1";
|
||||
|
||||
Account temp = new Account(loginName + "@" + baseUrl, MainApp.getAccountType(targetContext));
|
||||
UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
|
||||
if (!accountManager.exists(temp)) {
|
||||
AccountManager platformAccountManager = AccountManager.get(targetContext);
|
||||
platformAccountManager.addAccountExplicitly(temp, password, null);
|
||||
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION,
|
||||
Integer.toString(UserAccountManager.ACCOUNT_VERSION));
|
||||
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_VERSION, "14.0.0.0");
|
||||
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_BASE_URL, baseUrl.toString());
|
||||
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_USER_ID, loginName); // same as userId
|
||||
}
|
||||
|
||||
final UserAccountManager userAccountManager = UserAccountManagerImpl.fromContext(targetContext);
|
||||
account2 = userAccountManager.getAccountByName(loginName + "@" + baseUrl);
|
||||
account2Name = loginName + "@" + baseUrl;
|
||||
account2DisplayName = "User One@" + baseUrl;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void switchAccountViaAccountList() {
|
||||
FileDisplayActivity sut = activityRule.launchActivity(null);
|
||||
|
||||
assertEquals(account, sut.getUser().get().toPlatformAccount());
|
||||
|
||||
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
|
||||
onView(withId(R.id.drawer_active_user)).perform(click());
|
||||
|
||||
onView(anyOf(withText(account2Name), withText(account2DisplayName))).perform(click());
|
||||
|
||||
waitForIdleSync();
|
||||
|
||||
assertEquals(account2, sut.getUser().get().toPlatformAccount());
|
||||
|
||||
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
|
||||
onView(withId(R.id.drawer_active_user)).perform(click());
|
||||
onView(withText(account.name)).perform(click());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void switchAccountViaAvatar() {
|
||||
FileDisplayActivity sut = activityRule.launchActivity(null);
|
||||
|
||||
assertEquals(account, sut.getUser().get().toPlatformAccount());
|
||||
|
||||
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
|
||||
onView(withId(R.id.drawer_account_end)).perform(click());
|
||||
|
||||
waitForIdleSync();
|
||||
|
||||
assertEquals(account2, sut.getUser().get().toPlatformAccount());
|
||||
|
||||
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
|
||||
onView(withId(R.id.drawer_account_end)).perform(click());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.owncloud.android.ui.activity;
|
||||
|
||||
/*
|
||||
* Nextcloud Android client application
|
||||
*
|
||||
* @author Kilian Périsset
|
||||
* Copyright (C) 2019 Kilian Périsset (Infomaniak Network SA)
|
||||
* Copyright (C) 2019 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/>.
|
||||
*/
|
||||
|
||||
import com.owncloud.android.datamodel.OCFile;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
import androidx.test.filters.LargeTest;
|
||||
import androidx.test.rule.ActivityTestRule;
|
||||
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
@LargeTest
|
||||
public class FolderPickerActivityIT {
|
||||
@Rule
|
||||
public ActivityTestRule<FolderPickerActivity> activityRule =
|
||||
new ActivityTestRule<>(FolderPickerActivity.class);
|
||||
|
||||
@Test
|
||||
public void getActivityFile() {
|
||||
// Arrange
|
||||
FolderPickerActivity targetActivity = activityRule.getActivity();
|
||||
OCFile origin = new OCFile("/test/file.test");
|
||||
origin.setRemotePath("/remotePath/test");
|
||||
|
||||
// Act
|
||||
targetActivity.setFile(origin);
|
||||
OCFile target = targetActivity.getFile();
|
||||
|
||||
// Assert
|
||||
Assert.assertEquals(origin, target);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getParentFolder_isNotRootFolder() {
|
||||
// Arrange
|
||||
FolderPickerActivity targetActivity = activityRule.getActivity();
|
||||
OCFile origin = new OCFile("/test/");
|
||||
origin.setFileId(1);
|
||||
origin.setRemotePath("/test/");
|
||||
origin.setStoragePath("/test/");
|
||||
origin.setFolder();
|
||||
|
||||
// Act
|
||||
targetActivity.setFile(origin);
|
||||
OCFile target = targetActivity.getCurrentFolder();
|
||||
|
||||
// Assert
|
||||
Assert.assertEquals(origin, target);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getParentFolder_isRootFolder() {
|
||||
// Arrange
|
||||
FolderPickerActivity targetActivity = activityRule.getActivity();
|
||||
OCFile origin = new OCFile("/");
|
||||
origin.setFileId(1);
|
||||
origin.setRemotePath("/");
|
||||
origin.setStoragePath("/");
|
||||
origin.setFolder();
|
||||
|
||||
// Act
|
||||
targetActivity.setFile(origin);
|
||||
OCFile target = targetActivity.getCurrentFolder();
|
||||
|
||||
// Assert
|
||||
Assert.assertEquals(origin, target);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nullFile() {
|
||||
// Arrange
|
||||
FolderPickerActivity targetActivity = activityRule.getActivity();
|
||||
OCFile rootFolder = targetActivity.getStorageManager().getFileByPath(OCFile.ROOT_PATH);
|
||||
|
||||
// Act
|
||||
targetActivity.setFile(null);
|
||||
OCFile target = targetActivity.getCurrentFolder();
|
||||
|
||||
// Assert
|
||||
Assert.assertEquals(rootFolder, target);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getParentFolder() {
|
||||
// Arrange
|
||||
FolderPickerActivity targetActivity = activityRule.getActivity();
|
||||
OCFile origin = new OCFile("/test/file.test");
|
||||
origin.setRemotePath("/test/file.test");
|
||||
|
||||
OCFile target = new OCFile("/test/");
|
||||
|
||||
// Act
|
||||
targetActivity.setFile(origin);
|
||||
|
||||
// Assert
|
||||
Assert.assertEquals(origin, target);
|
||||
}
|
||||
}
|
||||
@@ -40,22 +40,22 @@ public class ManageAccountsActivityIT extends AbstractIT {
|
||||
false);
|
||||
|
||||
@Test
|
||||
public void open() throws InterruptedException {
|
||||
public void open() {
|
||||
Activity sut = activityRule.launchActivity(null);
|
||||
|
||||
Thread.sleep(2000);
|
||||
shortSleep();
|
||||
|
||||
Screenshot.snapActivity(sut).record();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void userInfoDetail() throws InterruptedException {
|
||||
public void userInfoDetail() {
|
||||
ManageAccountsActivity sut = activityRule.launchActivity(null);
|
||||
|
||||
User user = sut.accountManager.getUser();
|
||||
sut.onClick(user);
|
||||
|
||||
Thread.sleep(2000);
|
||||
shortSleep();
|
||||
|
||||
Screenshot.snapActivity(getCurrentActivity()).record();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
/*
|
||||
*
|
||||
* 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.fragment
|
||||
|
||||
import android.Manifest
|
||||
import androidx.test.core.app.ActivityScenario
|
||||
import androidx.test.espresso.intent.rule.IntentsTestRule
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import androidx.test.rule.GrantPermissionRule
|
||||
import com.evernote.android.job.JobRequest
|
||||
import com.facebook.testing.screenshot.Screenshot
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl
|
||||
import com.nextcloud.client.device.PowerManagementService
|
||||
import com.nextcloud.client.network.ConnectivityService
|
||||
import com.nextcloud.client.preferences.AppPreferences
|
||||
import com.nextcloud.client.preferences.AppPreferencesImpl
|
||||
import com.nextcloud.client.preferences.DarkMode
|
||||
import com.owncloud.android.AbstractIT
|
||||
import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager
|
||||
import com.owncloud.android.db.OCUpload
|
||||
import com.owncloud.android.files.services.FileUploader
|
||||
import com.owncloud.android.lib.resources.shares.CreateShareRemoteOperation
|
||||
import com.owncloud.android.lib.resources.shares.GetShareesRemoteOperation
|
||||
import com.owncloud.android.lib.resources.shares.OCShare
|
||||
import com.owncloud.android.lib.resources.shares.ShareType
|
||||
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.json.JSONObject
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
|
||||
class OCFileListFragmentIT : AbstractIT() {
|
||||
companion object {
|
||||
val SECOND_IN_MILLIS = 1000L
|
||||
val RESULT_PER_PAGE = 50
|
||||
}
|
||||
|
||||
@get:Rule
|
||||
val activityRule = IntentsTestRule(FileDisplayActivity::class.java, true, false)
|
||||
|
||||
@get:Rule
|
||||
val permissionRule = GrantPermissionRule.grant(Manifest.permission.WRITE_EXTERNAL_STORAGE)
|
||||
|
||||
private val connectivityServiceMock: ConnectivityService = object : ConnectivityService {
|
||||
override fun isInternetWalled(): Boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
override fun isOnlineWithWifi(): Boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
override fun getActiveNetworkType(): JobRequest.NetworkType {
|
||||
return JobRequest.NetworkType.ANY
|
||||
}
|
||||
}
|
||||
|
||||
private val powerManagementServiceMock: PowerManagementService = object : PowerManagementService {
|
||||
override val isPowerSavingEnabled: Boolean
|
||||
get() = false
|
||||
|
||||
override val isPowerSavingExclusionAvailable: Boolean
|
||||
get() = false
|
||||
|
||||
override val isBatteryCharging: Boolean
|
||||
get() = false
|
||||
}
|
||||
|
||||
@Test
|
||||
fun showRichWorkspace() {
|
||||
assertTrue(CreateFolderOperation("/test/", true).execute(client, storageManager).isSuccess)
|
||||
|
||||
val ocUpload = OCUpload(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt",
|
||||
"/test/Readme.md",
|
||||
account.name)
|
||||
val newUpload = UploadFileOperation(
|
||||
UploadsStorageManager(UserAccountManagerImpl.fromContext(targetContext), targetContext.contentResolver),
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
account,
|
||||
null,
|
||||
ocUpload,
|
||||
FileUploader.NameCollisionPolicy.DEFAULT,
|
||||
FileUploader.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
false)
|
||||
|
||||
newUpload.addRenameUploadListener {}
|
||||
newUpload.setRemoteFolderToBeCreated()
|
||||
|
||||
assertTrue(newUpload.execute(client, storageManager).isSuccess)
|
||||
|
||||
assertTrue(RefreshFolderOperation(storageManager.getFileByPath("/test/"),
|
||||
System.currentTimeMillis() / SECOND_IN_MILLIS,
|
||||
false,
|
||||
true,
|
||||
storageManager,
|
||||
account,
|
||||
targetContext).execute(client).isSuccess)
|
||||
|
||||
val sut = ActivityScenario.launch(FileDisplayActivity::class.java)
|
||||
sut.onActivity { activity -> activity.onBrowsedDownTo(storageManager.getFileByPath("/test/")) }
|
||||
|
||||
shortSleep()
|
||||
|
||||
sut.onActivity { activity ->
|
||||
Screenshot.snapActivity(activity).setName("richworkspaces_light").record()
|
||||
}
|
||||
|
||||
val preferences: AppPreferences = AppPreferencesImpl.fromContext(targetContext)
|
||||
preferences.darkThemeMode = DarkMode.DARK
|
||||
MainApp.setAppTheme(DarkMode.DARK)
|
||||
|
||||
sut.onActivity { activity -> activity.onBackPressed() }
|
||||
|
||||
sut.recreate()
|
||||
|
||||
sut.onActivity { activity -> activity.onBrowsedDownTo(storageManager.getFileByPath("/test/")) }
|
||||
|
||||
shortSleep()
|
||||
|
||||
sut.onActivity { activity ->
|
||||
Screenshot.snapActivity(activity).setName("richworkspaces_dark").record()
|
||||
}
|
||||
|
||||
// switch back to light mode
|
||||
preferences.darkThemeMode = DarkMode.LIGHT
|
||||
MainApp.setAppTheme(DarkMode.LIGHT)
|
||||
|
||||
sut.onActivity { activity -> activity.onBackPressed() }
|
||||
|
||||
sut.recreate()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun createAndShowShareToUser() {
|
||||
val path = "/shareToAdmin/"
|
||||
TestCase.assertTrue(CreateFolderOperation(path, true).execute(client, storageManager).isSuccess)
|
||||
|
||||
// share folder to user "admin"
|
||||
TestCase.assertTrue(CreateShareRemoteOperation(path,
|
||||
ShareType.USER,
|
||||
"admin",
|
||||
false,
|
||||
"",
|
||||
OCShare.MAXIMUM_PERMISSIONS_FOR_FOLDER)
|
||||
.execute(client).isSuccess)
|
||||
|
||||
val sut: FileDisplayActivity = activityRule.launchActivity(null)
|
||||
sut.startSyncFolderOperation(storageManager.getFileByPath("/"), true)
|
||||
|
||||
shortSleep()
|
||||
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
|
||||
Screenshot.snapActivity(sut).record()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun createAndShowShareToGroup() {
|
||||
val path = "/shareToGroup/"
|
||||
TestCase.assertTrue(CreateFolderOperation(path, true).execute(client, storageManager).isSuccess)
|
||||
|
||||
// share folder to group
|
||||
assertTrue(CreateShareRemoteOperation("/shareToGroup/",
|
||||
ShareType.GROUP,
|
||||
"users",
|
||||
false,
|
||||
"",
|
||||
OCShare.DEFAULT_PERMISSION)
|
||||
.execute(client).isSuccess)
|
||||
|
||||
val sut: FileDisplayActivity = activityRule.launchActivity(null)
|
||||
sut.startSyncFolderOperation(storageManager.getFileByPath("/"), true)
|
||||
|
||||
shortSleep()
|
||||
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
|
||||
Screenshot.snapActivity(sut).record()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun createAndShowShareToCircle() {
|
||||
val path = "/shareToCircle/"
|
||||
TestCase.assertTrue(CreateFolderOperation(path, true).execute(client, storageManager).isSuccess)
|
||||
|
||||
// share folder to circle
|
||||
// get circleId
|
||||
val searchResult = GetShareesRemoteOperation("publicCircle", 1, RESULT_PER_PAGE).execute(client)
|
||||
assertTrue(searchResult.logMessage, searchResult.isSuccess)
|
||||
|
||||
val resultJson: JSONObject = searchResult.data[0] as JSONObject
|
||||
val circleId: String = resultJson.getJSONObject("value").getString("shareWith")
|
||||
|
||||
assertTrue(CreateShareRemoteOperation("/shareToCircle/",
|
||||
ShareType.CIRCLE,
|
||||
circleId,
|
||||
false,
|
||||
"",
|
||||
OCShare.DEFAULT_PERMISSION)
|
||||
.execute(client).isSuccess)
|
||||
|
||||
val sut: FileDisplayActivity = activityRule.launchActivity(null)
|
||||
sut.startSyncFolderOperation(storageManager.getFileByPath("/"), true)
|
||||
|
||||
shortSleep()
|
||||
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
|
||||
Screenshot.snapActivity(sut).record()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun createAndShowShareViaLink() {
|
||||
val path = "/shareViaLink/"
|
||||
TestCase.assertTrue(CreateFolderOperation(path, true).execute(client, storageManager).isSuccess)
|
||||
|
||||
// share folder via public link
|
||||
TestCase.assertTrue(CreateShareRemoteOperation("/shareViaLink/",
|
||||
ShareType.PUBLIC_LINK,
|
||||
"",
|
||||
true,
|
||||
"",
|
||||
OCShare.READ_PERMISSION_FLAG)
|
||||
.execute(client).isSuccess)
|
||||
|
||||
val sut: FileDisplayActivity = activityRule.launchActivity(null)
|
||||
sut.startSyncFolderOperation(storageManager.getFileByPath("/"), true)
|
||||
|
||||
shortSleep()
|
||||
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
|
||||
Screenshot.snapActivity(sut).record()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
*
|
||||
* 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.helpers
|
||||
|
||||
import com.owncloud.android.MainApp
|
||||
import junit.framework.Assert.assertEquals
|
||||
import junit.framework.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class FileOperationsHelperIT {
|
||||
|
||||
@Test
|
||||
fun testNull() {
|
||||
MainApp.setStoragePath(null)
|
||||
assertEquals(-1L, FileOperationsHelper.getAvailableSpaceOnDevice())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testNonExistingPath() {
|
||||
MainApp.setStoragePath("/123/123")
|
||||
assertEquals(-1L, FileOperationsHelper.getAvailableSpaceOnDevice())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testExistingPath() {
|
||||
MainApp.setStoragePath("/sdcard/")
|
||||
assertTrue(FileOperationsHelper.getAvailableSpaceOnDevice() > 0L)
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,7 @@ public class PreviewTextFileFragmentTest extends AbstractIT {
|
||||
public void displaySimpleTextFile() throws InterruptedException {
|
||||
FileDisplayActivity sut = activityRule.launchActivity(null);
|
||||
|
||||
Thread.sleep(3000);
|
||||
shortSleep();
|
||||
|
||||
File file = new File(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt");
|
||||
OCFile test = new OCFile("/text.md");
|
||||
@@ -61,7 +61,7 @@ public class PreviewTextFileFragmentTest extends AbstractIT {
|
||||
test.setStoragePath(file.getAbsolutePath());
|
||||
sut.startTextPreview(test, false);
|
||||
|
||||
Thread.sleep(3000);
|
||||
shortSleep();
|
||||
|
||||
Screenshot.snapActivity(sut).record();
|
||||
}
|
||||
@@ -70,7 +70,7 @@ public class PreviewTextFileFragmentTest extends AbstractIT {
|
||||
public void displayJavaSnippetFile() throws IOException, InterruptedException {
|
||||
FileDisplayActivity sut = activityRule.launchActivity(null);
|
||||
|
||||
Thread.sleep(3000);
|
||||
shortSleep();
|
||||
|
||||
File file = getFile("java.md");
|
||||
OCFile test = new OCFile("/java.md");
|
||||
@@ -78,7 +78,7 @@ public class PreviewTextFileFragmentTest extends AbstractIT {
|
||||
test.setStoragePath(file.getAbsolutePath());
|
||||
sut.startTextPreview(test, false);
|
||||
|
||||
Thread.sleep(3000);
|
||||
shortSleep();
|
||||
|
||||
Screenshot.snapActivity(sut).record();
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ Eigenschaften:
|
||||
* Bleiben Sie auf dem Laufenden durch Benachrichtigungen
|
||||
* Mehrere Konten gleichzeitig
|
||||
* Geschützter Zugriff durch Fingerabdruck oder PIN
|
||||
* Integration mit DAVx5 (ehemals DAVdroid) für einfaches Konfigurieren der Kalender- & Kontakte-Synchronisation
|
||||
* Integration mit DAVx5 (ehemals DAVdroid) für einfaches Konfigurieren der Kalender- & Kontakte-Synchronisierung
|
||||
|
||||
Bitte melden Sie alle Probleme unter https://github.com/nextcloud/android/issues oder diskutieren Sie über die App auf https://help.nextcloud.com/c/clients/android
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Samo-hostująca platforma produkcyjna, która zapewnia kontrolę.
|
||||
Oprogramowanie biurowe uruchamiane na własnym hostingu, który zapewnia kontrolę.
|
||||
|
||||
Funkcje:
|
||||
* Łatwy, nowoczesny interfejs, dostosowany do wyglądu Twojego serwera
|
||||
|
||||
@@ -1 +1 @@
|
||||
Samo-hostująca platforma produkcyjna, która zapewnia kontrolę
|
||||
Oprogramowanie biurowe uruchamiane na własnym hostingu, który zapewnia kontrolę
|
||||
@@ -1,6 +1,6 @@
|
||||
Платформа за продуктивност коју и Ви можете да хостујете и која Вам даје контролу.
|
||||
Платформа продуктивности на вашем серверу и под вашом контролом.
|
||||
Особине:
|
||||
* Лако и модерно сучеље, потпуно усклађено са темом са сервера
|
||||
* Лако и модерно сучеље, усклађено са темом на серверу
|
||||
* Отпремање фајлова на Некстклауд сервер
|
||||
* Дељење фајлова са другима
|
||||
* Синхронизација омиљених фајлова и фасцикли
|
||||
@@ -9,10 +9,10 @@
|
||||
* Обавештења са сервера
|
||||
* Подршка за више налога
|
||||
* Безбедан приступ свим подацима преко отиска прста или пина
|
||||
* Интеграција са DAVx5-ом (раније знаном и као ДАВдроид) за брзо подешавање синхронизације календара & контаката
|
||||
* Интеграција са DAVx5 (раније знаном као ДАВдроид) за лако подешавање синхронизације календара и контаката
|
||||
|
||||
Све проблеме можете да пријавите на https://github.com/nextcloud/android/issues а о апликацији дискутујте на https://help.nextcloud.com/c/clients/android
|
||||
|
||||
Нови сте на Некстклауду? Некстклауд је лични сервер за синхронизацију, дељење фајлова & комуникацију. Потпуно је отвореног кода и можете да га сами хостовати или платити компанији да то ради за Вас. На овај начин, сами контролишете своје слике, календаре, контакте, документа и све остало.
|
||||
Нови сте на Некстклауду? Некстклауд је лични сервер за синхронизацију, дељење фајлова и комуникацију. То је слободан софтвер и можете га сами поставити на свој сервер или платити компанији да то учини уместо вас. На тај начин, сами контролишете своје слике, календаре, контакте, документа и све остало.
|
||||
|
||||
Погледајте Некстклауд на https://nextcloud.com
|
||||
@@ -1 +1 @@
|
||||
Платформа за продуктивност коју и Ви можете да хостујете и која Вам даје контрол
|
||||
Платформа продуктивности под вашом контролом
|
||||
@@ -66,13 +66,6 @@
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name=".services.firebase.NCFirebaseInstanceIDService">
|
||||
<intent-filter>
|
||||
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name="com.evernote.android.job.gcm.PlatformGcmService"
|
||||
android:enabled="true"
|
||||
|
||||
@@ -20,14 +20,15 @@
|
||||
package com.nextcloud.client.di;
|
||||
|
||||
import com.owncloud.android.authentication.ModifiedAuthenticatorActivity;
|
||||
import com.owncloud.android.services.firebase.NCFirebaseInstanceIDService;
|
||||
import com.owncloud.android.services.firebase.NCFirebaseMessagingService;
|
||||
|
||||
import dagger.Module;
|
||||
import dagger.android.ContributesAndroidInjector;
|
||||
|
||||
@Module
|
||||
abstract class VariantComponentsModule {
|
||||
@ContributesAndroidInjector abstract NCFirebaseInstanceIDService ncFirebaseInstanceIDService();
|
||||
@ContributesAndroidInjector
|
||||
abstract NCFirebaseMessagingService nCFirebaseMessagingService();
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract ModifiedAuthenticatorActivity modifiedAuthenticatorActivity();
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
/**
|
||||
* Nextcloud Android client application
|
||||
*
|
||||
* @author Mario Danic
|
||||
* Copyright (C) 2017 Mario Danic
|
||||
*
|
||||
* 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.services.firebase;
|
||||
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.google.firebase.iid.FirebaseInstanceId;
|
||||
import com.google.firebase.iid.FirebaseInstanceIdService;
|
||||
import com.nextcloud.client.account.UserAccountManager;
|
||||
import com.nextcloud.client.preferences.AppPreferences;
|
||||
import com.owncloud.android.R;
|
||||
import com.owncloud.android.utils.PushUtils;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
import dagger.android.AndroidInjection;
|
||||
|
||||
public class NCFirebaseInstanceIDService extends FirebaseInstanceIdService {
|
||||
|
||||
|
||||
@Inject AppPreferences preferences;
|
||||
@Inject UserAccountManager accountManager;
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
AndroidInjection.inject(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTokenRefresh() {
|
||||
//You can implement this method to store the token on your server
|
||||
if (!TextUtils.isEmpty(getResources().getString(R.string.push_server_url))) {
|
||||
preferences.setPushToken(FirebaseInstanceId.getInstance().getToken());
|
||||
PushUtils.pushRegistrationToServer(accountManager, preferences.getPushToken());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,28 +19,56 @@
|
||||
*/
|
||||
package com.owncloud.android.services.firebase;
|
||||
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.evernote.android.job.JobRequest;
|
||||
import com.evernote.android.job.util.support.PersistableBundleCompat;
|
||||
import com.google.firebase.messaging.FirebaseMessagingService;
|
||||
import com.google.firebase.messaging.RemoteMessage;
|
||||
import com.nextcloud.client.account.UserAccountManager;
|
||||
import com.nextcloud.client.preferences.AppPreferences;
|
||||
import com.owncloud.android.R;
|
||||
import com.owncloud.android.jobs.NotificationJob;
|
||||
import com.owncloud.android.utils.PushUtils;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import dagger.android.AndroidInjection;
|
||||
|
||||
public class NCFirebaseMessagingService extends FirebaseMessagingService {
|
||||
@Inject AppPreferences preferences;
|
||||
@Inject UserAccountManager accountManager;
|
||||
|
||||
@Override
|
||||
public void onMessageReceived(RemoteMessage remoteMessage) {
|
||||
if (remoteMessage != null && remoteMessage.getData() != null) {
|
||||
PersistableBundleCompat persistableBundleCompat = new PersistableBundleCompat();
|
||||
persistableBundleCompat.putString(NotificationJob.KEY_NOTIFICATION_SUBJECT, remoteMessage.getData().get
|
||||
(NotificationJob.KEY_NOTIFICATION_SUBJECT));
|
||||
persistableBundleCompat.putString(NotificationJob.KEY_NOTIFICATION_SIGNATURE, remoteMessage.getData().get
|
||||
(NotificationJob.KEY_NOTIFICATION_SIGNATURE));
|
||||
new JobRequest.Builder(NotificationJob.TAG)
|
||||
.addExtras(persistableBundleCompat)
|
||||
.setUpdateCurrent(false)
|
||||
.startNow()
|
||||
.build()
|
||||
.schedule();
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
AndroidInjection.inject(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
|
||||
remoteMessage.getData();
|
||||
PersistableBundleCompat persistableBundleCompat = new PersistableBundleCompat();
|
||||
persistableBundleCompat.putString(NotificationJob.KEY_NOTIFICATION_SUBJECT, remoteMessage.getData().get
|
||||
(NotificationJob.KEY_NOTIFICATION_SUBJECT));
|
||||
persistableBundleCompat.putString(NotificationJob.KEY_NOTIFICATION_SIGNATURE, remoteMessage.getData().get
|
||||
(NotificationJob.KEY_NOTIFICATION_SIGNATURE));
|
||||
new JobRequest.Builder(NotificationJob.TAG)
|
||||
.addExtras(persistableBundleCompat)
|
||||
.setUpdateCurrent(false)
|
||||
.startNow()
|
||||
.build()
|
||||
.schedule();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNewToken(@NonNull String newToken) {
|
||||
super.onNewToken(newToken);
|
||||
|
||||
if (!TextUtils.isEmpty(getResources().getString(R.string.push_server_url))) {
|
||||
preferences.setPushToken(newToken);
|
||||
PushUtils.pushRegistrationToServer(accountManager, preferences.getPushToken());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -117,6 +117,19 @@
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEARCH" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="http"
|
||||
android:host="*"
|
||||
android:pathPattern="/.*index.php/f/.*"
|
||||
/>
|
||||
<data android:scheme="https"
|
||||
android:host="*"
|
||||
android:pathPattern="/.*index.php/f/.*"
|
||||
/>
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.app.searchable"
|
||||
android:resource="@xml/users_and_groups_searchable"/>
|
||||
</activity>
|
||||
|
||||
|
After Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 23 KiB |
@@ -50,6 +50,7 @@ import org.apache.commons.httpclient.HttpState;
|
||||
import org.apache.commons.httpclient.NameValuePair;
|
||||
import org.apache.commons.httpclient.methods.DeleteMethod;
|
||||
import org.apache.commons.httpclient.methods.GetMethod;
|
||||
import org.apache.commons.httpclient.methods.HeadMethod;
|
||||
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
|
||||
import org.apache.commons.httpclient.methods.PostMethod;
|
||||
import org.apache.commons.httpclient.methods.PutMethod;
|
||||
@@ -297,6 +298,10 @@ public class InputStreamBinder extends IInputStreamService.Stub {
|
||||
method = new MkColMethod(requestUrl);
|
||||
break;
|
||||
|
||||
case "HEAD":
|
||||
method = new HeadMethod(requestUrl);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new UnsupportedOperationException(EXCEPTION_UNSUPPORTED_METHOD);
|
||||
|
||||
|
||||
@@ -27,14 +27,10 @@ import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.Serializable;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
public class PlainHeader implements Serializable {
|
||||
private static final long serialVersionUID = 3284979177401282512L;
|
||||
|
||||
@Getter
|
||||
private String name;
|
||||
@Getter
|
||||
private String value;
|
||||
|
||||
PlainHeader(String name, String value) {
|
||||
@@ -51,4 +47,12 @@ public class PlainHeader implements Serializable {
|
||||
name = (String) in.readObject();
|
||||
value = (String) in.readObject();
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return this.value;
|
||||
}
|
||||
}
|
||||
@@ -30,10 +30,7 @@ import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
public class Response {
|
||||
@Getter
|
||||
private InputStream body;
|
||||
private Header[] headers;
|
||||
|
||||
@@ -62,4 +59,8 @@ public class Response {
|
||||
Gson gson = new Gson();
|
||||
return gson.toJson(arrayList);
|
||||
}
|
||||
|
||||
public InputStream getBody() {
|
||||
return this.body;
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
* Nextcloud Android client application
|
||||
*
|
||||
* @author Chris Narkiewicz <[email protected]>
|
||||
* Copyright (C) 2019 Chris Narkiewicz
|
||||
* Copyright (C) 2019 Nextcloud GmbH
|
||||
* 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
|
||||
@@ -72,6 +72,10 @@ internal data class AnonymousUser(private val accountType: String) : User, Parce
|
||||
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) {
|
||||
|
||||
@@ -63,7 +63,11 @@ internal data class RegisteredUser(
|
||||
}
|
||||
|
||||
override fun nameEquals(user: User?): Boolean {
|
||||
return user?.accountName.equals(accountName, true)
|
||||
return nameEquals(user?.accountName)
|
||||
}
|
||||
|
||||
override fun nameEquals(accountName: CharSequence?): Boolean {
|
||||
return accountName?.toString().equals(this.accountName, true)
|
||||
}
|
||||
|
||||
override fun describeContents() = 0
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
* Nextcloud Android client application
|
||||
*
|
||||
* @author Chris Narkiewicz <[email protected]>
|
||||
* Copyright (C) 2019 Chris Narkiewicz
|
||||
* Copyright (C) 2019 Nextcloud GmbH
|
||||
* 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
|
||||
@@ -59,4 +59,11 @@ interface User : Parcelable {
|
||||
* @return true if account names are same, false otherwise
|
||||
*/
|
||||
fun nameEquals(user: User?): Boolean
|
||||
|
||||
/**
|
||||
* Compare account names, case insensitive.
|
||||
*
|
||||
* @return true if account names are same, false otherwise
|
||||
*/
|
||||
fun nameEquals(accountName: CharSequence?): Boolean
|
||||
}
|
||||
@@ -48,6 +48,14 @@ public interface UserAccountManager extends CurrentAccountProvider {
|
||||
*/
|
||||
void removeAllAccounts();
|
||||
|
||||
/**
|
||||
* Remove registered user.
|
||||
*
|
||||
* @param user user to remove
|
||||
* @return true if account was removed successfully, false otherwise
|
||||
*/
|
||||
boolean removeUser(User user);
|
||||
|
||||
/**
|
||||
* Get configured NextCloud's user accounts.
|
||||
*
|
||||
@@ -81,7 +89,11 @@ public interface UserAccountManager extends CurrentAccountProvider {
|
||||
boolean exists(Account account);
|
||||
|
||||
/**
|
||||
* Verifies that every account has userId set
|
||||
* Verifies that every account has userId set and sets the user id if not.
|
||||
* This migration is idempotent and can be run multiple times until
|
||||
* all accounts are migrated.
|
||||
*
|
||||
* @return true if migration was successful, false if any account failed to be migrated
|
||||
*/
|
||||
boolean migrateUserId();
|
||||
|
||||
|
||||
@@ -23,6 +23,9 @@ package com.nextcloud.client.account;
|
||||
import android.accounts.Account;
|
||||
import android.accounts.AccountManager;
|
||||
import android.app.Activity;
|
||||
import android.accounts.AccountManagerFuture;
|
||||
import android.accounts.AuthenticatorException;
|
||||
import android.accounts.OperationCanceledException;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.preference.PreferenceManager;
|
||||
@@ -43,6 +46,7 @@ import com.owncloud.android.lib.common.utils.Log_OC;
|
||||
import com.owncloud.android.lib.resources.status.OwnCloudVersion;
|
||||
import com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -81,6 +85,18 @@ public class UserAccountManagerImpl implements UserAccountManager {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean removeUser(User user) {
|
||||
try {
|
||||
AccountManagerFuture<Boolean> result = accountManager.removeAccount(user.toPlatformAccount(),
|
||||
null,
|
||||
null);
|
||||
return result.getResult();
|
||||
} catch (OperationCanceledException| AuthenticatorException| IOException ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public Account[] getAccounts() {
|
||||
@@ -276,10 +292,10 @@ public class UserAccountManagerImpl implements UserAccountManager {
|
||||
public boolean setCurrentOwnCloudAccount(int hashCode) {
|
||||
boolean result = false;
|
||||
if (hashCode != 0) {
|
||||
for (final Account account : getAccounts()) {
|
||||
if (hashCode == account.hashCode()) {
|
||||
for (final User user : getAllUsers()) {
|
||||
if (hashCode == user.hashCode()) {
|
||||
SharedPreferences.Editor appPrefs = PreferenceManager.getDefaultSharedPreferences(context).edit();
|
||||
appPrefs.putString(PREF_SELECT_OC_ACCOUNT, account.name);
|
||||
appPrefs.putString(PREF_SELECT_OC_ACCOUNT, user.getAccountName());
|
||||
appPrefs.apply();
|
||||
result = true;
|
||||
break;
|
||||
@@ -326,12 +342,11 @@ public class UserAccountManagerImpl implements UserAccountManager {
|
||||
}
|
||||
|
||||
public boolean migrateUserId() {
|
||||
boolean success = false;
|
||||
Account[] ocAccounts = accountManager.getAccountsByType(MainApp.getAccountType(context));
|
||||
String userId;
|
||||
String displayName;
|
||||
GetUserInfoRemoteOperation remoteUserNameOperation = new GetUserInfoRemoteOperation();
|
||||
|
||||
int failed = 0;
|
||||
for (Account account : ocAccounts) {
|
||||
String storedUserId = accountManager.getUserData(account, com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID);
|
||||
|
||||
@@ -354,10 +369,12 @@ public class UserAccountManagerImpl implements UserAccountManager {
|
||||
} else {
|
||||
// skip account, try it next time
|
||||
Log_OC.e(TAG, "Error while getting username for account: " + account.name);
|
||||
failed++;
|
||||
continue;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log_OC.e(TAG, "Error while getting username: " + e.getMessage());
|
||||
failed++;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -367,11 +384,9 @@ public class UserAccountManagerImpl implements UserAccountManager {
|
||||
accountManager.setUserData(account,
|
||||
com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID,
|
||||
userId);
|
||||
|
||||
success = true;
|
||||
}
|
||||
|
||||
return success;
|
||||
return failed == 0;
|
||||
}
|
||||
|
||||
private String getAccountType() {
|
||||
|
||||
@@ -36,6 +36,8 @@ public interface AppInfo {
|
||||
*/
|
||||
String getFormattedVersionCode();
|
||||
|
||||
int getVersionCode();
|
||||
|
||||
boolean isDebugBuild();
|
||||
|
||||
String getAppVersion(Context context);
|
||||
|
||||
@@ -33,6 +33,11 @@ class AppInfoImpl implements AppInfo {
|
||||
return Integer.toString(BuildConfig.VERSION_CODE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getVersionCode() {
|
||||
return BuildConfig.VERSION_CODE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDebugBuild() {
|
||||
return BuildConfig.DEBUG;
|
||||
|
||||
@@ -25,13 +25,15 @@ import android.app.Application;
|
||||
import android.app.NotificationManager;
|
||||
import android.content.ContentResolver;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.res.Resources;
|
||||
import android.os.Handler;
|
||||
import android.media.AudioManager;
|
||||
import android.os.Handler;
|
||||
|
||||
import com.nextcloud.client.account.CurrentAccountProvider;
|
||||
import com.nextcloud.client.account.UserAccountManager;
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl;
|
||||
import com.nextcloud.client.appinfo.AppInfo;
|
||||
import com.nextcloud.client.core.AsyncRunner;
|
||||
import com.nextcloud.client.core.Clock;
|
||||
import com.nextcloud.client.core.ClockImpl;
|
||||
@@ -41,6 +43,10 @@ import com.nextcloud.client.logger.FileLogHandler;
|
||||
import com.nextcloud.client.logger.Logger;
|
||||
import com.nextcloud.client.logger.LoggerImpl;
|
||||
import com.nextcloud.client.logger.LogsRepository;
|
||||
import com.nextcloud.client.migrations.Migrations;
|
||||
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.owncloud.android.datamodel.ArbitraryDataProvider;
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager;
|
||||
@@ -52,6 +58,8 @@ import com.owncloud.android.ui.activities.data.files.FilesRepository;
|
||||
import com.owncloud.android.ui.activities.data.files.FilesServiceApiImpl;
|
||||
import com.owncloud.android.ui.activities.data.files.RemoteFilesRepository;
|
||||
|
||||
import org.greenrobot.eventbus.EventBus;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
@@ -164,4 +172,26 @@ class AppModule {
|
||||
AudioManager audioManager(Context context) {
|
||||
return (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
EventBus eventBus() {
|
||||
return EventBus.getDefault();
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
MigrationsDb migrationsDb(Application application) {
|
||||
SharedPreferences store = application.getSharedPreferences("migrations", Context.MODE_PRIVATE);
|
||||
return new MigrationsDb(store);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
MigrationsManager migrationsManager(MigrationsDb migrationsDb,
|
||||
AppInfo appInfo,
|
||||
AsyncRunner asyncRunner,
|
||||
Migrations migrations) {
|
||||
return new MigrationsManagerImpl(appInfo, migrationsDb, asyncRunner, migrations.getSteps());
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
* Nextcloud Android client application
|
||||
*
|
||||
* @author Chris Narkiewicz
|
||||
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
|
||||
* 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
|
||||
@@ -74,6 +74,7 @@ import com.owncloud.android.ui.fragment.LocalFileListFragment;
|
||||
import com.owncloud.android.ui.fragment.OCFileListFragment;
|
||||
import com.owncloud.android.ui.fragment.PhotoFragment;
|
||||
import com.owncloud.android.ui.fragment.contactsbackup.ContactListFragment;
|
||||
import com.owncloud.android.ui.fragment.contactsbackup.ContactsBackupFragment;
|
||||
import com.owncloud.android.ui.preview.PreviewImageActivity;
|
||||
import com.owncloud.android.ui.preview.PreviewImageFragment;
|
||||
import com.owncloud.android.ui.preview.PreviewMediaFragment;
|
||||
@@ -138,8 +139,8 @@ abstract class ComponentsModule {
|
||||
@ContributesAndroidInjector abstract FileDetailSharingFragment fileDetailSharingFragment();
|
||||
@ContributesAndroidInjector abstract ChooseTemplateDialogFragment chooseTemplateDialogFragment();
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract ChooseRichDocumentsTemplateDialogFragment chooseRichDocumentsTemplateDialogFragment();
|
||||
@ContributesAndroidInjector abstract ChooseRichDocumentsTemplateDialogFragment chooseRichDocumentsTemplateDialogFragment();
|
||||
@ContributesAndroidInjector abstract ContactsBackupFragment contactsBackupFragment();
|
||||
@ContributesAndroidInjector abstract PreviewImageFragment previewImageFragment();
|
||||
@ContributesAndroidInjector abstract ContactListFragment chooseContactListFragment();
|
||||
@ContributesAndroidInjector abstract PreviewMediaFragment previewMediaFragment();
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Nextcloud Android client application
|
||||
*
|
||||
* @author Chris Narkiewicz
|
||||
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
|
||||
* 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
|
||||
@@ -27,7 +27,14 @@ import androidx.lifecycle.LiveData
|
||||
import androidx.lifecycle.MutableLiveData
|
||||
import androidx.lifecycle.ViewModel
|
||||
import com.nextcloud.client.etm.pages.EtmAccountsFragment
|
||||
import com.nextcloud.client.etm.pages.EtmBackgroundJobsFragment
|
||||
import com.nextcloud.client.etm.pages.EtmMigrations
|
||||
import com.nextcloud.client.etm.pages.EtmPreferencesFragment
|
||||
import com.nextcloud.client.jobs.BackgroundJobManager
|
||||
import com.nextcloud.client.jobs.JobInfo
|
||||
import com.nextcloud.client.migrations.MigrationInfo
|
||||
import com.nextcloud.client.migrations.MigrationsDb
|
||||
import com.nextcloud.client.migrations.MigrationsManager
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils
|
||||
import javax.inject.Inject
|
||||
@@ -35,7 +42,10 @@ import javax.inject.Inject
|
||||
class EtmViewModel @Inject constructor(
|
||||
private val defaultPreferences: SharedPreferences,
|
||||
private val platformAccountManager: AccountManager,
|
||||
private val resources: Resources
|
||||
private val resources: Resources,
|
||||
private val backgroundJobManager: BackgroundJobManager,
|
||||
private val migrationsManager: MigrationsManager,
|
||||
private val migrationsDb: MigrationsDb
|
||||
) : ViewModel() {
|
||||
|
||||
companion object {
|
||||
@@ -47,6 +57,11 @@ class EtmViewModel @Inject constructor(
|
||||
AccountUtils.Constants.KEY_OC_VERSION,
|
||||
AccountUtils.Constants.KEY_USER_ID
|
||||
)
|
||||
|
||||
const val PAGE_SETTINGS = 0
|
||||
const val PAGE_ACCOUNTS = 1
|
||||
const val PAGE_JOBS = 2
|
||||
const val PAGE_MIGRATIONS = 3
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -66,6 +81,16 @@ class EtmViewModel @Inject constructor(
|
||||
iconRes = R.drawable.ic_user,
|
||||
titleRes = R.string.etm_accounts,
|
||||
pageClass = EtmAccountsFragment::class
|
||||
),
|
||||
EtmMenuEntry(
|
||||
iconRes = R.drawable.ic_clock,
|
||||
titleRes = R.string.etm_background_jobs,
|
||||
pageClass = EtmBackgroundJobsFragment::class
|
||||
),
|
||||
EtmMenuEntry(
|
||||
iconRes = R.drawable.ic_arrow_up,
|
||||
titleRes = R.string.etm_migrations,
|
||||
pageClass = EtmMigrations::class
|
||||
)
|
||||
)
|
||||
|
||||
@@ -86,6 +111,22 @@ class EtmViewModel @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
val backgroundJobs: LiveData<List<JobInfo>> get() {
|
||||
return backgroundJobManager.jobs
|
||||
}
|
||||
|
||||
val migrationsInfo: List<MigrationInfo> get() {
|
||||
return migrationsManager.info
|
||||
}
|
||||
|
||||
val migrationsStatus: MigrationsManager.Status get() {
|
||||
return migrationsManager.status.value ?: MigrationsManager.Status.UNKNOWN
|
||||
}
|
||||
|
||||
val lastMigratedVersion: Int get() {
|
||||
return migrationsDb.lastMigratedVersion
|
||||
}
|
||||
|
||||
init {
|
||||
(currentPage as MutableLiveData).apply {
|
||||
value = null
|
||||
@@ -108,4 +149,24 @@ class EtmViewModel @Inject constructor(
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fun pruneJobs() {
|
||||
backgroundJobManager.pruneJobs()
|
||||
}
|
||||
|
||||
fun cancelAllJobs() {
|
||||
backgroundJobManager.cancelAllJobs()
|
||||
}
|
||||
|
||||
fun startTestJob() {
|
||||
backgroundJobManager.scheduleTestJob()
|
||||
}
|
||||
|
||||
fun cancelTestJob() {
|
||||
backgroundJobManager.cancelTestJob()
|
||||
}
|
||||
|
||||
fun clearMigrations() {
|
||||
migrationsDb.clearMigrations()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
/*
|
||||
* 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.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.lifecycle.Observer
|
||||
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.jobs.JobInfo
|
||||
import com.owncloud.android.R
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Locale
|
||||
|
||||
class EtmBackgroundJobsFragment : EtmBaseFragment() {
|
||||
|
||||
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_background_job_uuid)
|
||||
val name = view.findViewById<TextView>(R.id.etm_background_job_name)
|
||||
val user = view.findViewById<TextView>(R.id.etm_background_job_user)
|
||||
val state = view.findViewById<TextView>(R.id.etm_background_job_state)
|
||||
val started = view.findViewById<TextView>(R.id.etm_background_job_started)
|
||||
val progress = view.findViewById<TextView>(R.id.etm_background_job_progress)
|
||||
private val progressRow = view.findViewById<View>(R.id.etm_background_job_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 val dateFormat = SimpleDateFormat("YYYY-MM-dd HH:MM:ssZ", Locale.getDefault())
|
||||
var backgroundJobs: List<JobInfo> = emptyList()
|
||||
set(value) {
|
||||
field = value
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
|
||||
val view = inflater.inflate(R.layout.etm_background_job_list_item, parent, false)
|
||||
return ViewHolder(view)
|
||||
}
|
||||
|
||||
override fun getItemCount(): Int {
|
||||
return backgroundJobs.size
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(vh: ViewHolder, position: Int) {
|
||||
val info = backgroundJobs[position]
|
||||
vh.uuid.text = info.id.toString()
|
||||
vh.name.text = info.name
|
||||
vh.user.text = info.user
|
||||
vh.state.text = info.state
|
||||
vh.started.text = dateFormat.format(info.started)
|
||||
if (info.progress >= 0) {
|
||||
vh.progressEnabled = true
|
||||
vh.progress.text = info.progress.toString()
|
||||
} else {
|
||||
vh.progressEnabled = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private lateinit var list: RecyclerView
|
||||
private lateinit var adapter: Adapter
|
||||
|
||||
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_background_jobs, container, false)
|
||||
adapter = Adapter(inflater)
|
||||
list = view.findViewById(R.id.etm_background_jobs_list)
|
||||
list.layoutManager = LinearLayoutManager(context)
|
||||
list.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
|
||||
list.adapter = adapter
|
||||
vm.backgroundJobs.observe(this, Observer { onBackgroundJobsUpdated(it) })
|
||||
return view
|
||||
}
|
||||
|
||||
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
|
||||
super.onCreateOptionsMenu(menu, inflater)
|
||||
inflater.inflate(R.menu.fragment_etm_background_jobs, menu)
|
||||
}
|
||||
|
||||
override fun onOptionsItemSelected(item: MenuItem): Boolean {
|
||||
return when (item.itemId) {
|
||||
R.id.etm_background_jobs_cancel -> {
|
||||
vm.cancelAllJobs(); true
|
||||
}
|
||||
R.id.etm_background_jobs_prune -> {
|
||||
vm.pruneJobs(); true
|
||||
}
|
||||
R.id.etm_background_jobs_start_test -> {
|
||||
vm.startTestJob(); true
|
||||
}
|
||||
R.id.etm_background_jobs_cancel_test -> {
|
||||
vm.cancelTestJob(); true
|
||||
}
|
||||
else -> super.onOptionsItemSelected(item)
|
||||
}
|
||||
}
|
||||
|
||||
private fun onBackgroundJobsUpdated(backgroundJobs: List<JobInfo>) {
|
||||
adapter.backgroundJobs = backgroundJobs
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
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 com.nextcloud.client.etm.EtmBaseFragment
|
||||
import com.owncloud.android.R
|
||||
import kotlinx.android.synthetic.main.fragment_etm_migrations.*
|
||||
import java.util.Locale
|
||||
|
||||
class EtmMigrations : EtmBaseFragment() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setHasOptionsMenu(true)
|
||||
}
|
||||
|
||||
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
|
||||
return inflater.inflate(R.layout.fragment_etm_migrations, container, false)
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
showStatus()
|
||||
}
|
||||
|
||||
fun showStatus() {
|
||||
val builder = StringBuilder()
|
||||
val status = vm.migrationsStatus.toString().toLowerCase(Locale.US)
|
||||
builder.append("Migration status: $status\n")
|
||||
val lastMigratedVersion = if (vm.lastMigratedVersion >= 0) {
|
||||
vm.lastMigratedVersion.toString()
|
||||
} else {
|
||||
"never"
|
||||
}
|
||||
builder.append("Last migrated version: $lastMigratedVersion\n")
|
||||
builder.append("Migrations:\n")
|
||||
vm.migrationsInfo.forEach {
|
||||
val migrationStatus = if (it.applied) {
|
||||
"applied"
|
||||
} else {
|
||||
"pending"
|
||||
}
|
||||
builder.append(" - ${it.id} ${it.description} - $migrationStatus\n")
|
||||
}
|
||||
etm_migrations_text.text = builder.toString()
|
||||
}
|
||||
|
||||
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
|
||||
super.onCreateOptionsMenu(menu, inflater)
|
||||
inflater.inflate(R.menu.fragment_etm_migrations, menu)
|
||||
}
|
||||
|
||||
override fun onOptionsItemSelected(item: MenuItem): Boolean {
|
||||
return when (item.itemId) {
|
||||
R.id.etm_migrations_delete -> {
|
||||
onDeleteMigrationsClicked(); true
|
||||
}
|
||||
else -> super.onOptionsItemSelected(item)
|
||||
}
|
||||
}
|
||||
|
||||
private fun onDeleteMigrationsClicked() {
|
||||
vm.clearMigrations()
|
||||
showStatus()
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
* Nextcloud Android client application
|
||||
*
|
||||
* @author Chris Narkiewicz
|
||||
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
|
||||
* 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
|
||||
@@ -21,15 +21,18 @@ package com.nextcloud.client.jobs
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.content.res.Resources
|
||||
import android.os.Build
|
||||
import androidx.annotation.RequiresApi
|
||||
import androidx.work.ListenableWorker
|
||||
import androidx.work.WorkerFactory
|
||||
import androidx.work.WorkerParameters
|
||||
import com.nextcloud.client.account.UserAccountManager
|
||||
import com.nextcloud.client.core.Clock
|
||||
import com.nextcloud.client.device.DeviceInfo
|
||||
import com.nextcloud.client.device.PowerManagementService
|
||||
import com.nextcloud.client.preferences.AppPreferences
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProvider
|
||||
import com.owncloud.android.datamodel.SyncedFolderProvider
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
@@ -44,7 +47,10 @@ class BackgroundJobFactory @Inject constructor(
|
||||
private val clock: Clock,
|
||||
private val powerManagerService: PowerManagementService,
|
||||
private val backgroundJobManager: Provider<BackgroundJobManager>,
|
||||
private val deviceInfo: DeviceInfo
|
||||
private val deviceInfo: DeviceInfo,
|
||||
private val accountManager: UserAccountManager,
|
||||
private val resources: Resources,
|
||||
private val dataProvider: ArbitraryDataProvider
|
||||
) : WorkerFactory() {
|
||||
|
||||
override fun createWorker(
|
||||
@@ -61,12 +67,16 @@ class BackgroundJobFactory @Inject constructor(
|
||||
|
||||
return when (workerClass) {
|
||||
ContentObserverWork::class -> createContentObserverJob(context, workerParameters, clock)
|
||||
ContactsBackupWork::class -> createContactsBackupWork(context, workerParameters)
|
||||
else -> null // falls back to default factory
|
||||
}
|
||||
}
|
||||
|
||||
private fun createContentObserverJob(context: Context, workerParameters: WorkerParameters, clock: Clock):
|
||||
ListenableWorker? {
|
||||
private fun createContentObserverJob(
|
||||
context: Context,
|
||||
workerParameters: WorkerParameters,
|
||||
clock: Clock
|
||||
): ListenableWorker? {
|
||||
val folderResolver = SyncedFolderProvider(contentResolver, preferences, clock)
|
||||
@RequiresApi(Build.VERSION_CODES.N)
|
||||
if (deviceInfo.apiLevel >= Build.VERSION_CODES.N) {
|
||||
@@ -81,4 +91,15 @@ class BackgroundJobFactory @Inject constructor(
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private fun createContactsBackupWork(context: Context, params: WorkerParameters): ContactsBackupWork {
|
||||
return ContactsBackupWork(
|
||||
context,
|
||||
params,
|
||||
resources,
|
||||
dataProvider,
|
||||
contentResolver,
|
||||
accountManager
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
* Nextcloud Android client application
|
||||
*
|
||||
* @author Chris Narkiewicz
|
||||
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
|
||||
* 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
|
||||
@@ -21,6 +21,8 @@ package com.nextcloud.client.jobs
|
||||
|
||||
import android.os.Build
|
||||
import androidx.annotation.RequiresApi
|
||||
import androidx.lifecycle.LiveData
|
||||
import com.nextcloud.client.account.User
|
||||
|
||||
/**
|
||||
* This interface allows to control, schedule and monitor all application
|
||||
@@ -28,10 +30,49 @@ import androidx.annotation.RequiresApi
|
||||
*/
|
||||
interface BackgroundJobManager {
|
||||
|
||||
/**
|
||||
* Information about all application background jobs.
|
||||
*/
|
||||
val jobs: LiveData<List<JobInfo>>
|
||||
|
||||
/**
|
||||
* Start content observer job that monitors changes in media folders
|
||||
* and launches synchronization when needed.
|
||||
*
|
||||
* This call is idempotent - there will be only one scheduled job
|
||||
* regardless of number of calls.
|
||||
*/
|
||||
@RequiresApi(Build.VERSION_CODES.N)
|
||||
fun scheduleContentObserverJob()
|
||||
|
||||
/**
|
||||
* Schedule periodic contacts backups job. Operating system will
|
||||
* decide when to start the job.
|
||||
*
|
||||
* This call is idempotent - there can be only one scheduled job
|
||||
* at any given time.
|
||||
*
|
||||
* @param user User for which job will be scheduled.
|
||||
*/
|
||||
fun schedulePeriodicContactsBackup(user: User)
|
||||
|
||||
/**
|
||||
* Cancel periodic contacts backup. Existing tasks might finish, but no new
|
||||
* invocations will occur.
|
||||
*/
|
||||
fun cancelPeriodicContactsBackup(user: User)
|
||||
|
||||
/**
|
||||
* Immediately start single contacts backup job.
|
||||
* This job will launch independently from periodic contacts backup.
|
||||
*
|
||||
* @return Job info with current status, or null if job does not exist anymore
|
||||
*/
|
||||
fun startImmediateContactsBackup(user: User): LiveData<JobInfo?>
|
||||
|
||||
fun scheduleTestJob()
|
||||
fun cancelTestJob()
|
||||
|
||||
fun pruneJobs()
|
||||
fun cancelAllJobs()
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
* Nextcloud Android client application
|
||||
*
|
||||
* @author Chris Narkiewicz
|
||||
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
|
||||
* 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
|
||||
@@ -22,18 +22,172 @@ package com.nextcloud.client.jobs
|
||||
import android.os.Build
|
||||
import android.provider.MediaStore
|
||||
import androidx.annotation.RequiresApi
|
||||
import androidx.lifecycle.LiveData
|
||||
import androidx.lifecycle.Transformations
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.Data
|
||||
import androidx.work.ExistingPeriodicWorkPolicy
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.ListenableWorker
|
||||
import androidx.work.OneTimeWorkRequest
|
||||
import androidx.work.Operation
|
||||
import androidx.work.PeriodicWorkRequest
|
||||
import androidx.work.WorkInfo
|
||||
import androidx.work.WorkManager
|
||||
import com.nextcloud.client.account.User
|
||||
import com.nextcloud.client.core.Clock
|
||||
import java.util.Date
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
internal class BackgroundJobManagerImpl(private val workManager: WorkManager) : BackgroundJobManager {
|
||||
/**
|
||||
* Note to maintainers
|
||||
*
|
||||
* Since [androidx.work.WorkManager] is missing API to easily attach worker metadata,
|
||||
* we use tags API to attach our custom metadata.
|
||||
*
|
||||
* To create new job request, use [BackgroundJobManagerImpl.oneTimeRequestBuilder] and
|
||||
* [BackgroundJobManagerImpl.periodicRequestBuilder] calls, instead of calling
|
||||
* platform builders. Those methods will create builders pre-set with mandatory tags.
|
||||
*
|
||||
* Since Google is notoriously releasing new background job services, [androidx.work.WorkManager] API is
|
||||
* considered private implementation detail and should not be leaked through the interface, to minimize
|
||||
* potential migration cost in the future.
|
||||
*/
|
||||
@Suppress("TooManyFunctions") // we expect this implementation to have rich API
|
||||
internal class BackgroundJobManagerImpl(
|
||||
private val workManager: WorkManager,
|
||||
private val clock: Clock
|
||||
) : BackgroundJobManager {
|
||||
|
||||
companion object {
|
||||
const val TAG_CONTENT_SYNC = "content_sync"
|
||||
const val TAG_ALL = "*" // This tag allows us to retrieve list of all jobs run by Nextcloud client
|
||||
const val JOB_CONTENT_OBSERVER = "content_observer"
|
||||
const val JOB_PERIODIC_CONTACTS_BACKUP = "periodic_contacts_backup"
|
||||
const val JOB_IMMEDIATE_CONTACTS_BACKUP = "immediate_contacts_backup"
|
||||
const val JOB_TEST = "test_job"
|
||||
|
||||
const val MAX_CONTENT_TRIGGER_DELAY_MS = 1500L
|
||||
|
||||
const val TAG_PREFIX_NAME = "name"
|
||||
const val TAG_PREFIX_USER = "user"
|
||||
const val TAG_PREFIX_START_TIMESTAMP = "timestamp"
|
||||
val PREFIXES = setOf(TAG_PREFIX_NAME, TAG_PREFIX_USER, TAG_PREFIX_START_TIMESTAMP)
|
||||
const val NOT_SET_VALUE = "not set"
|
||||
const val DEFAULT_PERIODIC_JOB_INTERVAL_MINUTES = 15L
|
||||
const val INTERVAL_SECOND = 1000L
|
||||
const val INTERVAL_MINUTE = 60L * INTERVAL_SECOND
|
||||
const val INTERVAL_HOUR = 60 * INTERVAL_MINUTE
|
||||
const val INTERVAL_24H = 24L * INTERVAL_HOUR
|
||||
|
||||
fun formatNameTag(name: String, user: User? = null): String {
|
||||
return if (user == null) {
|
||||
"$TAG_PREFIX_NAME:$name"
|
||||
} else {
|
||||
"$TAG_PREFIX_NAME:$name ${user.accountName}"
|
||||
}
|
||||
}
|
||||
fun formatUserTag(user: User): String = "$TAG_PREFIX_USER:${user.accountName}"
|
||||
fun formatTimeTag(startTimestamp: Long): String = "$TAG_PREFIX_START_TIMESTAMP:$startTimestamp"
|
||||
|
||||
fun parseTag(tag: String): Pair<String, String>? {
|
||||
val key = tag.substringBefore(":", "")
|
||||
val value = tag.substringAfter(":", "")
|
||||
return if (key in PREFIXES) {
|
||||
key to value
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun parseTimestamp(timestamp: String): Date {
|
||||
try {
|
||||
val ms = timestamp.toLong()
|
||||
return Date(ms)
|
||||
} catch (ex: NumberFormatException) {
|
||||
return Date(0)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert platform [androidx.work.WorkInfo] object into application-specific [JobInfo] model.
|
||||
* Conversion extracts work metadata from tags.
|
||||
*/
|
||||
fun fromWorkInfo(info: WorkInfo?): JobInfo? {
|
||||
return if (info != null) {
|
||||
val metadata = mutableMapOf<String, String>()
|
||||
info.tags.forEach { parseTag(it)?.let { metadata[it.first] = it.second } }
|
||||
val timestamp = parseTimestamp(metadata.get(TAG_PREFIX_START_TIMESTAMP) ?: "0")
|
||||
JobInfo(
|
||||
id = info.id,
|
||||
state = info.state.toString(),
|
||||
name = metadata.get(TAG_PREFIX_NAME) ?: NOT_SET_VALUE,
|
||||
user = metadata.get(TAG_PREFIX_USER) ?: NOT_SET_VALUE,
|
||||
started = timestamp,
|
||||
progress = info.progress.getInt("progress", -1)
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create [OneTimeWorkRequest.Builder] pre-set with common attributes
|
||||
*/
|
||||
private fun oneTimeRequestBuilder(
|
||||
jobClass: KClass<out ListenableWorker>,
|
||||
jobName: String,
|
||||
user: User? = null
|
||||
): OneTimeWorkRequest.Builder {
|
||||
val builder = OneTimeWorkRequest.Builder(jobClass.java)
|
||||
.addTag(TAG_ALL)
|
||||
.addTag(formatNameTag(jobName, user))
|
||||
.addTag(formatTimeTag(clock.currentTime))
|
||||
user?.let { builder.addTag(formatUserTag(it)) }
|
||||
return builder
|
||||
}
|
||||
|
||||
/**
|
||||
* Create [PeriodicWorkRequest] pre-set with common attributes
|
||||
*/
|
||||
private fun periodicRequestBuilder(
|
||||
jobClass: KClass<out ListenableWorker>,
|
||||
jobName: String,
|
||||
intervalMins: Long = DEFAULT_PERIODIC_JOB_INTERVAL_MINUTES,
|
||||
user: User? = null
|
||||
): PeriodicWorkRequest.Builder {
|
||||
val builder = PeriodicWorkRequest.Builder(jobClass.java, intervalMins, TimeUnit.MINUTES)
|
||||
.addTag(TAG_ALL)
|
||||
.addTag(formatNameTag(jobName, user))
|
||||
.addTag(formatTimeTag(clock.currentTime))
|
||||
user?.let { builder.addTag(formatUserTag(it)) }
|
||||
return builder
|
||||
}
|
||||
|
||||
private fun WorkManager.getJobInfo(id: UUID): LiveData<JobInfo?> {
|
||||
val workInfo = getWorkInfoByIdLiveData(id)
|
||||
return Transformations.map(workInfo) { fromWorkInfo(it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel work using name tag with optional user scope.
|
||||
* All work instances will be cancelled.
|
||||
*/
|
||||
private fun WorkManager.cancelJob(name: String, user: User? = null): Operation {
|
||||
val tag = formatNameTag(name, user)
|
||||
return cancelAllWorkByTag(tag)
|
||||
}
|
||||
|
||||
override val jobs: LiveData<List<JobInfo>>
|
||||
get() {
|
||||
val workInfo = workManager.getWorkInfosByTagLiveData("*")
|
||||
return Transformations.map(workInfo) {
|
||||
it.map { fromWorkInfo(it) ?: JobInfo() }.sortedBy { it.started }.reversed()
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.N)
|
||||
override fun scheduleContentObserverJob() {
|
||||
val constrains = Constraints.Builder()
|
||||
@@ -44,11 +198,62 @@ internal class BackgroundJobManagerImpl(private val workManager: WorkManager) :
|
||||
.setTriggerContentMaxDelay(MAX_CONTENT_TRIGGER_DELAY_MS, TimeUnit.MILLISECONDS)
|
||||
.build()
|
||||
|
||||
val request = OneTimeWorkRequest.Builder(ContentObserverWork::class.java)
|
||||
val request = oneTimeRequestBuilder(ContentObserverWork::class, JOB_CONTENT_OBSERVER)
|
||||
.setConstraints(constrains)
|
||||
.addTag(TAG_CONTENT_SYNC)
|
||||
.build()
|
||||
|
||||
workManager.enqueue(request)
|
||||
workManager.enqueueUniqueWork(JOB_CONTENT_OBSERVER, ExistingWorkPolicy.KEEP, request)
|
||||
}
|
||||
|
||||
override fun schedulePeriodicContactsBackup(user: User) {
|
||||
val data = Data.Builder()
|
||||
.putString(ContactsBackupWork.ACCOUNT, user.accountName)
|
||||
.putBoolean(ContactsBackupWork.FORCE, true)
|
||||
.build()
|
||||
|
||||
val request = periodicRequestBuilder(
|
||||
ContactsBackupWork::class,
|
||||
JOB_PERIODIC_CONTACTS_BACKUP,
|
||||
INTERVAL_24H,
|
||||
user
|
||||
).setInputData(data).build()
|
||||
|
||||
workManager.enqueueUniquePeriodicWork(JOB_PERIODIC_CONTACTS_BACKUP, ExistingPeriodicWorkPolicy.KEEP, request)
|
||||
}
|
||||
|
||||
override fun cancelPeriodicContactsBackup(user: User) {
|
||||
workManager.cancelJob(JOB_PERIODIC_CONTACTS_BACKUP, user)
|
||||
}
|
||||
|
||||
override fun startImmediateContactsBackup(user: User): LiveData<JobInfo?> {
|
||||
val data = Data.Builder()
|
||||
.putString(ContactsBackupWork.ACCOUNT, user.accountName)
|
||||
.putBoolean(ContactsBackupWork.FORCE, true)
|
||||
.build()
|
||||
|
||||
val request = oneTimeRequestBuilder(ContactsBackupWork::class, JOB_IMMEDIATE_CONTACTS_BACKUP, user)
|
||||
.setInputData(data)
|
||||
.build()
|
||||
|
||||
workManager.enqueueUniqueWork(JOB_IMMEDIATE_CONTACTS_BACKUP, ExistingWorkPolicy.KEEP, request)
|
||||
return workManager.getJobInfo(request.id)
|
||||
}
|
||||
|
||||
override fun scheduleTestJob() {
|
||||
val request = periodicRequestBuilder(TestJob::class, JOB_TEST)
|
||||
.build()
|
||||
workManager.enqueueUniquePeriodicWork(JOB_TEST, ExistingPeriodicWorkPolicy.KEEP, request)
|
||||
}
|
||||
|
||||
override fun cancelTestJob() {
|
||||
workManager.cancelAllWorkByTag(formatNameTag(JOB_TEST))
|
||||
}
|
||||
|
||||
override fun pruneJobs() {
|
||||
workManager.pruneWork()
|
||||
}
|
||||
|
||||
override fun cancelAllJobs() {
|
||||
workManager.cancelAllWorkByTag(TAG_ALL)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
/*
|
||||
* 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.jobs
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.ServiceConnection
|
||||
import android.content.res.Resources
|
||||
import android.database.Cursor
|
||||
import android.net.Uri
|
||||
import android.os.IBinder
|
||||
import android.provider.ContactsContract
|
||||
import android.text.TextUtils
|
||||
import android.text.format.DateFormat
|
||||
import androidx.work.Worker
|
||||
import androidx.work.WorkerParameters
|
||||
import com.nextcloud.client.account.User
|
||||
import com.nextcloud.client.account.UserAccountManager
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProvider
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.files.services.FileUploader
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.operations.UploadFileOperation
|
||||
import com.owncloud.android.services.OperationsService
|
||||
import com.owncloud.android.services.OperationsService.OperationsServiceBinder
|
||||
import com.owncloud.android.ui.activity.ContactsPreferenceActivity
|
||||
import ezvcard.Ezvcard
|
||||
import ezvcard.VCardVersion
|
||||
import java.io.File
|
||||
import java.io.FileWriter
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.io.InputStreamReader
|
||||
import java.util.ArrayList
|
||||
import java.util.Calendar
|
||||
|
||||
class ContactsBackupWork(
|
||||
appContext: Context,
|
||||
params: WorkerParameters,
|
||||
private val resources: Resources,
|
||||
private val arbitraryDataProvider: ArbitraryDataProvider,
|
||||
private val contentResolver: ContentResolver,
|
||||
private val accountManager: UserAccountManager
|
||||
) : Worker(appContext, params) {
|
||||
|
||||
companion object {
|
||||
val TAG = ContactsBackupWork::class.java.simpleName
|
||||
const val ACCOUNT = "account"
|
||||
const val FORCE = "force"
|
||||
const val JOB_INTERVAL_MS: Long = 24 * 60 * 60 * 1000
|
||||
const val BUFFER_SIZE = 1024
|
||||
}
|
||||
|
||||
private var operationsServiceConnection: OperationsServiceConnection? = null
|
||||
private var operationsServiceBinder: OperationsServiceBinder? = null
|
||||
|
||||
@Suppress("ReturnCount") // pre-existing issue
|
||||
override fun doWork(): Result {
|
||||
val accountName = inputData.getString(ACCOUNT) ?: ""
|
||||
if (TextUtils.isEmpty(accountName)) { // no account provided
|
||||
return Result.failure()
|
||||
}
|
||||
val optionalUser = accountManager.getUser(accountName)
|
||||
if (!optionalUser.isPresent) {
|
||||
return Result.failure()
|
||||
}
|
||||
val user = optionalUser.get()
|
||||
val lastExecution = arbitraryDataProvider.getLongValue(user.toPlatformAccount(),
|
||||
ContactsPreferenceActivity.PREFERENCE_CONTACTS_LAST_BACKUP)
|
||||
val force = inputData.getBoolean(FORCE, false)
|
||||
if (force || lastExecution + JOB_INTERVAL_MS < Calendar.getInstance().timeInMillis) {
|
||||
Log_OC.d(TAG, "start contacts backup job")
|
||||
val backupFolder: String = resources.getString(R.string.contacts_backup_folder) + OCFile.PATH_SEPARATOR
|
||||
val daysToExpire: Int = applicationContext.getResources().getInteger(R.integer.contacts_backup_expire)
|
||||
backupContact(user, backupFolder)
|
||||
// bind to Operations Service
|
||||
operationsServiceConnection = OperationsServiceConnection(
|
||||
this,
|
||||
daysToExpire,
|
||||
backupFolder,
|
||||
user
|
||||
)
|
||||
applicationContext.bindService(
|
||||
Intent(applicationContext, OperationsService::class.java),
|
||||
operationsServiceConnection as OperationsServiceConnection,
|
||||
OperationsService.BIND_AUTO_CREATE
|
||||
)
|
||||
// store execution date
|
||||
arbitraryDataProvider.storeOrUpdateKeyValue(
|
||||
user.accountName,
|
||||
ContactsPreferenceActivity.PREFERENCE_CONTACTS_LAST_BACKUP,
|
||||
Calendar.getInstance().timeInMillis
|
||||
)
|
||||
} else {
|
||||
Log_OC.d(TAG, "last execution less than 24h ago")
|
||||
}
|
||||
return Result.success()
|
||||
}
|
||||
|
||||
private fun backupContact(user: User, backupFolder: String) {
|
||||
val vCard = ArrayList<String>()
|
||||
val cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null,
|
||||
null, null, null)
|
||||
if (cursor != null && cursor.count > 0) {
|
||||
cursor.moveToFirst()
|
||||
for (i in 0 until cursor.count) {
|
||||
vCard.add(getContactFromCursor(cursor))
|
||||
cursor.moveToNext()
|
||||
}
|
||||
}
|
||||
val filename = DateFormat.format("yyyy-MM-dd_HH-mm-ss", Calendar.getInstance()).toString() + ".vcf"
|
||||
Log_OC.d(TAG, "Storing: $filename")
|
||||
val file = File(applicationContext.getCacheDir(), filename)
|
||||
var fw: FileWriter? = null
|
||||
try {
|
||||
fw = FileWriter(file)
|
||||
for (card in vCard) {
|
||||
fw.write(card)
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
Log_OC.d(TAG, "Error ", e)
|
||||
} finally {
|
||||
cursor?.close()
|
||||
if (fw != null) {
|
||||
try {
|
||||
fw.close()
|
||||
} catch (e: IOException) {
|
||||
Log_OC.d(TAG, "Error closing file writer ", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
FileUploader.uploadNewFile(
|
||||
applicationContext,
|
||||
user.toPlatformAccount(),
|
||||
file.absolutePath,
|
||||
backupFolder + filename,
|
||||
FileUploader.LOCAL_BEHAVIOUR_MOVE,
|
||||
null,
|
||||
true,
|
||||
UploadFileOperation.CREATED_BY_USER,
|
||||
false,
|
||||
false,
|
||||
FileUploader.NameCollisionPolicy.ASK_USER
|
||||
)
|
||||
}
|
||||
|
||||
private fun expireFiles(daysToExpire: Int, backupFolderString: String, account: User) { // -1 disables expiration
|
||||
if (daysToExpire > -1) {
|
||||
val storageManager = FileDataStorageManager(account.toPlatformAccount(),
|
||||
applicationContext.getContentResolver())
|
||||
val backupFolder: OCFile = storageManager.getFileByPath(backupFolderString)
|
||||
val cal = Calendar.getInstance()
|
||||
cal.add(Calendar.DAY_OF_YEAR, -daysToExpire)
|
||||
val timestampToExpire = cal.timeInMillis
|
||||
if (backupFolder != null) {
|
||||
Log_OC.d(TAG, "expire: " + daysToExpire + " " + backupFolder.fileName)
|
||||
}
|
||||
val backups: List<OCFile> = storageManager.getFolderContent(backupFolder, false)
|
||||
for (backup in backups) {
|
||||
if (timestampToExpire > backup.modificationTimestamp) {
|
||||
Log_OC.d(TAG, "delete " + backup.remotePath)
|
||||
// delete backups
|
||||
val service = Intent(applicationContext, OperationsService::class.java)
|
||||
service.action = OperationsService.ACTION_REMOVE
|
||||
service.putExtra(OperationsService.EXTRA_ACCOUNT, account)
|
||||
service.putExtra(OperationsService.EXTRA_REMOTE_PATH, backup.remotePath)
|
||||
service.putExtra(OperationsService.EXTRA_REMOVE_ONLY_LOCAL, false)
|
||||
operationsServiceBinder!!.queueNewOperation(service)
|
||||
}
|
||||
}
|
||||
}
|
||||
operationsServiceConnection?.let {
|
||||
applicationContext.unbindService(it)
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("NestedBlockDepth")
|
||||
private fun getContactFromCursor(cursor: Cursor): String {
|
||||
val lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY))
|
||||
val uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey)
|
||||
var vCard = ""
|
||||
var inputStream: InputStream? = null
|
||||
var inputStreamReader: InputStreamReader? = null
|
||||
try {
|
||||
inputStream = applicationContext.getContentResolver().openInputStream(uri)
|
||||
val buffer = CharArray(BUFFER_SIZE)
|
||||
val stringBuilder = StringBuilder()
|
||||
if (inputStream != null) {
|
||||
inputStreamReader = InputStreamReader(inputStream)
|
||||
while (true) {
|
||||
val byteCount = inputStreamReader.read(buffer, 0, buffer.size)
|
||||
if (byteCount > 0) {
|
||||
stringBuilder.append(buffer, 0, byteCount)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
vCard = stringBuilder.toString()
|
||||
// bump to vCard 3.0 format (min version supported by server) since Android OS exports to 2.1
|
||||
return Ezvcard.write(Ezvcard.parse(vCard).all()).version(VCardVersion.V3_0).go()
|
||||
} catch (e: IOException) {
|
||||
Log_OC.d(TAG, e.message)
|
||||
} finally {
|
||||
try {
|
||||
inputStream?.close()
|
||||
inputStreamReader?.close()
|
||||
} catch (e: IOException) {
|
||||
Log_OC.e(TAG, "failed to close stream")
|
||||
}
|
||||
}
|
||||
return vCard
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements callback methods for service binding.
|
||||
*/
|
||||
private class OperationsServiceConnection internal constructor(
|
||||
private val worker: ContactsBackupWork,
|
||||
private val daysToExpire: Int,
|
||||
private val backupFolder: String,
|
||||
private val user: User
|
||||
) : ServiceConnection {
|
||||
override fun onServiceConnected(component: ComponentName, service: IBinder) {
|
||||
Log_OC.d(TAG, "service connected")
|
||||
if (component == ComponentName(worker.applicationContext, OperationsService::class.java)) {
|
||||
worker.operationsServiceBinder = service as OperationsServiceBinder
|
||||
worker.expireFiles(daysToExpire, backupFolder, user)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onServiceDisconnected(component: ComponentName) {
|
||||
Log_OC.d(TAG, "service disconnected")
|
||||
if (component == ComponentName(worker.applicationContext, OperationsService::class.java)) {
|
||||
worker.operationsServiceBinder = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* 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.jobs
|
||||
|
||||
import java.util.Date
|
||||
import java.util.UUID
|
||||
|
||||
data class JobInfo(
|
||||
val id: UUID = UUID.fromString("00000000-0000-0000-0000-000000000000"),
|
||||
val state: String = "",
|
||||
val name: String = "",
|
||||
val user: String = "",
|
||||
val started: Date = Date(0),
|
||||
val progress: Int = 0
|
||||
)
|
||||
@@ -2,7 +2,7 @@
|
||||
* Nextcloud Android client application
|
||||
*
|
||||
* @author Chris Narkiewicz
|
||||
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
|
||||
* 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
|
||||
@@ -23,6 +23,7 @@ import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import androidx.work.Configuration
|
||||
import androidx.work.WorkManager
|
||||
import com.nextcloud.client.core.Clock
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import javax.inject.Singleton
|
||||
@@ -32,7 +33,7 @@ class JobsModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun backgroundJobManager(context: Context, factory: BackgroundJobFactory): BackgroundJobManager {
|
||||
fun workManager(context: Context, factory: BackgroundJobFactory): WorkManager {
|
||||
val configuration = Configuration.Builder()
|
||||
.setWorkerFactory(factory)
|
||||
.build()
|
||||
@@ -44,7 +45,12 @@ class JobsModule {
|
||||
}
|
||||
|
||||
WorkManager.initialize(contextWrapper, configuration)
|
||||
val wm = WorkManager.getInstance(context)
|
||||
return BackgroundJobManagerImpl(wm)
|
||||
return WorkManager.getInstance(context)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun backgroundJobManager(workManager: WorkManager, clock: Clock): BackgroundJobManager {
|
||||
return BackgroundJobManagerImpl(workManager, clock)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* 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.jobs
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.Data
|
||||
import androidx.work.Worker
|
||||
import androidx.work.WorkerParameters
|
||||
|
||||
class TestJob(
|
||||
appContext: Context,
|
||||
params: WorkerParameters
|
||||
) : Worker(appContext, params) {
|
||||
|
||||
companion object {
|
||||
private const val MAX_PROGRESS = 100
|
||||
private const val DELAY_MS = 1000L
|
||||
private const val PROGRESS_KEY = "progress"
|
||||
}
|
||||
|
||||
override fun doWork(): Result {
|
||||
for (i in 0..MAX_PROGRESS) {
|
||||
Thread.sleep(DELAY_MS)
|
||||
val progress = Data.Builder()
|
||||
.putInt(PROGRESS_KEY, i)
|
||||
.build()
|
||||
setProgressAsync(progress)
|
||||
}
|
||||
return Result.success()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* 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.migrations
|
||||
|
||||
class MigrationError(val id: Int, message: String, cause: Throwable?) : RuntimeException(message, cause) {
|
||||
constructor(id: Int, message: String) : this(id, message, null)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* 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.migrations
|
||||
|
||||
data class MigrationInfo(val id: Int, val description: String, val applied: Boolean)
|
||||
@@ -0,0 +1,131 @@
|
||||
/*
|
||||
* 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.migrations
|
||||
|
||||
import android.os.Build
|
||||
import androidx.work.WorkManager
|
||||
import com.nextcloud.client.account.UserAccountManager
|
||||
import com.nextcloud.client.jobs.BackgroundJobManager
|
||||
import com.nextcloud.client.logger.Logger
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProvider
|
||||
import com.owncloud.android.ui.activity.ContactsPreferenceActivity
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* This class collects all migration steps and provides API to supply those
|
||||
* steps to [MigrationsManager] for execution.
|
||||
*/
|
||||
class Migrations @Inject constructor(
|
||||
private val logger: Logger,
|
||||
private val userAccountManager: UserAccountManager,
|
||||
private val workManager: WorkManager,
|
||||
private val arbitraryDataProvider: ArbitraryDataProvider,
|
||||
private val jobManager: BackgroundJobManager
|
||||
) {
|
||||
|
||||
companion object {
|
||||
val TAG = Migrations::class.java.simpleName
|
||||
}
|
||||
|
||||
/**
|
||||
* This class wraps migration logic with some metadata with some
|
||||
* metadata required to register and log overall migration progress.
|
||||
*
|
||||
* @param id Step id; id must be unique; this is verified upon registration
|
||||
* @param description Human readable migration step descriptionsss
|
||||
* @param mandatory If true, failing migration will cause an exception; if false, it will be skipped and repeated
|
||||
* again on next startup
|
||||
* @throws Exception migration logic is permitted to throw any kind of exceptions; all exceptions will be wrapped
|
||||
* into [MigrationException]
|
||||
*/
|
||||
abstract class Step(val id: Int, val description: String, val mandatory: Boolean = true) : Runnable
|
||||
|
||||
/**
|
||||
* Migrate legacy accounts by addming user IDs. This migration can be re-tried until all accounts are
|
||||
* successfully migrated.
|
||||
*/
|
||||
private val migrateUserId = object : Step(0, "Migrate user id", false) {
|
||||
override fun run() {
|
||||
val allAccountsHaveUserId = userAccountManager.migrateUserId()
|
||||
logger.i(TAG, "$description: success = $allAccountsHaveUserId")
|
||||
if (!allAccountsHaveUserId) {
|
||||
throw IllegalStateException("Failed to set user id for all accounts")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Content observer job must be restarted to use new scheduler abstraction.
|
||||
*/
|
||||
private val migrateContentObserverJob = object : Step(1, "Migrate content observer job", false) {
|
||||
override fun run() {
|
||||
val legacyWork = workManager.getWorkInfosByTag("content_sync").get()
|
||||
legacyWork.forEach {
|
||||
logger.i(TAG, "$description: cancelling legacy work ${it.id}")
|
||||
workManager.cancelWorkById(it.id)
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
jobManager.scheduleContentObserverJob()
|
||||
logger.i(TAG, "$description: enabled")
|
||||
} else {
|
||||
logger.i(TAG, "$description: disabled")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Contacts backup job has been migrated to new job runner framework. Re-start contacts upload
|
||||
* for all users that have it enabled.
|
||||
*
|
||||
* Old job is removed from source code, so we need to restart it for each user using
|
||||
* new jobs API.
|
||||
*/
|
||||
private val migrateContactsBackupJob = object : Step(2, "Restart contacts backup job") {
|
||||
override fun run() {
|
||||
val users = userAccountManager.allUsers
|
||||
if (users.isEmpty()) {
|
||||
logger.i(TAG, "$description: no users to migrate")
|
||||
} else {
|
||||
users.forEach {
|
||||
val backupEnabled = arbitraryDataProvider.getBooleanValue(it.accountName,
|
||||
ContactsPreferenceActivity.PREFERENCE_CONTACTS_AUTOMATIC_BACKUP)
|
||||
if (backupEnabled) {
|
||||
jobManager.schedulePeriodicContactsBackup(it)
|
||||
}
|
||||
logger.i(TAG, "$description: user = ${it.accountName}, backup enabled = $backupEnabled")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List of migration steps. Those steps will be loaded and run by [MigrationsManager]
|
||||
*/
|
||||
val steps: List<Step> = listOf(
|
||||
migrateUserId,
|
||||
migrateContentObserverJob,
|
||||
migrateContactsBackupJob
|
||||
).sortedBy { it.id }.apply {
|
||||
val uniqueIds = associateBy { it.id }.size
|
||||
if (uniqueIds != size) {
|
||||
throw IllegalStateException("All migrations must have unique id")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* 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.migrations
|
||||
|
||||
import android.content.SharedPreferences
|
||||
import java.util.TreeSet
|
||||
|
||||
class MigrationsDb(private val migrationsDb: SharedPreferences) {
|
||||
|
||||
companion object {
|
||||
const val DB_KEY_LAST_MIGRATED_VERSION = "last_migrated_version"
|
||||
const val DB_KEY_APPLIED_MIGRATIONS = "applied_migrations"
|
||||
const val DB_KEY_FAILED = "failed"
|
||||
const val DB_KEY_FAILED_MIGRATION_ID = "failed_migration_id"
|
||||
const val DB_KEY_FAILED_MIGRATION_ERROR_MESSAGE = "failed_migration_error"
|
||||
|
||||
const val NO_LAST_MIGRATED_VERSION = -1
|
||||
const val NO_FAILED_MIGRATION_ID = -1
|
||||
}
|
||||
|
||||
fun getAppliedMigrations(): List<Int> {
|
||||
val appliedIdsStr: Set<String> = migrationsDb.getStringSet(DB_KEY_APPLIED_MIGRATIONS, null) ?: TreeSet()
|
||||
return appliedIdsStr.mapNotNull {
|
||||
try {
|
||||
it.toInt()
|
||||
} catch (_: NumberFormatException) {
|
||||
null
|
||||
}
|
||||
}.sorted()
|
||||
}
|
||||
|
||||
fun addAppliedMigration(vararg migrations: Int) {
|
||||
val oldApplied = migrationsDb.getStringSet(DB_KEY_APPLIED_MIGRATIONS, null) ?: TreeSet()
|
||||
val newApplied = TreeSet<String>().apply {
|
||||
addAll(oldApplied)
|
||||
addAll(migrations.map { it.toString() })
|
||||
}
|
||||
migrationsDb.edit().putStringSet(DB_KEY_APPLIED_MIGRATIONS, newApplied).apply()
|
||||
}
|
||||
|
||||
var lastMigratedVersion: Int
|
||||
set(value) {
|
||||
migrationsDb.edit().putInt(DB_KEY_LAST_MIGRATED_VERSION, value).apply()
|
||||
}
|
||||
get() {
|
||||
return migrationsDb.getInt(DB_KEY_LAST_MIGRATED_VERSION, NO_LAST_MIGRATED_VERSION)
|
||||
}
|
||||
|
||||
val isFailed: Boolean get() = migrationsDb.getBoolean(DB_KEY_FAILED, false)
|
||||
val failureReason: String get() = migrationsDb.getString(DB_KEY_FAILED_MIGRATION_ERROR_MESSAGE, "") ?: ""
|
||||
val failedMigrationId: Int get() = migrationsDb.getInt(DB_KEY_FAILED_MIGRATION_ID, NO_FAILED_MIGRATION_ID)
|
||||
|
||||
fun setFailed(id: Int, error: String) {
|
||||
migrationsDb
|
||||
.edit()
|
||||
.putBoolean(DB_KEY_FAILED, true)
|
||||
.putString(DB_KEY_FAILED_MIGRATION_ERROR_MESSAGE, error)
|
||||
.putInt(DB_KEY_FAILED_MIGRATION_ID, id)
|
||||
.apply()
|
||||
}
|
||||
|
||||
fun clearMigrations() {
|
||||
migrationsDb.edit()
|
||||
.putStringSet(DB_KEY_APPLIED_MIGRATIONS, emptySet())
|
||||
.putInt(DB_KEY_LAST_MIGRATED_VERSION, 0)
|
||||
.apply()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* 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.migrations
|
||||
|
||||
import androidx.annotation.MainThread
|
||||
import androidx.lifecycle.LiveData
|
||||
|
||||
/**
|
||||
* This component allows starting and monitoring of application state migrations.
|
||||
* Migrations are intended to upgrade any existing, persisted application state
|
||||
* after upgrade to new version, similarly to database migrations.
|
||||
*/
|
||||
interface MigrationsManager {
|
||||
|
||||
enum class Status {
|
||||
/**
|
||||
* Application migration was not evaluated yet. This is the default
|
||||
* state just after [android.app.Application] start
|
||||
*/
|
||||
UNKNOWN,
|
||||
|
||||
/**
|
||||
* All migrations applied successfully.
|
||||
*/
|
||||
APPLIED,
|
||||
|
||||
/**
|
||||
* Migration in progress.
|
||||
*/
|
||||
RUNNING,
|
||||
|
||||
/**
|
||||
* Migration failed. Application is in undefined state.
|
||||
*/
|
||||
FAILED
|
||||
}
|
||||
|
||||
/**
|
||||
* Listenable migration progress.
|
||||
*/
|
||||
val status: LiveData<Status>
|
||||
|
||||
/**
|
||||
* Information about all pending and applied migrations
|
||||
*/
|
||||
val info: List<MigrationInfo>
|
||||
|
||||
/**
|
||||
* Starts application state migration. Migrations will be run in background thread.
|
||||
* Callers can use [status] to monitor migration progress.
|
||||
*
|
||||
* Although the migration process is run in background, status is updated
|
||||
* immediately and can be accessed immediately after start.
|
||||
*
|
||||
* @return Number of migration steps enqueued; 0 if no migrations were started.
|
||||
*/
|
||||
@Throws(MigrationError::class)
|
||||
@MainThread
|
||||
fun startMigration(): Int
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* 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.migrations
|
||||
|
||||
import androidx.annotation.MainThread
|
||||
import androidx.lifecycle.LiveData
|
||||
import androidx.lifecycle.MutableLiveData
|
||||
import com.nextcloud.client.appinfo.AppInfo
|
||||
import com.nextcloud.client.core.AsyncRunner
|
||||
import com.nextcloud.client.migrations.MigrationsManager.Status
|
||||
|
||||
internal class MigrationsManagerImpl(
|
||||
private val appInfo: AppInfo,
|
||||
private val migrationsDb: MigrationsDb,
|
||||
private val asyncRunner: AsyncRunner,
|
||||
private val migrations: Collection<Migrations.Step>
|
||||
) : MigrationsManager {
|
||||
|
||||
override val status: LiveData<Status> = MutableLiveData<Status>(Status.UNKNOWN)
|
||||
|
||||
override val info: List<MigrationInfo> get() {
|
||||
val applied = migrationsDb.getAppliedMigrations()
|
||||
return migrations.map {
|
||||
MigrationInfo(id = it.id, description = it.description, applied = applied.contains(it.id))
|
||||
}
|
||||
}
|
||||
|
||||
@Throws(MigrationError::class)
|
||||
@Suppress("ReturnCount")
|
||||
override fun startMigration(): Int {
|
||||
|
||||
if (migrationsDb.isFailed) {
|
||||
(status as MutableLiveData<Status>).value = Status.FAILED
|
||||
return 0
|
||||
}
|
||||
if (migrationsDb.lastMigratedVersion >= appInfo.versionCode) {
|
||||
(status as MutableLiveData<Status>).value = Status.APPLIED
|
||||
return 0
|
||||
}
|
||||
val applied = migrationsDb.getAppliedMigrations()
|
||||
val toApply = migrations.filter { !applied.contains(it.id) }
|
||||
if (toApply.isEmpty()) {
|
||||
onMigrationSuccess()
|
||||
return 0
|
||||
}
|
||||
(status as MutableLiveData<Status>).value = Status.RUNNING
|
||||
asyncRunner.post(
|
||||
task = { asyncApplyMigrations(toApply) },
|
||||
onResult = { onMigrationSuccess() },
|
||||
onError = { onMigrationFailed(it) }
|
||||
)
|
||||
return toApply.size
|
||||
}
|
||||
|
||||
/**
|
||||
* This method calls all pending migrations which can execute long-blocking code.
|
||||
* It should be run in a background thread.
|
||||
*/
|
||||
private fun asyncApplyMigrations(migrations: Collection<Migrations.Step>) {
|
||||
migrations.forEach {
|
||||
@Suppress("TooGenericExceptionCaught") // migration code is free to throw anything
|
||||
try {
|
||||
it.run()
|
||||
migrationsDb.addAppliedMigration(it.id)
|
||||
} catch (t: Throwable) {
|
||||
if (it.mandatory) {
|
||||
throw MigrationError(id = it.id, message = t.message ?: t.javaClass.simpleName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@MainThread
|
||||
private fun onMigrationFailed(error: Throwable) {
|
||||
val id = when (error) {
|
||||
is MigrationError -> error.id
|
||||
else -> -1
|
||||
}
|
||||
migrationsDb.setFailed(id, error.message ?: error.javaClass.simpleName)
|
||||
(status as MutableLiveData<Status>).value = Status.FAILED
|
||||
}
|
||||
|
||||
@MainThread
|
||||
private fun onMigrationSuccess() {
|
||||
migrationsDb.lastMigratedVersion = appInfo.versionCode
|
||||
(status as MutableLiveData<Status>).value = Status.APPLIED
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# Package com.nextcloud.client.migrations
|
||||
|
||||
This package provides utitilies to migrate application state
|
||||
during version upgrade.
|
||||
|
||||
Migrations are registered upon run so they can be run only once.
|
||||
@@ -43,6 +43,7 @@ import android.view.WindowManager;
|
||||
|
||||
import com.evernote.android.job.JobManager;
|
||||
import com.evernote.android.job.JobRequest;
|
||||
import com.nextcloud.client.account.User;
|
||||
import com.nextcloud.client.account.UserAccountManager;
|
||||
import com.nextcloud.client.appinfo.AppInfo;
|
||||
import com.nextcloud.client.core.Clock;
|
||||
@@ -53,6 +54,7 @@ import com.nextcloud.client.errorhandling.ExceptionHandler;
|
||||
import com.nextcloud.client.jobs.BackgroundJobManager;
|
||||
import com.nextcloud.client.logger.LegacyLoggerAdapter;
|
||||
import com.nextcloud.client.logger.Logger;
|
||||
import com.nextcloud.client.migrations.MigrationsManager;
|
||||
import com.nextcloud.client.network.ConnectivityService;
|
||||
import com.nextcloud.client.onboarding.OnboardingService;
|
||||
import com.nextcloud.client.preferences.AppPreferences;
|
||||
@@ -84,6 +86,7 @@ import com.owncloud.android.utils.ReceiversHelper;
|
||||
import com.owncloud.android.utils.SecurityUtils;
|
||||
|
||||
import org.conscrypt.Conscrypt;
|
||||
import org.greenrobot.eventbus.EventBus;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
@@ -92,6 +95,7 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@@ -166,6 +170,12 @@ public class MainApp extends MultiDexApplication implements HasAndroidInjector {
|
||||
@Inject
|
||||
Clock clock;
|
||||
|
||||
@Inject
|
||||
EventBus eventBus;
|
||||
|
||||
@Inject
|
||||
MigrationsManager migrationsManager;
|
||||
|
||||
private PassCodeManager passCodeManager;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
@@ -194,14 +204,6 @@ public class MainApp extends MultiDexApplication implements HasAndroidInjector {
|
||||
return powerManagementService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Temporary getter enabling intermediate refactoring.
|
||||
* TODO: remove when FileSyncHelper is refactored/removed
|
||||
*/
|
||||
public BackgroundJobManager getBackgroundJobManager() {
|
||||
return backgroundJobManager;
|
||||
}
|
||||
|
||||
private String getAppProcessName() {
|
||||
String processName = "";
|
||||
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
|
||||
@@ -257,14 +259,8 @@ public class MainApp extends MultiDexApplication implements HasAndroidInjector {
|
||||
|
||||
registerActivityLifecycleCallbacks(new ActivityInjector());
|
||||
|
||||
Thread t = new Thread(() -> {
|
||||
// best place, before any access to AccountManager or database
|
||||
if (!preferences.isUserIdMigrated()) {
|
||||
final boolean migrated = accountManager.migrateUserId();
|
||||
preferences.setMigratedUserId(migrated);
|
||||
}
|
||||
});
|
||||
t.start();
|
||||
int startedMigrationsCount = migrationsManager.startMigration();
|
||||
logger.i(TAG, String.format(Locale.US, "Started %d migrations", startedMigrationsCount));
|
||||
|
||||
JobManager.create(this).addJobCreator(
|
||||
new NCJobCreator(
|
||||
@@ -274,7 +270,9 @@ public class MainApp extends MultiDexApplication implements HasAndroidInjector {
|
||||
uploadsStorageManager,
|
||||
connectivityService,
|
||||
powerManagementService,
|
||||
clock
|
||||
clock,
|
||||
eventBus,
|
||||
backgroundJobManager
|
||||
)
|
||||
);
|
||||
|
||||
@@ -312,7 +310,7 @@ public class MainApp extends MultiDexApplication implements HasAndroidInjector {
|
||||
powerManagementService,
|
||||
backgroundJobManager,
|
||||
clock);
|
||||
initContactsBackup(accountManager);
|
||||
initContactsBackup(accountManager, backgroundJobManager);
|
||||
notificationChannels();
|
||||
|
||||
|
||||
@@ -382,13 +380,13 @@ public class MainApp extends MultiDexApplication implements HasAndroidInjector {
|
||||
securityKeyManager.init(this, config);
|
||||
}
|
||||
|
||||
public static void initContactsBackup(UserAccountManager accountManager) {
|
||||
public static void initContactsBackup(UserAccountManager accountManager, BackgroundJobManager backgroundJobManager) {
|
||||
ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(mContext.getContentResolver());
|
||||
Account[] accounts = accountManager.getAccounts();
|
||||
List<User> users = accountManager.getAllUsers();
|
||||
for (User user : users) {
|
||||
if (arbitraryDataProvider.getBooleanValue(user.toPlatformAccount(), PREFERENCE_CONTACTS_AUTOMATIC_BACKUP)) {
|
||||
backgroundJobManager.schedulePeriodicContactsBackup(user);
|
||||
|
||||
for (Account account : accounts) {
|
||||
if (arbitraryDataProvider.getBooleanValue(account, PREFERENCE_CONTACTS_AUTOMATIC_BACKUP)) {
|
||||
ContactsPreferenceActivity.startContactBackupJob(account);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -768,7 +766,7 @@ public class MainApp extends MultiDexApplication implements HasAndroidInjector {
|
||||
|
||||
for (SyncedFolder syncedFolder : syncedFolderProvider.getSyncedFolders()) {
|
||||
if (syncedFolder.isEnabled()) {
|
||||
FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder);
|
||||
FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder, true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,25 +19,9 @@
|
||||
* 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.datamodel;
|
||||
|
||||
import lombok.Getter;
|
||||
package com.owncloud.android.datamodel
|
||||
|
||||
/**
|
||||
* Data set for {@link ArbitraryDataProvider}
|
||||
* Data set for [ArbitraryDataProvider]
|
||||
*/
|
||||
@Getter
|
||||
class ArbitraryDataSet {
|
||||
private int id;
|
||||
private String cloudId;
|
||||
private String key;
|
||||
private String value;
|
||||
|
||||
ArbitraryDataSet(int id, String cloudId, String key, String value) {
|
||||
this.id = id;
|
||||
this.cloudId = cloudId;
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
internal class ArbitraryDataSet(val id: Int, val cloudId: String, val key: String, val value: String)
|
||||
@@ -24,16 +24,9 @@ package com.owncloud.android.datamodel;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* Decrypted class representation of metadata json of folder metadata.
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public class DecryptedFolderMetadata {
|
||||
private Metadata metadata;
|
||||
private Map<String, DecryptedFile> files;
|
||||
@@ -43,8 +36,27 @@ public class DecryptedFolderMetadata {
|
||||
this.files = new HashMap<>();
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public DecryptedFolderMetadata(Metadata metadata, Map<String, DecryptedFile> files) {
|
||||
this.metadata = metadata;
|
||||
this.files = files;
|
||||
}
|
||||
|
||||
public Metadata getMetadata() {
|
||||
return this.metadata;
|
||||
}
|
||||
|
||||
public Map<String, DecryptedFile> getFiles() {
|
||||
return this.files;
|
||||
}
|
||||
|
||||
public void setMetadata(Metadata metadata) {
|
||||
this.metadata = metadata;
|
||||
}
|
||||
|
||||
public void setFiles(Map<String, DecryptedFile> files) {
|
||||
this.files = files;
|
||||
}
|
||||
|
||||
public static class Metadata {
|
||||
private Map<Integer, String> metadataKeys; // each keys is encrypted on its own, decrypt on use
|
||||
private Sharing sharing;
|
||||
@@ -54,36 +66,140 @@ public class DecryptedFolderMetadata {
|
||||
public String toString() {
|
||||
return String.valueOf(version);
|
||||
}
|
||||
|
||||
public Map<Integer, String> getMetadataKeys() {
|
||||
return this.metadataKeys;
|
||||
}
|
||||
|
||||
public Sharing getSharing() {
|
||||
return this.sharing;
|
||||
}
|
||||
|
||||
public int getVersion() {
|
||||
return this.version;
|
||||
}
|
||||
|
||||
public void setMetadataKeys(Map<Integer, String> metadataKeys) {
|
||||
this.metadataKeys = metadataKeys;
|
||||
}
|
||||
|
||||
public void setSharing(Sharing sharing) {
|
||||
this.sharing = sharing;
|
||||
}
|
||||
|
||||
public void setVersion(int version) {
|
||||
this.version = version;
|
||||
}
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Encrypted {
|
||||
private Map<Integer, String> metadataKeys;
|
||||
|
||||
public Map<Integer, String> getMetadataKeys() {
|
||||
return this.metadataKeys;
|
||||
}
|
||||
|
||||
public void setMetadataKeys(Map<Integer, String> metadataKeys) {
|
||||
this.metadataKeys = metadataKeys;
|
||||
}
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Sharing {
|
||||
private Map<String, String> recipient;
|
||||
private String signature;
|
||||
|
||||
public Map<String, String> getRecipient() {
|
||||
return this.recipient;
|
||||
}
|
||||
|
||||
public String getSignature() {
|
||||
return this.signature;
|
||||
}
|
||||
|
||||
public void setRecipient(Map<String, String> recipient) {
|
||||
this.recipient = recipient;
|
||||
}
|
||||
|
||||
public void setSignature(String signature) {
|
||||
this.signature = signature;
|
||||
}
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class DecryptedFile {
|
||||
private Data encrypted;
|
||||
private String initializationVector;
|
||||
private String authenticationTag;
|
||||
private int metadataKey;
|
||||
|
||||
public Data getEncrypted() {
|
||||
return this.encrypted;
|
||||
}
|
||||
|
||||
public String getInitializationVector() {
|
||||
return this.initializationVector;
|
||||
}
|
||||
|
||||
public String getAuthenticationTag() {
|
||||
return this.authenticationTag;
|
||||
}
|
||||
|
||||
public int getMetadataKey() {
|
||||
return this.metadataKey;
|
||||
}
|
||||
|
||||
public void setEncrypted(Data encrypted) {
|
||||
this.encrypted = encrypted;
|
||||
}
|
||||
|
||||
public void setInitializationVector(String initializationVector) {
|
||||
this.initializationVector = initializationVector;
|
||||
}
|
||||
|
||||
public void setAuthenticationTag(String authenticationTag) {
|
||||
this.authenticationTag = authenticationTag;
|
||||
}
|
||||
|
||||
public void setMetadataKey(int metadataKey) {
|
||||
this.metadataKey = metadataKey;
|
||||
}
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Data {
|
||||
private String key;
|
||||
private String filename;
|
||||
private String mimetype;
|
||||
private int version;
|
||||
|
||||
public String getKey() {
|
||||
return this.key;
|
||||
}
|
||||
|
||||
public String getFilename() {
|
||||
return this.filename;
|
||||
}
|
||||
|
||||
public String getMimetype() {
|
||||
return this.mimetype;
|
||||
}
|
||||
|
||||
public int getVersion() {
|
||||
return this.version;
|
||||
}
|
||||
|
||||
public void setKey(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
public void setFilename(String filename) {
|
||||
this.filename = filename;
|
||||
}
|
||||
|
||||
public void setMimetype(String mimetype) {
|
||||
this.mimetype = mimetype;
|
||||
}
|
||||
|
||||
public void setVersion(int version) {
|
||||
this.version = version;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,16 +24,7 @@ import com.google.gson.annotations.SerializedName;
|
||||
|
||||
import org.parceler.Parcel;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Parcel
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
/*
|
||||
* Push data from server, https://github.com/nextcloud/notifications/blob/master/docs/push-v2.md#encrypted-subject-data
|
||||
*/
|
||||
@@ -46,4 +37,73 @@ public class DecryptedPushMessage {
|
||||
public boolean delete;
|
||||
@SerializedName("delete-all")
|
||||
public boolean deleteAll;
|
||||
|
||||
public DecryptedPushMessage(String app, String type, String subject, String id, int nid, boolean delete, boolean deleteAll) {
|
||||
this.app = app;
|
||||
this.type = type;
|
||||
this.subject = subject;
|
||||
this.id = id;
|
||||
this.nid = nid;
|
||||
this.delete = delete;
|
||||
this.deleteAll = deleteAll;
|
||||
}
|
||||
|
||||
public DecryptedPushMessage() {
|
||||
}
|
||||
|
||||
public String getApp() {
|
||||
return this.app;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
public String getSubject() {
|
||||
return this.subject;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public int getNid() {
|
||||
return this.nid;
|
||||
}
|
||||
|
||||
public boolean isDelete() {
|
||||
return this.delete;
|
||||
}
|
||||
|
||||
public boolean isDeleteAll() {
|
||||
return this.deleteAll;
|
||||
}
|
||||
|
||||
public void setApp(String app) {
|
||||
this.app = app;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public void setSubject(String subject) {
|
||||
this.subject = subject;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setNid(int nid) {
|
||||
this.nid = nid;
|
||||
}
|
||||
|
||||
public void setDelete(boolean delete) {
|
||||
this.delete = delete;
|
||||
}
|
||||
|
||||
public void setDeleteAll(boolean deleteAll) {
|
||||
this.deleteAll = deleteAll;
|
||||
}
|
||||
}
|
||||
@@ -23,26 +23,70 @@ package com.owncloud.android.datamodel;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* Encrypted class representation of metadata json of folder metadata
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public class EncryptedFolderMetadata {
|
||||
private DecryptedFolderMetadata.Metadata metadata;
|
||||
private Map<String, EncryptedFile> files;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public EncryptedFolderMetadata(DecryptedFolderMetadata.Metadata metadata, Map<String, EncryptedFile> files) {
|
||||
this.metadata = metadata;
|
||||
this.files = files;
|
||||
}
|
||||
|
||||
public DecryptedFolderMetadata.Metadata getMetadata() {
|
||||
return this.metadata;
|
||||
}
|
||||
|
||||
public Map<String, EncryptedFile> getFiles() {
|
||||
return this.files;
|
||||
}
|
||||
|
||||
public void setMetadata(DecryptedFolderMetadata.Metadata metadata) {
|
||||
this.metadata = metadata;
|
||||
}
|
||||
|
||||
public void setFiles(Map<String, EncryptedFile> files) {
|
||||
this.files = files;
|
||||
}
|
||||
|
||||
public static class EncryptedFile {
|
||||
private String encrypted;
|
||||
private String initializationVector;
|
||||
private String authenticationTag;
|
||||
private int metadataKey;
|
||||
|
||||
public String getEncrypted() {
|
||||
return this.encrypted;
|
||||
}
|
||||
|
||||
public String getInitializationVector() {
|
||||
return this.initializationVector;
|
||||
}
|
||||
|
||||
public String getAuthenticationTag() {
|
||||
return this.authenticationTag;
|
||||
}
|
||||
|
||||
public int getMetadataKey() {
|
||||
return this.metadataKey;
|
||||
}
|
||||
|
||||
public void setEncrypted(String encrypted) {
|
||||
this.encrypted = encrypted;
|
||||
}
|
||||
|
||||
public void setInitializationVector(String initializationVector) {
|
||||
this.initializationVector = initializationVector;
|
||||
}
|
||||
|
||||
public void setAuthenticationTag(String authenticationTag) {
|
||||
this.authenticationTag = authenticationTag;
|
||||
}
|
||||
|
||||
public void setMetadataKey(int metadataKey) {
|
||||
this.metadataKey = metadataKey;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -67,11 +67,8 @@ import java.util.Set;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
|
||||
@Getter
|
||||
public class FileDataStorageManager {
|
||||
private static final String TAG = FileDataStorageManager.class.getSimpleName();
|
||||
|
||||
@@ -85,7 +82,7 @@ public class FileDataStorageManager {
|
||||
|
||||
private ContentResolver contentResolver;
|
||||
private ContentProviderClient contentProviderClient;
|
||||
@Setter private Account account;
|
||||
private Account account;
|
||||
|
||||
public FileDataStorageManager(Account account, ContentResolver cr) {
|
||||
contentProviderClient = null;
|
||||
@@ -1695,15 +1692,20 @@ public class FileDataStorageManager {
|
||||
+ ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? OR "
|
||||
+ ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? OR "
|
||||
+ ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? OR "
|
||||
+ ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? OR "
|
||||
+ ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? ) ";
|
||||
String[] whereArgs = new String[]{filePath, accountName,
|
||||
Integer.toString(ShareType.USER.getValue()),
|
||||
Integer.toString(ShareType.GROUP.getValue()),
|
||||
Integer.toString(ShareType.EMAIL.getValue()),
|
||||
Integer.toString(ShareType.FEDERATED.getValue()),
|
||||
Integer.toString(ShareType.ROOM.getValue())};
|
||||
String[] whereArgs = new String[]{
|
||||
filePath,
|
||||
accountName,
|
||||
Integer.toString(ShareType.USER.getValue()),
|
||||
Integer.toString(ShareType.GROUP.getValue()),
|
||||
Integer.toString(ShareType.EMAIL.getValue()),
|
||||
Integer.toString(ShareType.FEDERATED.getValue()),
|
||||
Integer.toString(ShareType.ROOM.getValue()),
|
||||
Integer.toString(ShareType.CIRCLE.getValue())
|
||||
};
|
||||
|
||||
Cursor cursor = null;
|
||||
Cursor cursor;
|
||||
if (getContentResolver() != null) {
|
||||
cursor = getContentResolver().query(ProviderTableMeta.CONTENT_URI_SHARE, null, where, whereArgs, null);
|
||||
} else {
|
||||
@@ -2294,4 +2296,20 @@ public class FileDataStorageManager {
|
||||
private CapabilityBooleanType getBoolean(Cursor cursor, String columnName) {
|
||||
return CapabilityBooleanType.fromValue(cursor.getInt(cursor.getColumnIndex(columnName)));
|
||||
}
|
||||
|
||||
public ContentResolver getContentResolver() {
|
||||
return this.contentResolver;
|
||||
}
|
||||
|
||||
public ContentProviderClient getContentProviderClient() {
|
||||
return this.contentProviderClient;
|
||||
}
|
||||
|
||||
public Account getAccount() {
|
||||
return this.account;
|
||||
}
|
||||
|
||||
public void setAccount(Account account) {
|
||||
this.account = account;
|
||||
}
|
||||
}
|
||||
@@ -23,18 +23,10 @@
|
||||
package com.owncloud.android.datamodel;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* Model for filesystem data from the database.
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class FileSystemDataSet {
|
||||
private int id;
|
||||
private String localPath;
|
||||
@@ -44,4 +36,83 @@ public class FileSystemDataSet {
|
||||
private long foundAt;
|
||||
private long syncedFolderId;
|
||||
@Nullable private String crc32;
|
||||
|
||||
public FileSystemDataSet(int id, String localPath, long modifiedAt, boolean folder, boolean sentForUpload, long foundAt, long syncedFolderId, String crc32) {
|
||||
this.id = id;
|
||||
this.localPath = localPath;
|
||||
this.modifiedAt = modifiedAt;
|
||||
this.folder = folder;
|
||||
this.sentForUpload = sentForUpload;
|
||||
this.foundAt = foundAt;
|
||||
this.syncedFolderId = syncedFolderId;
|
||||
this.crc32 = crc32;
|
||||
}
|
||||
|
||||
public FileSystemDataSet() {
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public String getLocalPath() {
|
||||
return this.localPath;
|
||||
}
|
||||
|
||||
public long getModifiedAt() {
|
||||
return this.modifiedAt;
|
||||
}
|
||||
|
||||
public boolean isFolder() {
|
||||
return this.folder;
|
||||
}
|
||||
|
||||
public boolean isSentForUpload() {
|
||||
return this.sentForUpload;
|
||||
}
|
||||
|
||||
public long getFoundAt() {
|
||||
return this.foundAt;
|
||||
}
|
||||
|
||||
public long getSyncedFolderId() {
|
||||
return this.syncedFolderId;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getCrc32() {
|
||||
return this.crc32;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setLocalPath(String localPath) {
|
||||
this.localPath = localPath;
|
||||
}
|
||||
|
||||
public void setModifiedAt(long modifiedAt) {
|
||||
this.modifiedAt = modifiedAt;
|
||||
}
|
||||
|
||||
public void setFolder(boolean folder) {
|
||||
this.folder = folder;
|
||||
}
|
||||
|
||||
public void setSentForUpload(boolean sentForUpload) {
|
||||
this.sentForUpload = sentForUpload;
|
||||
}
|
||||
|
||||
public void setFoundAt(long foundAt) {
|
||||
this.foundAt = foundAt;
|
||||
}
|
||||
|
||||
public void setSyncedFolderId(long syncedFolderId) {
|
||||
this.syncedFolderId = syncedFolderId;
|
||||
}
|
||||
|
||||
public void setCrc32(@Nullable String crc32) {
|
||||
this.crc32 = crc32;
|
||||
}
|
||||
}
|
||||