Compare commits

...
Author SHA1 Message Date
Tobias Kaminsky a1253ce117 daily dev 20180918 2018-09-18 00:32:01 +02:00
Andy Scherzinger d9ce5b0228 Merge pull request #3044 from nextcloud/handlePermissions
Correct handle write protected folders
2018-09-17 08:12:59 +02:00
Nextcloud bot df742e0712 [tx-robot] updated from transifex 2018-09-17 00:50:37 +00:00
Nextcloud bot 3d3980a67b [tx-robot] updated from transifex 2018-09-16 00:49:33 +00:00
Nextcloud bot 785433108e [tx-robot] updated from transifex 2018-09-15 00:48:36 +00:00
Tobias Kaminsky 1f8854769b daily dev 20180915 2018-09-15 00:32:34 +02:00
tobiasKaminsky 4da88c2acb correct handle write protected folders
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-14 13:59:54 +02:00
Tobias Kaminsky c99cea497d Merge pull request #3031 from NilsGriebner/upload_filepicker_footer
Fix upload filepicker footer view
2018-09-14 11:40:25 +02:00
Nextcloud bot 521b1cda01 [tx-robot] updated from transifex 2018-09-14 07:47:37 +00:00
Andy Scherzinger aa09934df1 fix string 2018-09-14 09:41:09 +02:00
Tobias Kaminsky 82ea0bcd68 Merge pull request #3027 from nextcloud/sso
add own sso token manager with custom dialog
2018-09-14 08:34:56 +02:00
Nextcloud bot 903b0802a0 [tx-robot] updated from transifex 2018-09-14 06:28:43 +00:00
Nextcloud bot 0e7e85fabf [tx-robot] updated from transifex 2018-09-14 00:50:08 +00:00
Tobias Kaminsky 23a1a1f3b6 daily dev 20180914 2018-09-14 00:32:13 +02:00
AndyScherzinger e46aacc9c8 fix codacy 2018-09-13 19:06:31 +02:00
AndyScherzinger 7a7c1100c3 polish SSO dialog 2018-09-13 18:49:12 +02:00
AndyScherzinger e164da3beb add license header and line break to xml file 2018-09-13 18:18:02 +02:00
AndyScherzinger e04b94b2f6 improve permission screen design 2018-09-13 18:18:01 +02:00
David Luhmer fddcbbbecd fix issues reported by codacy 2018-09-13 18:18:01 +02:00
David Luhmer d0f474e611 fix issues reported by codacy 2018-09-13 18:18:00 +02:00
David Luhmer 086492b6d4 add own sso token manager with custom dialog 2018-09-13 18:17:59 +02:00
Andy Scherzinger 5ac1af47c1 Merge pull request #3037 from nextcloud/switchAccount
Fix account switching: After adding an account, the app restart and uses the new account
2018-09-13 12:51:36 +02:00
tobiasKaminsky 0c86ed9f77 fix account switching: now after adding an account, the app restart and uses the new account
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-13 11:28:05 +02:00
Andy Scherzinger ff6cf2df4a Merge pull request #3033 from nextcloud/quickfixForUnknownSharingType
Quickfix for unknown SharingTypes
2018-09-13 10:16:16 +02:00
tobiasKaminsky 9f2b8a73c8 quickfix for unknown SharingTypes
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-13 09:04:41 +02:00
Andy Scherzinger c4bbb792dc Merge pull request #3032 from nextcloud/dependabot/gradle/jacocoVersion
Bump jacocoVersion from 0.7.4.201502262128 to 0.8.2
2018-09-13 06:32:54 +02:00
dependabot[bot] ba84def527 Bump jacocoVersion from 0.7.4.201502262128 to 0.8.2
Bumps `jacocoVersion` from 0.7.4.201502262128 to 0.8.2.

Updates `org.jacoco.ant` from 0.7.4.201502262128 to 0.8.2
- [Release notes](https://github.com/jacoco/jacoco/releases)
- [Commits](https://github.com/jacoco/jacoco/commits/v0.8.2)

Updates `org.jacoco.agent` from 0.7.4.201502262128 to 0.8.2
- [Release notes](https://github.com/jacoco/jacoco/releases)
- [Commits](https://github.com/jacoco/jacoco/commits/v0.8.2)

Updates `org.jacoco.core` from 0.7.4.201502262128 to 0.8.2
- [Release notes](https://github.com/jacoco/jacoco/releases)
- [Commits](https://github.com/jacoco/jacoco/commits/v0.8.2)

Updates `org.jacoco.report` from 0.7.4.201502262128 to 0.8.2
- [Release notes](https://github.com/jacoco/jacoco/releases)
- [Commits](https://github.com/jacoco/jacoco/commits/v0.8.2)

Signed-off-by: dependabot[bot] <[email protected]>
2018-09-13 01:14:21 +00:00
Nextcloud bot d7d2e1916f [tx-robot] updated from transifex 2018-09-13 00:49:04 +00:00
Tobias Kaminsky cc66d8857e daily dev 20180913 2018-09-13 00:33:41 +02:00
Nils Griebner b49e881d43 Fix upload filepicker footer view 2018-09-12 20:07:44 +02:00
Andy Scherzinger fc62aa42b8 Merge pull request #3010 from nextcloud/codacy
Codacy
2018-09-12 16:41:32 +02:00
Andy Scherzinger fc3a911a14 Merge pull request #3028 from nextcloud/deleteProguard
Delete proguard
2018-09-12 16:04:59 +02:00
AndyScherzinger ee4ec654de CR 2018-09-12 16:02:59 +02:00
Tobias Kaminsky 755425cf0c Delete proguard
As discussed in https://github.com/nextcloud/android-library/issues/160 proguard.cfg is not correctly working.
As we do not use it, this should be removed.
2018-09-12 14:51:23 +02:00
AndyScherzinger c839a5b83e codacy: avoid using Literals in Conditional Statements 2018-09-12 13:53:21 +02:00
AndyScherzinger 112450418a organize imports 2018-09-12 13:53:20 +02:00
AndyScherzinger f6f0165caf explicitly cast var-arg parameter (null) to String[] to get rid of compiler warning 2018-09-12 13:53:20 +02:00
AndyScherzinger 0fb3dedef1 fix all experimental warnings found by findbugs (missing stream closing) 2018-09-12 13:53:19 +02:00
AndyScherzinger 333dfcb1ed codacy: avoid using implementation types like 'HashMap'; use the interface instead 2018-09-12 13:53:18 +02:00
AndyScherzinger f81415dbab make all utils methods static 2018-09-12 13:53:18 +02:00
AndyScherzinger d5008116db codacy: avoid using Literals in Conditional Statements 2018-09-12 13:53:17 +02:00
AndyScherzinger 994d73f529 make all utils methods static 2018-09-12 13:53:17 +02:00
AndyScherzinger 65df2e82b3 codacy: utils classes are to be final with private constructor 2018-09-12 13:53:16 +02:00
AndyScherzinger ce4ce8db41 fix exceptions in method signature 2018-09-12 13:53:16 +02:00
AndyScherzinger 0f7fe6fd1c codacy: make utilities classes final with private constructor 2018-09-12 13:53:15 +02:00
AndyScherzinger 4724ab3329 codacy: combine nested if statements 2018-09-12 13:53:14 +02:00
AndyScherzinger b40b12e0eb codacy: replace with local variable 2018-09-12 13:53:14 +02:00
AndyScherzinger 5195badfd1 use correct exception 2018-09-12 13:53:13 +02:00
AndyScherzinger fb4b9a932f shorten if statement 2018-09-12 13:53:13 +02:00
AndyScherzinger 69399c394f codacy: position literals first in String comparisons for EqualsIgnoreCase 2018-09-12 13:53:12 +02:00
AndyScherzinger 0e93f00277 codacy: a class which only has private constructors should be final 2018-09-12 13:53:12 +02:00
AndyScherzinger 5f10a9301b codacy: This statement should have braces 2018-09-12 13:53:09 +02:00
Andy Scherzinger 916ef99313 Merge pull request #3025 from nextcloud/whatsNewOnWhite
Tint drawable according to login color
2018-09-12 13:13:37 +02:00
Tobias Kaminsky 00a045864d Merge pull request #3013 from nextcloud/storeMnemonicAsTyped
Store mnemonic as typed in
2018-09-12 10:51:41 +02:00
tobiasKaminsky 7ffc8660bb tint drawable according to login color (e.g. black on white background, white on blue background)
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-12 09:55:06 +02:00
Tobias Kaminsky 0c371b9603 Merge pull request #3008 from NilsGriebner/filepicker_grid
Use grid_item view for gridview in upload filepicker
2018-09-12 09:43:00 +02:00
Tobias Kaminsky dafe42d1c5 Merge pull request #3018 from nextcloud/fixAvatarFetching
Fix Avatar fetching for Nc14 server
2018-09-12 09:26:51 +02:00
Nextcloud bot cbf84e27bb [tx-robot] updated from transifex 2018-09-12 00:48:05 +00:00
Tobias Kaminsky f5ab3c9a53 daily dev 20180912 2018-09-12 00:32:51 +02:00
AndyScherzinger d8da2f8007 fixes #3015 - server sends a HTTP-201 (not 200) for a newly created avatar on Nc14
HTTP-201 (CREATED) is actually the correct HTTP code since the resource has just been created and is part of the body/reply
2018-09-11 17:28:27 +02:00
Andy Scherzinger da8d098fa1 Merge pull request #3009 from nextcloud/fixNPEonVersionChecking
Fix npe on version checking
2018-09-11 13:14:54 +02:00
tobiasKaminsky 9e4a9d7027 correct order
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-11 12:50:16 +02:00
tobiasKaminsky 21ebf1568e store mnemonic as typed in
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-11 11:15:59 +02:00
tobiasKaminsky 3ac8a8875b If first version is null, try to get it from capabilities
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-11 10:27:53 +02:00
Andy Scherzinger 63fe97e7e0 Merge pull request #3012 from nextcloud/dependabot/gradle/com.github.albfernandez-juniversalchardet-2.2.0
Bump juniversalchardet from 2.1.0 to 2.2.0
2018-09-11 06:36:45 +02:00
dependabot[bot] bca12ca282 Bump juniversalchardet from 2.1.0 to 2.2.0
Bumps [juniversalchardet](https://github.com/albfernandez/juniversalchardet) from 2.1.0 to 2.2.0.
- [Release notes](https://github.com/albfernandez/juniversalchardet/releases)
- [Commits](https://github.com/albfernandez/juniversalchardet/compare/v2.1.0...v2.2.0)

Signed-off-by: dependabot[bot] <[email protected]>
2018-09-11 01:14:49 +00:00
Tobias Kaminsky 637f117784 daily dev 20180911 2018-09-11 00:33:47 +02:00
Andy Scherzinger ca05284cda Merge pull request #3006 from nextcloud/mario-firebase-core-removal
Remove Firebase-core from the build
2018-09-10 16:18:41 +02:00
tobiasKaminsky 6ade530a26 fix npe on version checking
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-10 12:09:28 +02:00
Nils Griebner 7dc0604b8b Use grid_item view for gridview in upload filepicker 2018-09-10 11:12:29 +02:00
Tobias Kaminsky f996b3f671 Merge pull request #2989 from nextcloud/dependabot/gradle/org.jetbrains-annotations-16.0.2
Bump annotations from 15.0 to 16.0.2
2018-09-10 10:58:22 +02:00
Tobias Kaminsky 775671463d Merge pull request #2997 from nextcloud/dependabot/gradle/commons-io-commons-io-2.6
Bump commons-io from 2.5 to 2.6
2018-09-10 10:57:53 +02:00
Tobias Kaminsky 66b59ddf07 Merge pull request #2990 from nextcloud/dependabot/gradle/com.dicedmelon.gradle-jacoco-android-0.1.3
Bump jacoco-android from 0.1.2 to 0.1.3
2018-09-10 10:57:23 +02:00
Tobias Kaminsky 9e640c6837 Merge pull request #3007 from nextcloud/pullapproveDependencies
"dependencies" label do not need a pull approve
2018-09-10 10:56:39 +02:00
tobiasKaminsky 914a2b67ca "dependencies" label do not need a pull approve
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-10 10:43:51 +02:00
Mario Đanić 3168dc779a Remove Firebase-core from the build 2018-09-10 10:37:28 +02:00
Andy Scherzinger ef466a372c Merge pull request #3003 from nextcloud/dependabot/gradle/org.mockito-mockito-core-2.22.0
Bump mockito-core from 2.21.0 to 2.22.0
2018-09-10 08:12:03 +02:00
dependabot[bot] cd65368ead Bump mockito-core from 2.21.0 to 2.22.0
Bumps [mockito-core](https://github.com/mockito/mockito) from 2.21.0 to 2.22.0.
- [Release notes](https://github.com/mockito/mockito/releases)
- [Commits](https://github.com/mockito/mockito/compare/v2.21.0...v2.22.0)

Signed-off-by: dependabot[bot] <[email protected]>
2018-09-10 01:20:50 +00:00
Nextcloud bot 58e43e27ef [tx-robot] updated from transifex 2018-09-10 00:48:45 +00:00
Tobias Kaminsky c45adad67a daily dev 20180908 2018-09-08 00:33:05 +02:00
Andy Scherzinger 33087f7b63 Merge pull request #3000 from nextcloud/dependabot/gradle/org.parceler-parceler-1.1.11
Bump parceler from 1.1.9 to 1.1.11
2018-09-07 18:01:15 +02:00
dependabot[bot] 9aa38b5c3a Bump parceler from 1.1.9 to 1.1.11
Bumps [parceler](https://github.com/johncarl81/parceler) from 1.1.9 to 1.1.11.
- [Release notes](https://github.com/johncarl81/parceler/releases)
- [Changelog](https://github.com/johncarl81/parceler/blob/master/CHANGELOG.adoc)
- [Commits](https://github.com/johncarl81/parceler/compare/parceler-project-1.1.9...parceler-project-1.1.11)

Signed-off-by: dependabot[bot] <[email protected]>
2018-09-07 15:53:31 +00:00
Andy Scherzinger 479112204f Merge pull request #2996 from nextcloud/dependabot/gradle/org.parceler-parceler-api-1.1.11
Bump parceler-api from 1.1.9 to 1.1.11
2018-09-07 17:51:41 +02:00
dependabot[bot] 36c22d2001 Bump parceler-api from 1.1.9 to 1.1.11
Bumps [parceler-api](https://github.com/johncarl81/parceler) from 1.1.9 to 1.1.11.
- [Release notes](https://github.com/johncarl81/parceler/releases)
- [Changelog](https://github.com/johncarl81/parceler/blob/master/CHANGELOG.adoc)
- [Commits](https://github.com/johncarl81/parceler/compare/parceler-project-1.1.9...parceler-project-1.1.11)

Signed-off-by: dependabot[bot] <[email protected]>
2018-09-07 15:24:18 +00:00
Andy Scherzinger b8e1975824 Merge pull request #2998 from nextcloud/dependabot/gradle/com.github.chrisbanes-PhotoView-2.1.4
Bump PhotoView from 2.1.3 to 2.1.4
2018-09-07 17:22:18 +02:00
dependabot[bot] a0c038e9d6 Bump PhotoView from 2.1.3 to 2.1.4
Bumps PhotoView from 2.1.3 to 2.1.4.

Signed-off-by: dependabot[bot] <[email protected]>
2018-09-07 15:16:29 +00:00
Andy Scherzinger a7c8e5e1fb Merge pull request #2992 from nextcloud/dependabot/gradle/com.google.code.gson-gson-2.8.5
Bump gson from 2.8.2 to 2.8.5
2018-09-07 17:14:48 +02:00
dependabot[bot] 591bf4f422 Bump annotations from 15.0 to 16.0.2
Bumps [annotations](https://github.com/JetBrains/java-annotations) from 15.0 to 16.0.2.
- [Release notes](https://github.com/JetBrains/java-annotations/releases)
- [Commits](https://github.com/JetBrains/java-annotations/commits)

Signed-off-by: dependabot[bot] <[email protected]>
2018-09-07 15:08:55 +00:00
dependabot[bot] d5e70d6cf1 Bump gson from 2.8.2 to 2.8.5
Bumps [gson](https://github.com/google/gson) from 2.8.2 to 2.8.5.
- [Release notes](https://github.com/google/gson/releases)
- [Changelog](https://github.com/google/gson/blob/master/CHANGELOG.md)
- [Commits](https://github.com/google/gson/compare/gson-parent-2.8.2...gson-parent-2.8.5)

Signed-off-by: dependabot[bot] <[email protected]>
2018-09-07 15:08:15 +00:00
Andy Scherzinger 68ea0890e0 Merge pull request #2993 from nextcloud/dependabot/gradle/tools.fastlane-screengrab-1.2.0
Bump screengrab from 1.0.0 to 1.2.0
2018-09-07 17:06:12 +02:00
dependabot[bot] 8caa5769e6 Bump screengrab from 1.0.0 to 1.2.0
Bumps screengrab from 1.0.0 to 1.2.0.

Signed-off-by: dependabot[bot] <[email protected]>
2018-09-07 14:57:08 +00:00
dependabot[bot] 807537f8fd Bump commons-io from 2.5 to 2.6
Bumps commons-io from 2.5 to 2.6.

Signed-off-by: dependabot[bot] <[email protected]>
2018-09-07 14:55:59 +00:00
Andy Scherzinger 4a9d42b785 Merge pull request #2994 from nextcloud/dependabot/gradle/com.github.albfernandez-juniversalchardet-2.1.0
Bump juniversalchardet from v2.0.0 to 2.1.0
2018-09-07 16:53:51 +02:00
dependabot[bot] dbe451e5dd Bump juniversalchardet from v2.0.0 to 2.1.0
Bumps [juniversalchardet](https://github.com/albfernandez/juniversalchardet) from v2.0.0 to 2.1.0.
- [Release notes](https://github.com/albfernandez/juniversalchardet/releases)
- [Commits](https://github.com/albfernandez/juniversalchardet/compare/v2.0.0...v2.1.0)

Signed-off-by: dependabot[bot] <[email protected]>
2018-09-07 14:42:05 +00:00
Andy Scherzinger 26c56114ee Merge pull request #2980 from nextcloud/preventNPEonMediaStream
Prevent NPE on media stream
2018-09-07 16:36:33 +02:00
Andy Scherzinger b27beb7f8f Merge pull request #2982 from nextcloud/addProviderException
Add provider Exception
2018-09-07 16:35:42 +02:00
dependabot[bot] 46efc82c51 Bump jacoco-android from 0.1.2 to 0.1.3
Bumps jacoco-android from 0.1.2 to 0.1.3.

Signed-off-by: dependabot[bot] <[email protected]>
2018-09-07 14:29:27 +00:00
Andy Scherzinger 0f5febd1ae Merge pull request #2971 from nextcloud/bumpLibs
Library upgrades
2018-09-07 15:43:55 +02:00
tobiasKaminsky 2e5bdd5c4d add provider Exception
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-07 12:10:51 +02:00
Tobias Kaminsky 659649791c Merge pull request #2967 from nextcloud/removeGCM
Remove gcm as we use firebase messaging
2018-09-07 11:57:44 +02:00
tobiasKaminsky ba26aa741a prevent NPE on media stream
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-07 09:21:59 +02:00
AndyScherzinger 9a8b57c3a6 mockito-core 2.2.5->2.21.0 2018-09-07 09:12:06 +02:00
AndyScherzinger f7202bb13a fb-contrib 7.4.2->7.4.3 2018-09-07 09:12:05 +02:00
AndyScherzinger a403109464 findsecbugs-plugin 1.4.4->1.8.0 2018-09-07 09:12:05 +02:00
AndyScherzinger da4f2a2831 eventbus 3.0.0->3.1.1 2018-09-07 09:11:56 +02:00
Tobias Kaminsky 16afbeb3eb daily dev 20180907 2018-09-07 00:32:22 +02:00
Andy Scherzinger 8b0a4ca09c Merge pull request #2974 from nextcloud/fixExitMode
Nullable check on exit mode
2018-09-06 18:10:16 +02:00
Andy Scherzinger d8ba6f3c3a Merge pull request #2916 from nextcloud/codacy
Further codacy fixes
2018-09-06 18:09:01 +02:00
AndyScherzinger 1ccccb1ffe codacy: All methods are static. Consider using a utility class instead. 2018-09-06 17:58:47 +02:00
AndyScherzinger a0698feb96 fix var-arg call with null value 2018-09-06 17:58:47 +02:00
AndyScherzinger c1ee0fbbb0 use Exception like done on master before 2018-09-06 17:58:46 +02:00
AndyScherzinger 77af543b48 codacy: using varargs for methods or constructors which take an array the last parameter 2018-09-06 17:58:46 +02:00
AndyScherzinger ec6b1aa37d refactor delete method to reduce method complexity 2018-09-06 17:58:45 +02:00
AndyScherzinger ae256ad13a extract sync into separate method to reduce complexity 2018-09-06 17:58:45 +02:00
AndyScherzinger 67e1cf39e9 codacy: replace literals with constants 2018-09-06 17:58:44 +02:00
AndyScherzinger 98ebd9b8c8 codacy: using varargs for methods and constructors which take an array the last parameter 2018-09-06 17:58:44 +02:00
AndyScherzinger dfca74b1e8 codacy_ replace literals with constants 2018-09-06 17:58:43 +02:00
AndyScherzinger 63f2d407a4 codacy: fix newly created issues 2018-09-06 17:58:43 +02:00
AndyScherzinger df18d6eccc codacy: avoid using redundant field initializer 2018-09-06 17:58:42 +02:00
AndyScherzinger eafa49c822 codacy: avoid declaring a variable if it is unreferenced before a possible exit point. 2018-09-06 17:58:41 +02:00
AndyScherzinger 54c36092c2 codacy: don't create exact same object several times in loop 2018-09-06 17:58:41 +02:00
AndyScherzinger 10eb9d3920 codacy: remove useless parentheses 2018-09-06 17:58:40 +02:00
AndyScherzinger 0275b81c7b codacy: don't assign null 2018-09-06 17:58:40 +02:00
AndyScherzinger 4170370f63 codacy: don't create same object in a loop 2018-09-06 17:58:31 +02:00
tobiasKaminsky 06039a9e01 nullable check
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-06 11:28:32 +02:00
Tobias Kaminsky d5fba307d7 Merge pull request #2969 from nextcloud/doNotBlock
Do not block on check for dev version
2018-09-06 09:31:03 +02:00
tobiasKaminsky caaf13d678 do not block on check for dev version
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-05 16:02:45 +02:00
tobiasKaminsky 7f7ee24e2b remove gcm as we use firebase messaging
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-05 12:23:00 +02:00
Tobias Kaminsky 681be2bad5 Merge pull request #2965 from nextcloud/showWhatsNewOnlyOnUpgrade
Show whats new screen only on update
2018-09-05 09:25:01 +02:00
tobiasKaminsky 37c974f871 show whats new screen only on update
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-05 08:15:08 +02:00
Nextcloud bot bbd942c122 [tx-robot] updated from transifex 2018-09-05 00:46:59 +00:00
Tobias Kaminsky 25704d19a6 daily dev 20180905 2018-09-05 00:32:12 +02:00
Andy Scherzinger cc21e815d8 Merge pull request #2962 from nextcloud/340alpha1
3.4.0 alpha 1
2018-09-04 15:59:20 +02:00
Andy Scherzinger ce4a4d3652 3.4.0 alpha 1 2018-09-04 15:57:36 +02:00
Andy Scherzinger 051345a647 Merge pull request #2960 from nextcloud/addLinksToSummary
Add links to summary
2018-09-04 15:40:58 +02:00
Andy Scherzinger c83356cd40 Merge pull request #1116 from nextcloud/sso
Proof of concept for Single Sign On
2018-09-04 15:38:47 +02:00
nextcloud-android-bot 625810803f Drone: update Lint results to reflect reduced error/warning count [skip ci] 2018-09-04 13:12:38 +00:00
Tobias Kaminsky e329809802 Update lint-results.txt
update lint for #1116
2018-09-04 15:09:33 +02:00
Tobias Kaminsky 2a64998555 Merge branch 'master' into sso 2018-09-04 15:01:32 +02:00
tobiasKaminsky 79fdf11512 manually increase lint
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-04 15:00:40 +02:00
tobiasKaminsky b9998c74f0 add links to summary
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-04 14:19:18 +02:00
David Luhmer b26f5dc5d2 Merge pull request #2954 from nextcloud/sso_hashedToken
Use hashed/salted token
2018-09-04 14:14:24 +02:00
Andy Scherzinger 5ed69587e2 Merge pull request #2935 from nextcloud/improve-share-link-handling
Improve share link handling
2018-09-04 11:53:34 +02:00
AndyScherzinger e765cc8306 updated changelog 2018-09-04 11:43:08 +02:00
AndyScherzinger 6ae79355b5 show send to for sharing link via overflow menu in details screen 2018-09-04 11:38:35 +02:00
AndyScherzinger b9bc9bc84b further color fixes for snackbar action 2018-09-04 11:38:34 +02:00
AndyScherzinger 16836ad119 theme share link color in share link snackbar 2018-09-04 11:38:34 +02:00
Tilo Spannagel 4577084517 Improve share link handling
Signed-off-by: Tilo Spannagel <[email protected]>
2018-09-04 11:38:33 +02:00
tobiasKaminsky d969bc816c fix for codacy
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-04 11:37:38 +02:00
Andy Scherzinger 506acd0bbb Merge pull request #2944 from nextcloud/removeDivider
remove dividers
2018-09-04 11:29:49 +02:00
AndyScherzinger 056dc6ece1 fix user info layout alignments 2018-09-04 11:18:30 +02:00
AndyScherzinger 030d697d85 fix iem text alignment to be properly material design (72dp left column) 2018-09-04 11:18:29 +02:00
AndyScherzinger b607d8d176 remove divider in account list 2018-09-04 11:18:29 +02:00
AndyScherzinger a9027218f5 remove card view divider in user info 2018-09-04 11:18:28 +02:00
AndyScherzinger a09b983209 remove empty line 2018-09-04 11:18:28 +02:00
AndyScherzinger ea74122370 fix r-t-l alignment 2018-09-04 11:18:27 +02:00
AndyScherzinger 3da5db1646 remove dividers 2018-09-04 11:18:24 +02:00
Andy Scherzinger 8585208249 Merge pull request #2958 from nextcloud/fixTimSortAgain
Fix Timsort (again)
2018-09-04 11:03:37 +02:00
tobiasKaminsky 7358c3dd09 - change long to bigInteger
- add another test

Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-04 10:41:35 +02:00
Nextcloud bot e9d4a31f18 [tx-robot] updated from transifex 2018-09-04 00:45:45 +00:00
David Luhmer 322aee0454 remove permissions (fix https://github.com/nextcloud/Android-SingleSignOn/issues/27) 2018-09-03 22:01:16 +02:00
David Luhmer e3c708c87f add token verification method into inputstreambinder class (otherwise client app needs dependency on encryptionutils class) 2018-09-03 21:59:52 +02:00
David Luhmer 6a33b72654 increase serial version uid (otherwise connection will fail without error message) 2018-09-03 18:20:32 +02:00
Andy Scherzinger 537e896e57 Merge pull request #2940 from nextcloud/fixDeletedFilesView
make restore icon grey600
2018-09-03 18:03:45 +02:00
tobiasKaminsky c73ffe0e0c use hashed/salted token
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-03 17:22:42 +02:00
tobiasKaminsky 31c795faa5 change corresponding svgl
Signed-off-by: tobiasKaminsky <[email protected]>
2018-09-03 16:19:14 +02:00
AndyScherzinger cd5c360155 make restore icon grey600 2018-09-03 11:25:39 +02:00
David Luhmer 415afeb4e3 fix lint issues 2018-09-02 15:01:17 +02:00
David Luhmer f077a7ef33 use getter methods to access NextcloudRequest's variables / add support to disable follow-redirects 2018-09-02 14:51:14 +02:00
David Luhmer 6978fd35d1 fix lint issue "Do not add empty strings" 2018-08-30 18:24:46 +02:00
David Luhmer 65dde41927 add non-translatable flag to single sign on permission labels 2018-08-30 17:00:50 +02:00
David Luhmer c1d4d3d484 Merge branch 'master' into sso 2018-08-28 20:41:00 +02:00
David Luhmer e360ce456a update NextcloudRequest serialization id 2018-08-27 14:15:55 +02:00
David Luhmer 96e79e71fb add more exceptions / improve error handling 2018-08-27 14:15:33 +02:00
David Luhmer 614982a642 add calling package name if it's not set (when validating auth token) 2018-08-27 12:57:02 +02:00
David Luhmer 0234e8097f validate tokens in a way that timing attacks are not possible 2018-08-27 11:35:20 +02:00
David Luhmer 57e7eee9ff remove check for package name as it can be faked easily 2018-08-27 11:34:44 +02:00
David Luhmer 97b924d545 add custom exception for unsupported http method call 2018-08-27 11:34:07 +02:00
David Luhmer e84be102ff fix broken import of custom exceptions after refactoring 2018-08-27 11:19:52 +02:00
David Luhmer e387edc696 Add custom exceptions to constants class as well 2018-08-27 11:13:52 +02:00
David Luhmer dbef39c436 Use constants for username/token/url 2018-08-27 11:12:58 +02:00
David Luhmer 8133875769 create constants for custom exceptions 2018-08-27 11:05:56 +02:00
AndyScherzinger f97b7e4ea1 place license header at the top of the file 2018-08-27 10:50:10 +02:00
David Luhmer ba89fcba8b Fix code quality issue / reorder statements 2018-08-25 18:03:56 +02:00
David Luhmer 7948876041 Fix more code quality issues 2018-08-25 11:34:34 +02:00
David Luhmer 07a9e8c55f Fix code quality issues 2018-08-24 21:35:08 +02:00
David Luhmer cdf3ec2680 fix everything @AndyScherzinger proposed 2018-08-24 17:47:17 +02:00
David Luhmer 767ca18e5e add missing license headers 2018-08-24 17:45:31 +02:00
David Luhmer 89684052b8 fix refactoring of permissions (from owncloud to nextcloud) 2018-08-24 17:14:47 +02:00
David Luhmer e08cb4dec4 Merge branch 'master' into sso 2018-08-24 16:49:38 +02:00
tobiasKaminsky da79ca4afa package renaming
Signed-off-by: tobiasKaminsky <[email protected]>
2018-06-18 14:27:20 +02:00
David Luhmer 6eec0a3a1c add support to verify calling namespace 2018-06-15 15:28:38 +02:00
David Luhmer 12c86d721d remove duplicated files after merge 2018-06-15 15:19:07 +02:00
David Luhmer f41bd34407 Merge branch 'sso' of https://github.com/nextcloud/android into sso
# Conflicts:
#	src/main/java/com/owncloud/android/services/AccountManagerService.java
2018-06-15 14:41:55 +02:00
David Luhmer 2eece7aa33 Refactoring 2018-06-15 14:40:56 +02:00
tobiasKaminsky c2d18556c3 use token for verification, with SharedProvider as ArbitraryContentProvider does not work on service context
Signed-off-by: tobiasKaminsky <[email protected]>
2018-06-15 00:02:40 +02:00
AndyScherzinger b2d099c39f Fixes after rebase 2018-06-15 00:02:39 +02:00
tobiasKaminsky fb2bd16d4b - use userId instead of loginName
- use serverUrl from ocAccount

Signed-off-by: tobiasKaminsky <[email protected]>
2018-06-15 00:02:39 +02:00
David Luhmer 27970e77ed Code cleanup / add some todos/comments 2018-06-15 00:02:38 +02:00
David Luhmer 45cf8af64f Code cleanup / add check if auth token is correct 2018-06-15 00:02:38 +02:00
David Luhmer 0547a0974d Code cleanup / add basic exception handling 2018-06-15 00:02:37 +02:00
David Luhmer b810a59167 fix permission issues 2018-06-15 00:02:37 +02:00
tobiasKaminsky 9cd3b6cbae satisfy codacy 2018-06-15 00:02:36 +02:00
tobiasKaminsky 09dbb43d74 changes according to codacy 2018-06-15 00:02:36 +02:00
David Luhmer c102b9552a Implement sso prototype by @David-Developement 2018-06-15 00:02:35 +02:00
tobiasKaminsky 347c0edef2 use token for verification, with SharedProvider as ArbitraryContentProvider does not work on service context
Signed-off-by: tobiasKaminsky <[email protected]>
2018-06-12 14:30:03 +02:00
AndyScherzinger ebc50d44b6 Fixes after rebase 2018-06-12 11:40:46 +02:00
tobiasKaminsky 73e41885c6 - use userId instead of loginName
- use serverUrl from ocAccount

Signed-off-by: tobiasKaminsky <[email protected]>
2018-06-12 11:40:46 +02:00
David Luhmer b6593f783e Code cleanup / add some todos/comments 2018-06-12 11:40:45 +02:00
David Luhmer b7712e7580 Code cleanup / add check if auth token is correct 2018-06-12 11:40:45 +02:00
David Luhmer 294d23bfb6 Code cleanup / add basic exception handling 2018-06-12 11:40:44 +02:00
David Luhmer 0435448727 fix permission issues 2018-06-12 11:40:44 +02:00
tobiasKaminsky 68d8499049 satisfy codacy 2018-06-12 11:40:43 +02:00
tobiasKaminsky f52eb08606 changes according to codacy 2018-06-12 11:40:42 +02:00
David Luhmer bdfabd70e9 Implement sso prototype by @David-Developement 2018-06-12 11:40:42 +02:00
174 changed files with 2928 additions and 1169 deletions

No files matched your search

+4
View File
@@ -20,6 +20,10 @@ group_defaults:
enabled: false
reset_on_reopened:
enabled: true
conditions:
labels:
exclude:
- dependencies
groups:
code-review:
+9
View File
@@ -1,3 +1,12 @@
## 3.2.4 (Sept, 04, 2018)
fix push notification on gplay release
## 3.2.3 (Aug, 21, 2018)
- Fix crash on Android Android 4.x
## 3.2.2 (Aug, 20, 2018)
- New simple signup screen
## 3.2.1 (June, 11, 2018)
- Enhanced file detail/sharing screen for mail-shares
- Fix local sorting and file selection
+20 -18
View File
@@ -17,7 +17,7 @@ buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:3.1.4'
classpath 'org.codehaus.groovy:groovy-all:2.4.12'
classpath('com.dicedmelon.gradle:jacoco-android:0.1.2') {
classpath('com.dicedmelon.gradle:jacoco-android:0.1.3') {
exclude group: 'org.codehaus.groovy', module: 'groovy-all'
}
}
@@ -30,13 +30,14 @@ apply plugin: 'findbugs'
apply plugin: 'jacoco-android'
configurations.all {
exclude group: 'com.google.firebase', module: 'firebase-core'
// check for updates every build
resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}
ext {
supportLibraryVersion = '27.1.1'
jacocoVersion = "0.7.4.201502262128"
jacocoVersion = "0.8.2"
travisBuild = System.getenv("TRAVIS") == "true"
@@ -57,7 +58,7 @@ repositories {
// semantic versioning for version code
def versionMajor = 3
def versionMinor = 3
def versionMinor = 4
def versionPatch = 0
def versionBuild = 0 // 0-49=Alpha / 50-98=RC / 99=stable
@@ -129,8 +130,8 @@ android {
versionDev {
applicationId "com.nextcloud.android.beta"
dimension "default"
versionCode 20180903
versionName "20180903"
versionCode 20180918
versionName "20180918"
}
}
}
@@ -212,6 +213,7 @@ dependencies {
implementation 'com.android.support:multidex:1.0.3'
// implementation project('nextcloud-android-library')
genericImplementation "com.github.nextcloud:android-library:master-SNAPSHOT"
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
gplayImplementation "com.github.nextcloud:android-library:master-SNAPSHOT"
versionDevImplementation 'com.github.nextcloud:android-library:master-SNAPSHOT' // use always latest master
implementation "com.android.support:support-v4:${supportLibraryVersion}"
@@ -220,33 +222,33 @@ dependencies {
implementation "com.android.support:appcompat-v7:${supportLibraryVersion}"
implementation "com.android.support:cardview-v7:${supportLibraryVersion}"
implementation "com.android.support:exifinterface:${supportLibraryVersion}"
implementation 'com.github.albfernandez:juniversalchardet:v2.0.0'
implementation 'com.github.albfernandez:juniversalchardet:2.2.0'
implementation 'com.google.code.findbugs:annotations:2.0.1'
implementation 'commons-io:commons-io:2.5'
implementation 'commons-io:commons-io:2.6'
implementation 'com.github.evernote:android-job:v1.2.5'
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
implementation 'org.greenrobot:eventbus:3.0.0'
implementation 'org.greenrobot:eventbus:3.1.1'
implementation 'com.googlecode.ez-vcard:ez-vcard:0.10.4'
implementation 'org.lukhnos:nnio:0.2'
implementation 'com.madgag.spongycastle:pkix:1.54.0.0'
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.afollestad:sectioned-recyclerview:0.5.0'
implementation 'com.github.chrisbanes:PhotoView:2.1.3'
implementation 'com.github.chrisbanes:PhotoView:2.1.4'
implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.15'
implementation 'org.parceler:parceler-api:1.1.9'
annotationProcessor 'org.parceler:parceler:1.1.9'
implementation 'org.parceler:parceler-api:1.1.11'
annotationProcessor 'org.parceler:parceler:1.1.11'
implementation ('com.github.bumptech.glide:glide:3.7.0') {
exclude group: "com.android.support"
}
implementation 'com.caverock:androidsvg:1.3'
implementation "com.android.support:support-annotations:${supportLibraryVersion}"
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.google.code.gson:gson:2.8.5'
// dependencies for local unit tests
testImplementation 'junit:junit:4.12'
testImplementation 'org.mockito:mockito-core:2.2.5'
testImplementation 'org.mockito:mockito-core:2.22.0'
// dependencies for instrumented tests
// JUnit4 Rules
androidTestImplementation 'com.android.support.test:rules:1.0.2'
@@ -260,12 +262,12 @@ dependencies {
androidTestImplementation 'com.android.support.test.uiautomator:uiautomator-v18:2.1.3'
// fix conflict in dependencies; see http://g.co/androidstudio/app-test-app-conflict for details
//androidTestImplementation "com.android.support:support-annotations:${supportLibraryVersion}"
implementation 'org.jetbrains:annotations:15.0'
implementation 'org.jetbrains:annotations:16.0.2'
androidTestImplementation 'tools.fastlane:screengrab:1.0.0'
androidTestImplementation 'tools.fastlane:screengrab:1.2.0'
findbugsPlugins 'com.h3xstream.findsecbugs:findsecbugs-plugin:1.4.4'
findbugsPlugins 'com.mebigfatguy.fb-contrib:fb-contrib:7.4.2'
findbugsPlugins 'com.h3xstream.findsecbugs:findsecbugs-plugin:1.8.0'
findbugsPlugins 'com.mebigfatguy.fb-contrib:fb-contrib:7.4.3'
// jacocoAnt "org.jacoco:org.jacoco.ant:${jacocoVersion}"
// jacocoAgent "org.jacoco:org.jacoco.agent:${jacocoVersion}"
+2 -2
View File
@@ -1,4 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewbox="0 0 16 16" width="16" height="16">
<path
d="m9.025 1.08c-3.95 0-6.535 3.447-6.364 6.72h-2.161l3.904 3.92 4.08-3.874h-2.147c-0.237-1.7 1.163-3.114 2.689-3.092 1.595 0.024 2.8 1.23 2.8 2.734 0.09 1.594-1.63 3.428-3.966 2.53 0 1.23 0.003 2.545 0 3.765 4.19 0.83 7.64-2.51 7.64-6.25 0-3.563-2.92-6.453-6.475-6.453z"/>
<path style="fill:#757575"
d="m9.025 1.08c-3.95 0-6.535 3.447-6.364 6.72h-2.161l3.904 3.92 4.08-3.874h-2.147c-0.237-1.7 1.163-3.114 2.689-3.092 1.595 0.024 2.8 1.23 2.8 2.734 0.09 1.594-1.63 3.428-3.966 2.53 0 1.23 0.003 2.545 0 3.765 4.19 0.83 7.64-2.51 7.64-6.25 0-3.563-2.92-6.453-6.475-6.453z"/>
</svg>

Before

Width:  |  Height:  |  Size: 396 B

After

Width:  |  Height:  |  Size: 419 B

+1 -2
View File
@@ -1,4 +1,3 @@
dependencies {
implementation "com.google.firebase:firebase-messaging:17.1.0"
implementation "com.google.android.gms:play-services-gcm:15.0.1"
implementation "com.google.firebase:firebase-messaging:17.3.0"
}
-38
View File
@@ -1,38 +0,0 @@
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService
-keepclasseswithmembernames class * {
native <methods>;
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
-keepattributes InnerClasses
+7 -7
View File
@@ -21,14 +21,14 @@ lintValue=$?
echo "Branch: $3"
if [ $3 = "master" ]; then
echo "New findbugs result for master at: https://nextcloud.kaminsky.me/index.php/s/fYZa7NeBsnmFZQD"
echo "New findbugs result for master at: https://www.kaminsky.me/nc-dev/client-findbugs/master.html"
curl -u $4:$5 -X PUT https://nextcloud.kaminsky.me/remote.php/webdav/findbugs/master.html --upload-file build/reports/findbugs/findbugs.html
summary=$(sed -n "/<h1>Summary<\/h1>/,/<h1>Warnings<\/h1>/p" build/reports/findbugs/findbugs.html | head -n-1 | sed s'/<\/a>//'g | sed s'/<a.*>//'g | sed s'/Summary/FindBugs (master)/' | tr "\"" "\'" | tr -d "\r\n")
curl -u $4:$5 -X PUT -d "$summary" https://nextcloud.kaminsky.me/remote.php/webdav/findbugs/findbugs.html
if [ $lintValue -ne 1 ]; then
echo "New lint result for master at: https://nextcloud.kaminsky.me/index.php/s/tXwtChzyqMj6I8v"
echo "New lint result for master at: https://www.kaminsky.me/nc-dev/client-lint/master.html"
curl -u $4:$5 -X PUT https://nextcloud.kaminsky.me/remote.php/webdav/droneLogs/master.html --upload-file build/reports/lint/lint.html
exit 0
fi
@@ -36,10 +36,10 @@ else
if [ -e $6 ]; then
6="master-"$(date +%F)
fi
echo "New lint results at https://nextcloud.kaminsky.me/index.php/s/tXwtChzyqMj6I8v ->" $6.html
echo "New lint results at https://www.kaminsky.me/nc-dev/client-lint/$6.html"
curl 2>/dev/null -u $4:$5 -X PUT https://nextcloud.kaminsky.me/remote.php/webdav/droneLogs/$6.html --upload-file build/reports/lint/lint.html
echo "New findbugs results at https://nextcloud.kaminsky.me/index.php/s/fYZa7NeBsnmFZQD ->" $6.html
echo "New findbugs results at https://www.kaminsky.me/nc-dev/client-findbugs/$6.html"
curl 2>/dev/null -u $4:$5 -X PUT https://nextcloud.kaminsky.me/remote.php/webdav/findbugs/$6.html --upload-file build/reports/findbugs/findbugs.html
# delete all old comments
@@ -64,9 +64,9 @@ else
lintWarningNew=$(echo $lintResultNew | grep "[0-9]* warning" -o | cut -f1 -d" ")
lintErrorOld=$(grep "[0-9]* error" scripts/analysis/lint-results.txt -o | cut -f1 -d" ")
lintWarningOld=$(grep "[0-9]* warning" scripts/analysis/lint-results.txt -o | cut -f1 -d" ")
lintResult="<h1>Lint</h1><table width='500' cellpadding='5' cellspacing='2'><tr class='tablerow0'><td>Type</td><td>Master</td><td>PR</td></tr><tr class='tablerow1'><td>Warnings</td><td>"$lintWarningOld"</td><td>"$lintWarningNew"</td></tr><tr class='tablerow0'><td>Errors</td><td>"$lintErrorOld"</td><td>"$lintErrorNew"</td></tr></table>"
findbugsResultNew=$(sed -n "/<h1>Summary<\/h1>/,/<h1>Warnings<\/h1>/p" build/reports/findbugs/findbugs.html |head -n-1 | sed s'/<\/a>//'g | sed s'/<a.*>//'g | sed s'/Summary/FindBugs (new)/' | tr "\"" "\'" | tr -d "\n")
findbugsResultOld=$(curl 2>/dev/null https://nextcloud.kaminsky.me/index.php/s/YaHngKMM6ERmBeg/download | tr "\"" "\'" | tr -d "\r\n")
lintResult="<h1>Lint</h1><table width='500' cellpadding='5' cellspacing='2'><tr class='tablerow0'><td>Type</td><td><a href='https://www.kaminsky.me/nc-dev/client-lint/master.html'>Master</a></td><td><a href='https://www.kaminsky.me/nc-dev/client-lint/"$6".html'>PR</a></td></tr><tr class='tablerow1'><td>Warnings</td><td>"$lintWarningOld"</td><td>"$lintWarningNew"</td></tr><tr class='tablerow0'><td>Errors</td><td>"$lintErrorOld"</td><td>"$lintErrorNew"</td></tr></table>"
findbugsResultNew=$(sed -n "/<h1>Summary<\/h1>/,/<h1>Warnings<\/h1>/p" build/reports/findbugs/findbugs.html |head -n-1 | sed s'/<\/a>//'g | sed s'/<a.*>//'g | sed s"#Summary#<a href=\"https://www.kaminsky.me/nc-dev/client-findbugs/$6.html\">FindBugs</a> (new)#" | tr "\"" "\'" | tr -d "\n")
findbugsResultOld=$(curl 2>/dev/null https://nextcloud.kaminsky.me/index.php/s/YaHngKMM6ERmBeg/download | tr "\"" "\'" | tr -d "\r\n" | sed s'#FindBugs#<a href=\"https://www.kaminsky.me/nc-dev/client-findbugs/master.html">FindBugs</a>#'| tr "\"" "\'" | tr -d "\n")
curl -u $1:$2 -X POST https://api.github.com/repos/nextcloud/android/issues/$7/comments -d "{ \"body\" : \"$lintResult $findbugsResultNew $findbugsResultOld $checkLibraryMessage \" }"
if [ $checkLibrary -eq 1 ]; then
+1 -1
View File
@@ -1,2 +1,2 @@
DO NOT TOUCH; GENERATED BY DRONE
<span class="mdl-layout-title">Lint Report: 93 warnings</span>
<span class="mdl-layout-title">Lint Report: 94 warnings</span>
@@ -258,6 +258,19 @@ public class EncryptionTestIT {
}
}
@Test
public void testSHA512() {
// sent to 3rd party app in cleartext
String token = "4ae5978bf5354cd284b539015d442141";
String salt = EncryptionUtils.encodeBytesToBase64String(EncryptionUtils.randomBytes(EncryptionUtils.saltLength));
// stored in database
String hashedToken = EncryptionUtils.generateSHA512(token, salt);
// check: use passed cleartext and salt to verify hashed token
assertTrue(EncryptionUtils.verifySHA512(hashedToken, token));
}
// Helper
private boolean compareJsonStrings(String expected, String actual) {
@@ -362,4 +375,4 @@ public class EncryptionTestIT {
return temp;
}
}
}
@@ -0,0 +1 @@
Приложението Nextcloud за Android осигурява достъп до всичките ви файлове в Next
@@ -0,0 +1 @@
Nextcloud
@@ -28,9 +28,12 @@ import com.owncloud.android.db.PreferenceManager;
import java.security.Key;
public class PushUtils {
public final class PushUtils {
public static final String KEY_PUSH = "push";
private PushUtils() {
}
public static void pushRegistrationToServer() {
// do nothing
}
@@ -44,7 +47,7 @@ public class PushUtils {
return null;
}
public SignatureVerification verifySignature(Context context, byte[] signatureBytes, byte[] subjectBytes) {
public static SignatureVerification verifySignature(Context context, byte[] signatureBytes, byte[] subjectBytes) {
return null;
}
@@ -71,7 +71,7 @@ import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Locale;
public class PushUtils {
public final class PushUtils {
public static final String KEY_PUSH = "push";
private static final String TAG = "PushUtils";
@@ -81,6 +81,9 @@ public class PushUtils {
private static final String KEYPAIR_PUB_EXTENSION = ".pub";
private static ArbitraryDataProvider arbitraryDataProvider;
private PushUtils() {
}
public static String generateSHA512Hash(String pushToken) {
MessageDigest messageDigest = null;
try {
@@ -295,7 +298,6 @@ public class PushUtils {
fileInputStream = new FileInputStream(path);
byte[] bytes = new byte[fileInputStream.available()];
fileInputStream.read(bytes);
fileInputStream.close();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
@@ -315,6 +317,14 @@ public class PushUtils {
Log_OC.d(TAG, "InvalidKeySpecException while reading the key");
} catch (NoSuchAlgorithmException e) {
Log_OC.d(TAG, "RSA algorithm not supported");
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
Log_OC.e(TAG, "Error closing input stream during reading key from file", e);
}
}
}
return null;
@@ -331,12 +341,19 @@ public class PushUtils {
}
keyFileOutputStream = new FileOutputStream(path);
keyFileOutputStream.write(encoded);
keyFileOutputStream.close();
return 0;
} catch (FileNotFoundException e) {
Log_OC.d(TAG, "Failed to save key to file");
} catch (IOException e) {
Log_OC.d(TAG, "Failed to save key to file via IOException");
} finally {
if (keyFileOutputStream != null) {
try {
keyFileOutputStream.close();
} catch (IOException e) {
Log_OC.e(TAG, "Error closing input stream during reading key from file", e);
}
}
}
return -1;
@@ -400,7 +417,7 @@ public class PushUtils {
}
}
public SignatureVerification verifySignature(Context context, byte[] signatureBytes, byte[] subjectBytes) {
public static SignatureVerification verifySignature(Context context, byte[] signatureBytes, byte[] subjectBytes) {
Signature signature = null;
PublicKey publicKey;
SignatureVerification signatureVerification = new SignatureVerification();
@@ -413,7 +430,6 @@ public class PushUtils {
Gson gson = new Gson();
PushConfigurationState pushArbitraryData;
try {
signature = Signature.getInstance("SHA512withRSA");
if (accounts.length > 0) {
@@ -444,7 +460,7 @@ public class PushUtils {
return signatureVerification;
}
private Key readKeyFromString(boolean readPublicKey, String keyString) {
private static Key readKeyFromString(boolean readPublicKey, String keyString) {
String modifiedKey;
if (readPublicKey) {
modifiedKey = keyString.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----",
@@ -464,7 +480,6 @@ public class PushUtils {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decode(modifiedKey, Base64.DEFAULT));
return keyFactory.generatePrivate(keySpec);
}
} catch (NoSuchAlgorithmException e) {
Log.d("TAG", "No such algorithm while reading key from string");
} catch (InvalidKeySpecException e) {
@@ -473,5 +488,4 @@ public class PushUtils {
return null;
}
}
+13
View File
@@ -66,6 +66,7 @@
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<application
android:name=".MainApp"
android:icon="@mipmap/ic_launcher"
@@ -295,6 +296,18 @@
<activity android:name=".ui.activity.ManageSpaceActivity"
android:label="@string/manage_space_title"
android:theme="@style/Theme.ownCloud" />
<service
android:name=".services.AccountManagerService"
android:enabled="true"
android:exported="true" >
</service>
<activity
android:name=".ui.activity.SsoGrantPermissionActivity"
android:exported="true"
android:theme="@style/Theme.ownCloud.Dialog.NoTitle" />
</application>
</manifest>
@@ -0,0 +1,25 @@
/***
Copyright (c) 2008-2011 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
From _The Busy Coder's Guide to Advanced Android Development_
http://commonsware.com/AdvAndroid
More information here: https://github.com/abeluck/android-streams-ipc
*/
package com.nextcloud.android.sso.aidl;
// Declare the interface.
interface IInputStreamService {
ParcelFileDescriptor performNextcloudRequest(in ParcelFileDescriptor input);
}
@@ -0,0 +1,22 @@
package com.nextcloud.android.sso;
public class Constants {
// Authenticator related constants
public static final String SSO_USERNAME = "username";
public static final String SSO_TOKEN = "token";
public static final String SSO_SERVER_URL = "server_url";
public static final String SSO_SHARED_PREFERENCE = "single-sign-on";
public static final String NEXTCLOUD_SSO_EXCEPTION = "NextcloudSsoException";
public static final String NEXTCLOUD_SSO = "NextcloudSSO";
public static final String NEXTCLOUD_FILES_ACCOUNT = "NextcloudFilesAccount";
// Custom Exceptions
public static final String EXCEPTION_INVALID_TOKEN = "CE_1";
public static final String EXCEPTION_ACCOUNT_NOT_FOUND = "CE_2";
public static final String EXCEPTION_UNSUPPORTED_METHOD = "CE_3";
public static final String EXCEPTION_INVALID_REQUEST_URL = "CE_4";
public static final String EXCEPTION_HTTP_REQUEST_FAILED = "CE_5";
public static final String EXCEPTION_ACCOUNT_ACCESS_DECLINED = "CE_6";
}
@@ -0,0 +1,251 @@
/*
* Nextcloud SingleSignOn
*
* @author David Luhmer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* More information here: https://github.com/abeluck/android-streams-ipc
*/
package com.nextcloud.android.sso;
import android.accounts.Account;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import com.nextcloud.android.sso.aidl.IInputStreamService;
import com.nextcloud.android.sso.aidl.NextcloudRequest;
import com.nextcloud.android.sso.aidl.ParcelFileDescriptorUtil;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.lib.common.OwnCloudAccount;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.OwnCloudClientManager;
import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.utils.EncryptionUtils;
import org.apache.commons.httpclient.HttpMethodBase;
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.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Map;
import static com.nextcloud.android.sso.Constants.EXCEPTION_ACCOUNT_NOT_FOUND;
import static com.nextcloud.android.sso.Constants.EXCEPTION_HTTP_REQUEST_FAILED;
import static com.nextcloud.android.sso.Constants.EXCEPTION_INVALID_REQUEST_URL;
import static com.nextcloud.android.sso.Constants.EXCEPTION_INVALID_TOKEN;
import static com.nextcloud.android.sso.Constants.EXCEPTION_UNSUPPORTED_METHOD;
import static com.nextcloud.android.sso.Constants.SSO_SHARED_PREFERENCE;
/**
* Stream binder to pass usable InputStreams across the process boundary in Android.
*/
public class InputStreamBinder extends IInputStreamService.Stub {
private final static String TAG = "InputStreamBinder";
private static final String CONTENT_TYPE_APPLICATION_JSON = "application/json";
private static final String CHARSET_UTF8 = "UTF-8";
private static final int HTTP_STATUS_CODE_OK = 200;
private static final int HTTP_STATUS_CODE_MULTIPLE_CHOICES = 300;
private static final char PATH_SEPARATOR = '/';
private Context context;
public InputStreamBinder(Context context) {
this.context = context;
}
private NameValuePair[] convertMapToNVP(Map<String, String> map) {
NameValuePair[] nvp = new NameValuePair[map.size()];
int i = 0;
for (String key : map.keySet()) {
nvp[i] = new NameValuePair(key, map.get(key));
i++;
}
return nvp;
}
public ParcelFileDescriptor performNextcloudRequest(ParcelFileDescriptor input) {
// read the input
final InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(input);
Exception exception = null;
InputStream httpStream = new InputStream() {
@Override
public int read() {
return 0;
}
};
try {
// Start request and catch exceptions
NextcloudRequest request = deserializeObjectAndCloseStream(is);
httpStream = processRequest(request);
} catch (Exception e) {
Log_OC.e(TAG, e.getMessage());
exception = e;
}
try {
// Write exception to the stream followed by the actual network stream
InputStream exceptionStream = serializeObjectToInputStream(exception);
InputStream resultStream = new java.io.SequenceInputStream(exceptionStream, httpStream);
return ParcelFileDescriptorUtil.pipeFrom(resultStream, thread -> Log.d(TAG, "Done sending result"));
} catch (IOException e) {
Log_OC.e(TAG, e.getMessage());
}
return null;
}
private <T extends Serializable> ByteArrayInputStream serializeObjectToInputStream(T obj) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.flush();
oos.close();
return new ByteArrayInputStream(baos.toByteArray());
}
private <T extends Serializable> T deserializeObjectAndCloseStream(InputStream is) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(is);
T result = (T) ois.readObject();
is.close();
ois.close();
return result;
}
private InputStream processRequest(final NextcloudRequest request) throws UnsupportedOperationException, com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException, OperationCanceledException, AuthenticatorException, IOException {
Account account = AccountUtils.getOwnCloudAccountByName(context, request.getAccountName()); // TODO handle case that account is not found!
if(account == null) {
throw new IllegalStateException(EXCEPTION_ACCOUNT_NOT_FOUND);
}
// Validate token
if (!isValid(request)) {
throw new IllegalStateException(EXCEPTION_INVALID_TOKEN);
}
// Validate URL
if(request.getUrl().length() == 0 || request.getUrl().charAt(0) != PATH_SEPARATOR) {
throw new IllegalStateException(EXCEPTION_INVALID_REQUEST_URL, new IllegalStateException("URL need to start with a /"));
}
OwnCloudClientManager ownCloudClientManager = OwnCloudClientManagerFactory.getDefaultSingleton();
OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
OwnCloudClient client = ownCloudClientManager.getClientFor(ocAccount, context);
String requestUrl = client.getBaseUri() + request.getUrl();
HttpMethodBase method;
switch (request.getMethod()) {
case "GET":
method = new GetMethod(requestUrl);
break;
case "POST":
method = new PostMethod(requestUrl);
if (request.getRequestBody() != null) {
StringRequestEntity requestEntity = new StringRequestEntity(
request.getRequestBody(),
CONTENT_TYPE_APPLICATION_JSON,
CHARSET_UTF8);
((PostMethod) method).setRequestEntity(requestEntity);
}
break;
case "PUT":
method = new PutMethod(requestUrl);
if (request.getRequestBody() != null) {
StringRequestEntity requestEntity = new StringRequestEntity(
request.getRequestBody(),
CONTENT_TYPE_APPLICATION_JSON,
CHARSET_UTF8);
((PutMethod) method).setRequestEntity(requestEntity);
}
break;
case "DELETE":
method = new DeleteMethod(requestUrl);
break;
default:
throw new UnsupportedOperationException(EXCEPTION_UNSUPPORTED_METHOD);
}
method.setQueryString(convertMapToNVP(request.getParameter()));
method.addRequestHeader("OCS-APIREQUEST", "true");
client.setFollowRedirects(request.isFollowRedirects());
int status = client.executeMethod(method);
// Check if status code is 2xx --> https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_Success
if (status >= HTTP_STATUS_CODE_OK && status < HTTP_STATUS_CODE_MULTIPLE_CHOICES) {
return method.getResponseBodyAsStream();
} else {
throw new IllegalStateException(EXCEPTION_HTTP_REQUEST_FAILED, new IllegalStateException(String.valueOf(status)));
}
}
private boolean isValid(NextcloudRequest request) {
String callingPackageName = context.getPackageManager().getNameForUid(Binder.getCallingUid());
SharedPreferences sharedPreferences = context.getSharedPreferences(SSO_SHARED_PREFERENCE,
Context.MODE_PRIVATE);
String hash = sharedPreferences.getString(callingPackageName, "");
return validateToken(hash, request.getToken());
}
private boolean validateToken(String hash, String token) {
String salt = hash.split("\\$")[1]; // TODO extract "$"
String newHash = EncryptionUtils.generateSHA512(token, salt);
// As discussed with Lukas R. at the Nextcloud Conf 2018, always compare whole strings
// and don't exit prematurely if the string does not match anymore to prevent timing-attacks
return isEqual(hash.getBytes(), newHash.getBytes());
}
// Taken from http://codahale.com/a-lesson-in-timing-attacks/
private static boolean isEqual(byte[] a, byte[] b) {
if (a.length != b.length) {
return false;
}
int result = 0;
for (int i = 0; i < a.length; i++) {
result |= a[i] ^ b[i];
}
return result == 0;
}
}
@@ -0,0 +1,26 @@
/*
* Nextcloud SingleSignOn
*
* @author David Luhmer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.android.sso.aidl;
public interface IThreadListener {
void onThreadFinished(final Thread thread);
}
@@ -0,0 +1,147 @@
/*
* Nextcloud SingleSignOn
*
* @author David Luhmer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.android.sso.aidl;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NextcloudRequest implements Serializable {
private static final long serialVersionUID = 215521212534240L; //assign a long value
private String method;
private Map<String, List<String>> header = new HashMap<>();
private Map<String, String> parameter = new HashMap<>();
private String requestBody;
private String url;
private String token;
private String packageName;
private String accountName;
private boolean followRedirects;
private NextcloudRequest() { }
public static class Builder {
private NextcloudRequest ncr;
public Builder() {
ncr = new NextcloudRequest();
}
public NextcloudRequest build() {
return ncr;
}
public Builder setMethod(String method) {
ncr.method = method;
return this;
}
public Builder setHeader(Map<String, List<String>> header) {
ncr.header = header;
return this;
}
public Builder setParameter(Map<String, String> parameter) {
ncr.parameter = parameter;
return this;
}
public Builder setRequestBody(String requestBody) {
ncr.requestBody = requestBody;
return this;
}
public Builder setUrl(String url) {
ncr.url = url;
return this;
}
public Builder setToken(String token) {
ncr.token = token;
return this;
}
public Builder setAccountName(String accountName) {
ncr.accountName = accountName;
return this;
}
/**
* Default value: true
* @param followRedirects
* @return
*/
public Builder setFollowRedirects(boolean followRedirects) {
ncr.followRedirects = followRedirects;
return this;
}
}
public String getMethod() {
return this.method;
}
public Map<String, List<String>> getHeader() {
return this.header;
}
public Map<String, String> getParameter() {
return this.parameter;
}
public String getRequestBody() {
return this.requestBody;
}
public String getUrl() {
return this.url;
}
public String getToken() {
return this.token;
}
public void setToken(String token) {
this.token = token;
}
public String getPackageName() {
return this.packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getAccountName() {
return this.accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public boolean isFollowRedirects() {
return this.followRedirects;
}
}
@@ -0,0 +1,106 @@
/*
* Nextcloud SingleSignOn
*
* @author David Luhmer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.android.sso.aidl;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import com.owncloud.android.lib.common.utils.Log_OC;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public final class ParcelFileDescriptorUtil {
private ParcelFileDescriptorUtil() { }
public static ParcelFileDescriptor pipeFrom(InputStream inputStream, IThreadListener listener)
throws IOException {
ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
ParcelFileDescriptor readSide = pipe[0];
ParcelFileDescriptor writeSide = pipe[1];
// start the transfer thread
new TransferThread(inputStream, new ParcelFileDescriptor.AutoCloseOutputStream(writeSide),
listener)
.start();
return readSide;
}
public static ParcelFileDescriptor pipeTo(OutputStream outputStream, IThreadListener listener)
throws IOException {
ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
ParcelFileDescriptor readSide = pipe[0];
ParcelFileDescriptor writeSide = pipe[1];
// start the transfer thread
new TransferThread(new ParcelFileDescriptor.AutoCloseInputStream(readSide), outputStream,
listener)
.start();
return writeSide;
}
public static class TransferThread extends Thread {
private static final String TAG = TransferThread.class.getCanonicalName();
private final InputStream mIn;
private final OutputStream mOut;
private final IThreadListener mListener;
TransferThread(InputStream in, OutputStream out, IThreadListener listener) {
super("ParcelFileDescriptor Transfer Thread");
mIn = in;
mOut = out;
mListener = listener;
setDaemon(true);
}
@Override
public void run() {
byte[] buf = new byte[1024];
int len;
try {
while ((len = mIn.read(buf)) > 0) {
mOut.write(buf, 0, len);
}
mOut.flush(); // just to be safe
} catch (IOException e) {
Log.e("TransferThread", "writing failed");
} finally {
try {
mIn.close();
} catch (IOException e) {
Log_OC.e(TAG, e.getMessage());
}
try {
mOut.close();
} catch (IOException e) {
Log_OC.e(TAG, e.getMessage());
}
}
if (mListener != null) {
mListener.onThreadFinished(this);
}
}
}
}
@@ -109,7 +109,7 @@ public class MainApp extends MultiDexApplication {
private static String storagePath;
private static boolean mOnlyOnDevice = false;
private static boolean mOnlyOnDevice;
private SharedPreferences appPrefs;
@SuppressWarnings("unused")
@@ -154,7 +154,7 @@ public class MainApp extends MultiDexApplication {
Log_OC.d("Debug", "start logging");
}
if (Build.VERSION.SDK_INT >= 24) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
try {
Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
m.invoke(null);
@@ -1,4 +1,4 @@
/**
/*
* ownCloud Android client application
*
* @author David A. Velasco
@@ -57,7 +57,7 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
public static final String KEY_REQUIRED_FEATURES = "requiredFeatures";
public static final String KEY_LOGIN_OPTIONS = "loginOptions";
public static final String KEY_ACCOUNT = "account";
private static final String TAG = AccountAuthenticator.class.getSimpleName();
private Context mContext;
@@ -75,16 +75,15 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
*/
@Override
public Bundle addAccount(AccountAuthenticatorResponse response,
String accountType, String authTokenType,
String[] requiredFeatures, Bundle options)
throws NetworkErrorException {
String accountType, String authTokenType,
String[] requiredFeatures, Bundle options) {
Log_OC.i(TAG, "Adding account with type " + accountType + " and auth token " + authTokenType);
final Bundle bundle = new Bundle();
AccountManager accountManager = AccountManager.get(mContext);
Account[] accounts = accountManager.getAccountsByType(MainApp.getAccountType(mContext));
final Bundle bundle = new Bundle();
if (mContext.getResources().getBoolean(R.bool.multiaccount_support) || accounts.length < 1) {
try {
validateAccountType(accountType);
@@ -104,16 +103,13 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
setIntentFlags(intent);
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
} else {
// Return an error
bundle.putInt(AccountManager.KEY_ERROR_CODE, AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION);
final String message = String.format(mContext.getString(R.string.auth_unsupported_multiaccount), mContext.getString(R.string.app_name));
bundle.putString(AccountManager.KEY_ERROR_MESSAGE, message);
mHandler.post(() -> Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show());
}
return bundle;
@@ -124,7 +120,7 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
*/
@Override
public Bundle confirmCredentials(AccountAuthenticatorResponse response,
Account account, Bundle options) throws NetworkErrorException {
Account account, Bundle options) {
try {
validateAccountType(account.type);
} catch (AuthenticatorException e) {
@@ -155,9 +151,8 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
*/
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response,
Account account, String authTokenType, Bundle options)
throws NetworkErrorException {
/// validate parameters
Account account, String authTokenType, Bundle options) {
// validate parameters
try {
validateAccountType(account.type);
validateAuthTokenType(authTokenType);
@@ -203,7 +198,7 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
@Override
public Bundle hasFeatures(AccountAuthenticatorResponse response,
Account account, String[] features) throws NetworkErrorException {
Account account, String[] features) {
final Bundle result = new Bundle();
result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true);
return result;
@@ -211,8 +206,7 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
@Override
public Bundle updateCredentials(AccountAuthenticatorResponse response,
Account account, String authTokenType, Bundle options)
throws NetworkErrorException {
Account account, String authTokenType, Bundle options) {
Intent intent = new Intent(mContext, AuthenticatorActivity.class);
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
@@ -15,7 +15,6 @@
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.owncloud.android.authentication;
@@ -34,12 +33,14 @@ import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
import com.owncloud.android.lib.resources.status.OwnCloudVersion;
import com.owncloud.android.ui.activity.ManageAccountsActivity;
public class AccountUtils {
/**
* Helper class for dealing with accounts.
*/
public final class AccountUtils {
private static final String PREF_SELECT_OC_ACCOUNT = "select_oc_account";
public static final int ACCOUNT_VERSION = 1;
public static final int ACCOUNT_VERSION_WITH_PROPER_ID = 2;
//public static final int ACCOUNT_VERSION_WITH_PROPER_ID = 2;
public static final String ACCOUNT_USES_STANDARD_PASSWORD = "ACCOUNT_USES_STANDARD_PASSWORD";
private AccountUtils() {
@@ -152,10 +153,8 @@ public class AccountUtils {
public static boolean setCurrentOwnCloudAccount(final Context context, String accountName) {
boolean result = false;
if (accountName != null) {
boolean found;
for (final Account account : getAccounts(context)) {
found = (account.name.equals(accountName));
if (found) {
if (accountName.equals(account.name)) {
SharedPreferences.Editor appPrefs = PreferenceManager.getDefaultSharedPreferences(context).edit();
appPrefs.putString(PREF_SELECT_OC_ACCOUNT, accountName);
appPrefs.apply();
@@ -188,6 +188,8 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
public static final String REGULAR_SERVER_INPUT_TYPE = "regular";
public static final String SUBDOMAIN_SERVER_INPUT_TYPE = "prefix";
public static final String DIRECTORY_SERVER_INPUT_TYPE = "suffix";
public static final int NO_ICON = 0;
public static final String EMPTY_STRING = "";
/// parameters from EXTRAs in starter Intent
private byte mAction;
@@ -196,8 +198,8 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
/// activity-level references / state
private final Handler mHandler = new Handler();
private ServiceConnection mOperationsServiceConnection = null;
private OperationsServiceBinder mOperationsServiceBinder = null;
private ServiceConnection mOperationsServiceConnection;
private OperationsServiceBinder mOperationsServiceBinder;
private AccountManager mAccountMgr;
private Uri mNewCapturedUriFromOAuth2Redirection;
@@ -207,7 +209,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
private TextView mServerStatusView;
private TextWatcher mHostUrlInputWatcher;
private String mServerStatusText = "";
private String mServerStatusText = EMPTY_STRING;
private int mServerStatusIcon;
private boolean mServerIsChecked;
@@ -227,10 +229,10 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
private WebView mLoginWebView;
private String mAuthStatusText = "";
private String mAuthStatusText = EMPTY_STRING;
private int mAuthStatusIcon;
private String mAuthToken = "";
private String mAuthToken = EMPTY_STRING;
private AuthenticatorAsyncTask mAsyncTask;
private boolean mIsFirstAuthAttempt;
@@ -547,7 +549,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
if (dataString.length() < prefix.length()) {
throw new IllegalArgumentException("Invalid login URL detected");
}
LoginUrlInfo loginUrlInfo = new LoginUrlInfo();
// format is basically xxx://login/server:xxx&user:xxx&password while all variables are optional
String data = dataString.substring(prefix.length());
@@ -560,6 +561,8 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
throw new IllegalArgumentException("Illegal number of login URL elements detected: " + values.length);
}
LoginUrlInfo loginUrlInfo = new LoginUrlInfo();
for (String value : values) {
if (value.startsWith("user" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR)) {
loginUrlInfo.username = URLDecoder.decode(
@@ -754,7 +757,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
if (mAuthStatusIcon != 0) {
Log_OC.d(TAG, "onTextChanged: hiding authentication status");
mAuthStatusIcon = 0;
mAuthStatusText = "";
mAuthStatusText = EMPTY_STRING;
showAuthStatus();
}
}
@@ -815,7 +818,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
mUsernameInput.setEnabled(false);
mUsernameInput.setFocusable(false);
}
mPasswordInput.setText(""); // clean password to avoid social hacking
mPasswordInput.setText(EMPTY_STRING); // clean password to avoid social hacking
if (isPasswordExposed) {
showPassword();
}
@@ -1179,7 +1182,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
}
} else {
mServerStatusText = "";
mServerStatusText = EMPTY_STRING;
mServerStatusIcon = 0;
if (!webViewLoginMethod) {
showServerStatus();
@@ -1403,7 +1406,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
if (!webViewLoginMethod && !mUsernameInput.getText().toString().trim().equals(username)) {
// fail - not a new account, but an existing one; disallow
result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);
mAuthToken = "";
mAuthToken = EMPTY_STRING;
updateAuthStatusIconAndText(result);
showAuthStatus();
Log_OC.d(TAG, result.getLogMessage());
@@ -1622,7 +1625,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
mServerStatusText = getResources().getString(R.string.untrusted_domain);
break;
default:
mServerStatusText = "";
mServerStatusText = EMPTY_STRING;
mServerStatusIcon = 0;
break;
}
@@ -1718,7 +1721,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
}
}
/**
* Processes the result of the access check performed to try the user credentials.
*
@@ -1790,7 +1792,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
updateServerStatusIconAndText(result);
showServerStatus();
mAuthStatusIcon = 0;
mAuthStatusText = "";
mAuthStatusText = EMPTY_STRING;
if (!webViewLoginMethod) {
showAuthStatus();
@@ -1823,7 +1825,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
}
}
/**
* Updates the authentication token.
*
@@ -1873,7 +1874,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
}
/**
* Creates a new account through the Account Authenticator that started this activity.
*
@@ -1922,7 +1922,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
if (isOAuth || isSaml) {
// with external authorizations, the password is never input in the app
mAccountMgr.addAccountExplicitly(mAccount, "", null);
mAccountMgr.addAccountExplicitly(mAccount, EMPTY_STRING, null);
} else {
if (!webViewLoginMethod) {
mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
@@ -1983,12 +1983,13 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
}
}
/**
/**
* Updates the content and visibility state of the icon and text associated
* to the last check on the ownCloud server.
*/
private void showServerStatus() {
if (mServerStatusIcon == 0 && "".equals(mServerStatusText)) {
if (mServerStatusIcon == NO_ICON && EMPTY_STRING.equals(mServerStatusText)) {
mServerStatusView.setVisibility(View.INVISIBLE);
} else {
mServerStatusView.setText(mServerStatusText);
@@ -1997,13 +1998,12 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
}
}
/**
* Updates the content and visibility state of the icon and text associated
* to the interactions with the OAuth authorization server.
*/
private void showAuthStatus() {
if (mAuthStatusIcon == 0 && "".equals(mAuthStatusText)) {
if (mAuthStatusIcon == NO_ICON && EMPTY_STRING.equals(mAuthStatusText)) {
mAuthStatusView.setVisibility(View.INVISIBLE);
} else {
mAuthStatusView.setText(mAuthStatusText);
@@ -2012,7 +2012,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
}
}
private void showRefreshButton(boolean show) {
if (webViewLoginMethod && mRefreshButton != null) {
if (show) {
@@ -2082,6 +2081,8 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
private abstract static class RightDrawableOnTouchListener implements OnTouchListener {
private static final int RIGHT_DRAWABLE_COMPOUND_DRAWABLES_LENGTH = 2;
private int fuzz = 75;
/**
@@ -2092,7 +2093,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
Drawable rightDrawable = null;
if (view instanceof TextView) {
Drawable[] drawables = ((TextView) view).getCompoundDrawables();
if (drawables.length > 2) {
if (drawables.length > RIGHT_DRAWABLE_COMPOUND_DRAWABLES_LENGTH) {
rightDrawable = drawables[2];
}
}
@@ -32,7 +32,7 @@ import java.util.Locale;
/**
* Helper class for authenticator-URL related logic.
*/
public abstract class AuthenticatorUrlUtils {
public final class AuthenticatorUrlUtils {
public static final String WEBDAV_PATH_4_0_AND_LATER = "/remote.php/webdav";
private static final String HTTPS_PROTOCOL = "https://";
@@ -41,6 +41,9 @@ public abstract class AuthenticatorUrlUtils {
private static final String ODAV_PATH = "/remote.php/odav";
private static final String SAML_SSO_PATH = "/remote.php/webdav";
private AuthenticatorUrlUtils() {
}
/**
* Returns the proper URL path to access the WebDAV interface of an ownCloud server,
* according to its version and the authorization method used.
@@ -37,7 +37,7 @@ import com.owncloud.android.utils.DeviceCredentialUtils;
import java.util.HashSet;
import java.util.Set;
public class PassCodeManager {
public final class PassCodeManager {
private static final Set<Class> exemptOfPasscodeActivities;
@@ -53,10 +53,10 @@ public class PassCodeManager {
private static final int PASS_CODE_TIMEOUT = 1000;
// keeping a "low" positive value is the easiest way to prevent the pass code is requested on rotations
private static PassCodeManager passCodeManagerInstance = null;
private static PassCodeManager passCodeManagerInstance;
private Long timestamp = 0L;
private int visibleActivitiesCounter = 0;
private int visibleActivitiesCounter;
public static PassCodeManager getPassCodeManager() {
if (passCodeManagerInstance == null) {
@@ -35,7 +35,8 @@ import java.util.List;
* Database provider for handling the persistence aspects of arbitrary data table.
*/
public class ArbitraryDataProvider {
static private final String TAG = ArbitraryDataProvider.class.getSimpleName();
private static final String TAG = ArbitraryDataProvider.class.getSimpleName();
private static final String TRUE = "true";
private ContentResolver contentResolver;
@@ -115,9 +116,7 @@ public class ArbitraryDataProvider {
}
public boolean getBooleanValue(String accountName, String key) {
String value = getValue(accountName, key);
return !value.isEmpty() && value.equalsIgnoreCase("true");
return TRUE.equalsIgnoreCase(getValue(accountName, key));
}
public boolean getBooleanValue(Account account, String key) {
@@ -25,7 +25,7 @@ import java.util.HashMap;
import java.util.Map;
/**
* Decrypted class representation of metadata json of folder metadata
* Decrypted class representation of metadata json of folder metadata.
*/
public class DecryptedFolderMetadata {
private Metadata metadata;
@@ -36,7 +36,7 @@ public class DecryptedFolderMetadata {
this.files = new HashMap<>();
}
public DecryptedFolderMetadata(Metadata metadata, HashMap<String, DecryptedFile> files) {
public DecryptedFolderMetadata(Metadata metadata, Map<String, DecryptedFile> files) {
this.metadata = metadata;
this.files = files;
}
@@ -766,7 +766,8 @@ public class FileDataStorageManager {
}
}
public void migrateStoredFiles(String srcPath, String dstPath) throws Exception {
public void migrateStoredFiles(String srcPath, String dstPath)
throws RemoteException, OperationApplicationException {
Cursor cursor;
try {
if (getContentResolver() != null) {
@@ -1465,8 +1466,8 @@ public class FileDataStorageManager {
}
}
public void saveSharesDB(ArrayList<OCShare> shares) {
ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
public void saveSharesDB(List<OCShare> shares) {
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
// Reset flags & Remove shares for this files
String filePath = "";
@@ -1580,7 +1581,7 @@ public class FileDataStorageManager {
* @return
*/
private ArrayList<ContentProviderOperation> prepareInsertShares(
ArrayList<OCShare> shares, ArrayList<ContentProviderOperation> operations) {
List<OCShare> shares, ArrayList<ContentProviderOperation> operations) {
if (shares != null) {
// prepare operations to insert or update files to save in the given folder
@@ -44,7 +44,7 @@ import javax.annotation.Nullable;
/**
* Media queries to gain access to media lists for the device.
*/
public class MediaProvider {
public final class MediaProvider {
private static final String TAG = MediaProvider.class.getSimpleName();
// fixed query parameters
@@ -58,6 +58,10 @@ public class MediaProvider {
private static final String[] VIDEOS_FOLDER_PROJECTION = {"Distinct " + MediaStore.Video.Media.BUCKET_ID,
MediaStore.Video.Media.BUCKET_DISPLAY_NAME};
private MediaProvider() {
// utility class -> private constructor
}
/**
* Getting All Images Paths.
*
@@ -59,6 +59,7 @@ public class OCFile implements Parcelable, Comparable<OCFile>, ServerFileInterfa
private final static String PERMISSION_SHARED_WITH_ME = "S"; // TODO move to better location
private final static String PERMISSION_CAN_RESHARE = "R";
private final static String PERMISSION_CAN_WRITE = "CK";
public static final String PATH_SEPARATOR = "/";
public static final String ROOT_PATH = PATH_SEPARATOR;
@@ -466,8 +467,8 @@ public class OCFile implements Parcelable, Comparable<OCFile>, ServerFileInterfa
Log_OC.d(TAG, "OCFile name changing from " + mRemotePath);
if (name != null && name.length() > 0 && !name.contains(PATH_SEPARATOR) &&
!mRemotePath.equals(ROOT_PATH)) {
String parent = (new File(this.getRemotePath())).getParent();
parent = (parent.endsWith(PATH_SEPARATOR)) ? parent : parent + PATH_SEPARATOR;
String parent = new File(this.getRemotePath()).getParent();
parent = parent.endsWith(PATH_SEPARATOR) ? parent : parent + PATH_SEPARATOR;
mRemotePath = parent + name;
if (isFolder()) {
mRemotePath += PATH_SEPARATOR;
@@ -784,6 +785,11 @@ public class OCFile implements Parcelable, Comparable<OCFile>, ServerFileInterfa
return permissions != null && permissions.contains(PERMISSION_CAN_RESHARE);
}
public boolean canWrite() {
String permissions = getPermissions();
return permissions != null && permissions.contains(PERMISSION_CAN_WRITE);
}
public WebdavEntry.MountType getMountType() {
return mMountType;
}
@@ -78,7 +78,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* Manager for concurrent access to thumbnails cache.
*/
public class ThumbnailsCacheManager {
public final class ThumbnailsCacheManager {
public static final String PREFIX_RESIZED_IMAGE = "r";
public static final String PREFIX_THUMBNAIL = "t";
@@ -103,6 +103,9 @@ public class ThumbnailsCacheManager {
public static final Bitmap mDefaultVideo = BitmapFactory.decodeResource(MainApp.getAppContext().getResources(),
R.drawable.file_movie);
private ThumbnailsCacheManager() {
}
public static class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
@Override
@@ -641,6 +644,9 @@ public class ThumbnailsCacheManager {
}
public static class MediaThumbnailGenerationTask extends AsyncTask<Object, Void, Bitmap> {
private static final int IMAGE_KEY_PARAMS_LENGTH = 2;
private enum Type {IMAGE, VIDEO}
private final WeakReference<ImageView> mImageViewReference;
private File mFile;
@@ -660,7 +666,7 @@ public class ThumbnailsCacheManager {
try {
if (params[0] instanceof File) {
mFile = (File) params[0];
if (params.length == 2) {
if (params.length == IMAGE_KEY_PARAMS_LENGTH) {
mImageKey = (String) params[1];
}
@@ -870,7 +876,8 @@ public class ThumbnailsCacheManager {
// we are using eTag to download a new avatar only if it changed
switch (status) {
case HttpStatus.SC_OK:
// new avatar
case HttpStatus.SC_CREATED:
// new avatar
InputStream inputStream = get.getResponseBodyAsStream();
String newETag = null;
@@ -45,13 +45,14 @@ import java.util.Observable;
* information for each file.
*/
public class UploadsStorageManager extends Observable {
private static final String TAG = UploadsStorageManager.class.getSimpleName();
private static final String AND = " AND ";
static private final String TAG = UploadsStorageManager.class.getSimpleName();
private static final int SINGLE_RESULT = 1;
private ContentResolver mContentResolver;
private Context mContext;
public UploadsStorageManager(ContentResolver contentResolver, Context context) {
if (contentResolver == null) {
throw new IllegalArgumentException("Cannot create an instance with a NULL contentResolver");
@@ -123,7 +124,7 @@ public class UploadsStorageManager extends Observable {
);
Log_OC.d(TAG, "updateUpload returns with: " + result + " for file: " + ocUpload.getLocalPath());
if (result != 1) {
if (result != SINGLE_RESULT) {
Log_OC.e(TAG, "Failed to update item " + ocUpload.getLocalPath() + " into upload db.");
} else {
notifyObserversNow();
@@ -189,7 +190,7 @@ public class UploadsStorageManager extends Observable {
);
if (c != null) {
if (c.getCount() != 1) {
if (c.getCount() != SINGLE_RESULT) {
Log_OC.e(TAG, c.getCount() + " items for id=" + id
+ " available in UploadDb. Expected 1. Failed to update upload db.");
} else {
@@ -272,10 +273,10 @@ public class UploadsStorageManager extends Observable {
}
public OCUpload[] getAllStoredUploads() {
return getUploads(null, null);
return getUploads(null, (String[]) null);
}
private OCUpload[] getUploads(@Nullable String selection, @Nullable String[] selectionArgs) {
private OCUpload[] getUploads(@Nullable String selection, @Nullable String... selectionArgs) {
OCUpload[] list;
Cursor c = getDB().query(
@@ -393,7 +394,7 @@ public class UploadsStorageManager extends Observable {
*/
public OCUpload[] getFinishedUploads() {
return getUploads(ProviderTableMeta.UPLOADS_STATUS + "==" + UploadStatus.UPLOAD_SUCCEEDED.value, null);
return getUploads(ProviderTableMeta.UPLOADS_STATUS + "==" + UploadStatus.UPLOAD_SUCCEEDED.value, (String[]) null);
}
public OCUpload[] getFailedButNotDelayedUploadsForCurrentAccount() {
@@ -432,7 +433,7 @@ public class UploadsStorageManager extends Observable {
"<>" + UploadResult.DELAYED_FOR_CHARGING.getValue() +
AND + ProviderTableMeta.UPLOADS_LAST_RESULT +
"<>" + UploadResult.DELAYED_IN_POWER_SAVE_MODE.getValue(),
null
(String[]) null
);
}
@@ -1,4 +1,4 @@
/**
/*
* Nextcloud Android client application
*
* @author Bartosz Przybylski
@@ -1,4 +1,4 @@
/**
/*
* Nextcloud Android client application
*
* @author Bartosz Przybylski
@@ -24,14 +24,14 @@ package com.owncloud.android.datastorage.providers;
import com.owncloud.android.datastorage.StoragePoint;
import java.io.File;
import java.util.Vector;
import java.util.List;
/**
* @author Bartosz Przybylski
*/
abstract class AbstractStoragePointProvider implements IStoragePointProvider {
boolean canBeAddedToAvailableList(Vector<StoragePoint> currentList, String path) {
boolean canBeAddedToAvailableList(List<StoragePoint> currentList, String path) {
if (path == null) {
return false;
}
@@ -1,4 +1,4 @@
/**
/*
* Nextcloud Android client application
*
* @author Bartosz Przybylski
@@ -25,6 +25,7 @@ import android.text.TextUtils;
import com.owncloud.android.datastorage.StoragePoint;
import java.util.List;
import java.util.Vector;
/**
@@ -40,15 +41,15 @@ public class EnvironmentStoragePointProvider extends AbstractStoragePointProvide
}
@Override
public Vector<StoragePoint> getAvailableStoragePoint() {
Vector<StoragePoint> result = new Vector<>();
public List<StoragePoint> getAvailableStoragePoint() {
List<StoragePoint> result = new Vector<>();
addEntriesFromEnv(result, sSecondaryStorageEnvName);
return result;
}
private void addEntriesFromEnv(Vector<StoragePoint> result, String envName) {
private void addEntriesFromEnv(List<StoragePoint> result, String envName) {
String env = System.getenv(envName);
if (env != null) {
for (String p : env.split(":")) {
@@ -1,4 +1,4 @@
/**
/*
* Nextcloud Android client application
*
* @author Bartosz Przybylski
@@ -23,7 +23,7 @@ package com.owncloud.android.datastorage.providers;
import com.owncloud.android.datastorage.StoragePoint;
import java.util.Vector;
import java.util.List;
/**
* @author Bartosz Przybylski
@@ -38,11 +38,9 @@ public interface IStoragePointProvider {
*/
boolean canProvideStoragePoints();
/**
*
* @return available storage points
*/
Vector<StoragePoint> getAvailableStoragePoint();
List<StoragePoint> getAvailableStoragePoint();
}
@@ -1,4 +1,4 @@
/**
/*
* Nextcloud Android client application
*
* @author Bartosz Przybylski
@@ -23,6 +23,7 @@ package com.owncloud.android.datastorage.providers;
import com.owncloud.android.datastorage.StoragePoint;
import java.util.List;
import java.util.Locale;
import java.util.Vector;
import java.util.regex.Pattern;
@@ -42,8 +43,8 @@ public class MountCommandStoragePointProvider extends AbstractCommandLineStorage
}
@Override
public Vector<StoragePoint> getAvailableStoragePoint() {
Vector<StoragePoint> result = new Vector<>();
public List<StoragePoint> getAvailableStoragePoint() {
List<StoragePoint> result = new Vector<>();
for (String p : getPotentialPaths(getCommandLineResult())) {
if (canBeAddedToAvailableList(result, p)) {
@@ -54,8 +55,8 @@ public class MountCommandStoragePointProvider extends AbstractCommandLineStorage
return result;
}
private Vector<String> getPotentialPaths(String mounted) {
final Vector<String> result = new Vector<>();
private List<String> getPotentialPaths(String mounted) {
final List<String> result = new Vector<>();
for (String line : mounted.split("\n")) {
if (!line.toLowerCase(Locale.US).contains("asec") && sPattern.matcher(line).matches()) {
@@ -24,6 +24,7 @@ package com.owncloud.android.datastorage.providers;
import com.owncloud.android.datastorage.StoragePoint;
import com.owncloud.android.lib.common.utils.Log_OC;
import java.util.List;
import java.util.Vector;
/**
@@ -38,8 +39,8 @@ public class VDCStoragePointProvider extends AbstractCommandLineStoragePoint {
@Override
public Vector<StoragePoint> getAvailableStoragePoint() {
Vector<StoragePoint> result = new Vector<>();
public List<StoragePoint> getAvailableStoragePoint() {
List<StoragePoint> result = new Vector<>();
result.addAll(getPaths(getCommandLineResult()));
@@ -51,8 +52,8 @@ public class VDCStoragePointProvider extends AbstractCommandLineStoragePoint {
return sVDCVolListCommand;
}
private Vector<StoragePoint> getPaths(String vdcResources) {
Vector<StoragePoint> result = new Vector<>();
private List<StoragePoint> getPaths(String vdcResources) {
List<StoragePoint> result = new Vector<>();
for (String line : vdcResources.split("\n")) {
String vdcLine[] = line.split(" ");
@@ -353,7 +353,7 @@ public class OCUpload implements Parcelable {
(getLastResult() == null ? "null" : getLastResult().getValue());
} catch (NullPointerException e) {
Log_OC.d(TAG, "Exception " + e.toString());
return (e.toString());
return e.toString();
}
}
@@ -36,7 +36,7 @@ import static com.owncloud.android.ui.fragment.OCFileListFragment.FOLDER_LAYOUT_
/**
* Helper to simplify reading of Preferences all around the app
*/
public abstract class PreferenceManager {
public final class PreferenceManager {
/**
* Constant to access value of last path selected by the user to upload a file shared from other app.
* Value handled by the app without direct access in the UI.
@@ -65,6 +65,9 @@ public abstract class PreferenceManager {
private static final String PREF__FOLDER_SORT_ORDER = "folder_sort_order";
private static final String PREF__FOLDER_LAYOUT = "folder_layout";
private PreferenceManager() {
}
public static void setKeysReInit(Context context) {
saveBooleanPreference(context, PREF__KEYS_REINIT, true);
}
@@ -363,11 +363,9 @@ public class FileMenuFilter {
OperationsServiceBinder opsBinder = mComponentsGetter.getOperationsServiceBinder();
FileUploaderBinder uploaderBinder = mComponentsGetter.getFileUploaderBinder();
FileDownloaderBinder downloaderBinder = mComponentsGetter.getFileDownloaderBinder();
synchronizing = (
anyFileSynchronizing(opsBinder) || // comparing local and remote
synchronizing = anyFileSynchronizing(opsBinder) || // comparing local and remote
anyFileDownloading(downloaderBinder) ||
anyFileUploading(uploaderBinder)
);
anyFileUploading(uploaderBinder);
}
return synchronizing;
}
@@ -399,11 +399,10 @@ public class FileUploader extends Service
boolean isPowerSaving = PowerUtils.isPowerSaveMode(context);
for ( OCUpload failedUpload: failedUploads) {
accountMatch = (account == null || account.name.equals(failedUpload.getAccountName()));
resultMatch = ((uploadResult == null || uploadResult.equals(failedUpload.getLastResult())));
accountMatch = account == null || account.name.equals(failedUpload.getAccountName());
resultMatch = uploadResult == null || uploadResult.equals(failedUpload.getLastResult());
if (accountMatch && resultMatch) {
if (currentAccount == null ||
!currentAccount.name.equals(failedUpload.getAccountName())) {
if (currentAccount == null || !currentAccount.name.equals(failedUpload.getAccountName())) {
currentAccount = failedUpload.getAccount(context);
}
@@ -572,12 +571,6 @@ public class FileUploader extends Service
mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
}
boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_FORGET);
boolean isCreateRemoteFolder = intent.getBooleanExtra(KEY_CREATE_REMOTE_FOLDER, false);
int createdBy = intent.getIntExtra(KEY_CREATED_BY, UploadFileOperation.CREATED_BY_USER);
if (intent.hasExtra(KEY_FILE) && files == null) {
Log_OC.e(TAG, "Incorrect array for OCFiles provided in upload intent");
return Service.START_NOT_STICKY;
@@ -612,6 +605,10 @@ public class FileUploader extends Service
}
// at this point variable "OCFile[] files" is loaded correctly.
boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_FORGET);
boolean isCreateRemoteFolder = intent.getBooleanExtra(KEY_CREATE_REMOTE_FOLDER, false);
int createdBy = intent.getIntExtra(KEY_CREATED_BY, UploadFileOperation.CREATED_BY_USER);
String uploadKey;
UploadFileOperation newUpload;
try {
@@ -1217,15 +1214,14 @@ public class FileUploader extends Service
!uploadResult.getCode().equals(ResultCode.DELAYED_IN_POWER_SAVE_MODE) &&
!uploadResult.getCode().equals(ResultCode.LOCK_FAILED) ) {
int tickerId = (uploadResult.isSuccess()) ? R.string.uploader_upload_succeeded_ticker :
int tickerId = uploadResult.isSuccess() ? R.string.uploader_upload_succeeded_ticker :
R.string.uploader_upload_failed_ticker;
String content;
// check credentials error
boolean needsToUpdateCredentials = ResultCode.UNAUTHORIZED.equals(uploadResult.getCode());
tickerId = (needsToUpdateCredentials) ?
R.string.uploader_upload_failed_credentials_error : tickerId;
tickerId = needsToUpdateCredentials ? R.string.uploader_upload_failed_credentials_error : tickerId;
mNotificationBuilder
.setTicker(getString(tickerId))
@@ -47,6 +47,7 @@ import com.owncloud.android.operations.UploadFileOperation;
import com.owncloud.android.ui.activity.Preferences;
import com.owncloud.android.utils.FileStorageUtils;
import com.owncloud.android.utils.FilesSyncHelper;
import com.owncloud.android.utils.MimeType;
import com.owncloud.android.utils.MimeTypeUtil;
import com.owncloud.android.utils.PowerUtils;
@@ -65,7 +66,6 @@ import java.util.TimeZone;
*/
public class FilesSyncJob extends Job {
public static final String TAG = "FilesSyncJob";
public static final String SKIP_CUSTOM = "skipCustom";
public static final String OVERRIDE_POWER_SAVING = "overridePowerSaving";
@@ -73,8 +73,6 @@ public class FilesSyncJob extends Job {
@Override
protected Result onRunJob(@NonNull Params params) {
final Context context = MainApp.getAppContext();
final ContentResolver contentResolver = context.getContentResolver();
FileUploader.UploadRequester requester = new FileUploader.UploadRequester();
PowerManager.WakeLock wakeLock = null;
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
@@ -84,7 +82,6 @@ public class FilesSyncJob extends Job {
}
PersistableBundleCompat bundle = params.getExtras();
final boolean skipCustom = bundle.getBoolean(SKIP_CUSTOM, false);
final boolean overridePowerSaving = bundle.getBoolean(OVERRIDE_POWER_SAVING, false);
// If we are in power save mode, better to postpone upload
@@ -96,102 +93,24 @@ public class FilesSyncJob extends Job {
Resources resources = MainApp.getAppContext().getResources();
boolean lightVersion = resources.getBoolean(R.bool.syncedFolder_light);
final boolean skipCustom = bundle.getBoolean(SKIP_CUSTOM, false);
FilesSyncHelper.restartJobsIfNeeded();
FilesSyncHelper.insertAllDBEntries(skipCustom);
// Create all the providers we'll need
final ContentResolver contentResolver = context.getContentResolver();
final FilesystemDataProvider filesystemDataProvider = new FilesystemDataProvider(contentResolver);
SyncedFolderProvider syncedFolderProvider = new SyncedFolderProvider(contentResolver);
Locale currentLocale = context.getResources().getConfiguration().locale;
SimpleDateFormat sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss", currentLocale);
sFormatter.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
FileUploader.UploadRequester requester = new FileUploader.UploadRequester();
for (SyncedFolder syncedFolder : syncedFolderProvider.getSyncedFolders()) {
if ((syncedFolder.isEnabled()) && (!skipCustom || MediaFolderType.CUSTOM != syncedFolder.getType())) {
for (String path : filesystemDataProvider.getFilesForUpload(syncedFolder.getLocalPath(),
Long.toString(syncedFolder.getId()))) {
File file = new File(path);
Long lastModificationTime = file.lastModified();
final Locale currentLocale = context.getResources().getConfiguration().locale;
if (MediaFolderType.IMAGE == syncedFolder.getType()) {
String mimeTypeString = FileStorageUtils.getMimeTypeFromName(file.getAbsolutePath());
if ("image/jpeg".equalsIgnoreCase(mimeTypeString) || "image/tiff".
equalsIgnoreCase(mimeTypeString)) {
try {
ExifInterface exifInterface = new ExifInterface(file.getAbsolutePath());
String exifDate = exifInterface.getAttribute(ExifInterface.TAG_DATETIME);
if (!TextUtils.isEmpty(exifDate)) {
ParsePosition pos = new ParsePosition(0);
SimpleDateFormat sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss",
currentLocale);
sFormatter.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
Date dateTime = sFormatter.parse(exifDate, pos);
lastModificationTime = dateTime.getTime();
}
} catch (Exception e) {
Log_OC.d(TAG, "Failed to get the proper time " + e.getLocalizedMessage());
}
}
}
String mimeType = MimeTypeUtil.getBestMimeTypeByFilename(file.getAbsolutePath());
Account account = AccountUtils.getOwnCloudAccountByName(context, syncedFolder.getAccount());
String remotePath;
boolean subfolderByDate;
Integer uploadAction;
boolean needsCharging;
boolean needsWifi;
if (lightVersion) {
ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(
context.getContentResolver());
needsCharging = resources.getBoolean(R.bool.syncedFolder_light_on_charging);
needsWifi = account == null || arbitraryDataProvider.getBooleanValue(account.name,
Preferences.SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI);
String uploadActionString = resources.getString(R.string.syncedFolder_light_upload_behaviour);
uploadAction = getUploadAction(uploadActionString);
subfolderByDate = resources.getBoolean(R.bool.syncedFolder_light_use_subfolders);
remotePath = resources.getString(R.string.syncedFolder_remote_folder);
} else {
needsCharging = syncedFolder.getChargingOnly();
needsWifi = syncedFolder.getWifiOnly();
uploadAction = syncedFolder.getUploadAction();
subfolderByDate = syncedFolder.getSubfolderByDate();
remotePath = syncedFolder.getRemotePath();
}
if (!subfolderByDate) {
String adaptedPath = file.getAbsolutePath()
.replace(syncedFolder.getLocalPath(), "")
.replace("/" + file.getName(), "");
remotePath += adaptedPath;
}
requester.uploadFileWithOverwrite(
context,
account,
file.getAbsolutePath(),
FileStorageUtils.getInstantUploadFilePath(
currentLocale,
remotePath, file.getName(),
lastModificationTime, subfolderByDate),
uploadAction,
mimeType,
true, // create parent folder if not existent
UploadFileOperation.CREATED_AS_INSTANT_PICTURE,
needsWifi,
needsCharging,
true
);
filesystemDataProvider.updateFilesystemFileAsSentForUpload(path,
Long.toString(syncedFolder.getId()));
}
syncFolder(context, resources, lightVersion, filesystemDataProvider, currentLocale, sFormatter,
requester, syncedFolder);
}
}
@@ -202,6 +121,97 @@ public class FilesSyncJob extends Job {
return Result.SUCCESS;
}
private void syncFolder(Context context, Resources resources, boolean lightVersion,
FilesystemDataProvider filesystemDataProvider, Locale currentLocale,
SimpleDateFormat sFormatter, FileUploader.UploadRequester requester,
SyncedFolder syncedFolder) {
String remotePath;
boolean subfolderByDate;
Integer uploadAction;
boolean needsCharging;
boolean needsWifi;
Account account = AccountUtils.getOwnCloudAccountByName(context, syncedFolder.getAccount());
for (String path : filesystemDataProvider.getFilesForUpload(syncedFolder.getLocalPath(),
Long.toString(syncedFolder.getId()))) {
File file = new File(path);
Long lastModificationTime = calculateLastModificationTime(file, syncedFolder, sFormatter);
String mimeType = MimeTypeUtil.getBestMimeTypeByFilename(file.getAbsolutePath());
if (lightVersion) {
ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(
context.getContentResolver());
needsCharging = resources.getBoolean(R.bool.syncedFolder_light_on_charging);
needsWifi = account == null || arbitraryDataProvider.getBooleanValue(account.name,
Preferences.SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI);
String uploadActionString = resources.getString(R.string.syncedFolder_light_upload_behaviour);
uploadAction = getUploadAction(uploadActionString);
subfolderByDate = resources.getBoolean(R.bool.syncedFolder_light_use_subfolders);
remotePath = resources.getString(R.string.syncedFolder_remote_folder);
} else {
needsCharging = syncedFolder.getChargingOnly();
needsWifi = syncedFolder.getWifiOnly();
uploadAction = syncedFolder.getUploadAction();
subfolderByDate = syncedFolder.getSubfolderByDate();
remotePath = syncedFolder.getRemotePath();
}
if (!subfolderByDate) {
String adaptedPath = file.getAbsolutePath()
.replace(syncedFolder.getLocalPath(), "")
.replace("/" + file.getName(), "");
remotePath += adaptedPath;
}
requester.uploadFileWithOverwrite(
context,
account,
file.getAbsolutePath(),
FileStorageUtils.getInstantUploadFilePath(
currentLocale,
remotePath, file.getName(),
lastModificationTime, subfolderByDate),
uploadAction,
mimeType,
true, // create parent folder if not existent
UploadFileOperation.CREATED_AS_INSTANT_PICTURE,
needsWifi,
needsCharging,
true
);
filesystemDataProvider.updateFilesystemFileAsSentForUpload(path,
Long.toString(syncedFolder.getId()));
}
}
private Long calculateLastModificationTime(File file, SyncedFolder syncedFolder, SimpleDateFormat formatter) {
Long lastModificationTime = file.lastModified();
if (MediaFolderType.IMAGE == syncedFolder.getType()) {
String mimeTypeString = FileStorageUtils.getMimeTypeFromName(file.getAbsolutePath());
if (MimeType.JPEG.equalsIgnoreCase(mimeTypeString)
|| MimeType.TIFF.equalsIgnoreCase(mimeTypeString)) {
try {
ExifInterface exifInterface = new ExifInterface(file.getAbsolutePath());
String exifDate = exifInterface.getAttribute(ExifInterface.TAG_DATETIME);
if (!TextUtils.isEmpty(exifDate)) {
ParsePosition pos = new ParsePosition(0);
Date dateTime = formatter.parse(exifDate, pos);
lastModificationTime = dateTime.getTime();
}
} catch (Exception e) {
Log_OC.d(TAG, "Failed to get the proper time " + e.getLocalizedMessage());
}
}
}
return lastModificationTime;
}
private Integer getUploadAction(String action) {
switch (action) {
case "LOCAL_BEHAVIOUR_FORGET":
@@ -71,11 +71,10 @@ public class NotificationJob extends Job {
try {
byte[] base64DecodedSubject = Base64.decode(subject, Base64.DEFAULT);
byte[] base64DecodedSignature = Base64.decode(signature, Base64.DEFAULT);
PushUtils pushUtils = new PushUtils();
PrivateKey privateKey = (PrivateKey) PushUtils.readKeyFromFile(false);
try {
SignatureVerification signatureVerification = pushUtils.verifySignature(context,
SignatureVerification signatureVerification = PushUtils.verifySignature(context,
base64DecodedSignature, base64DecodedSubject);
if (signatureVerification.isSignatureValid()) {
@@ -100,10 +100,10 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
private static final float DUCK_VOLUME = 0.1f;
/** Media player instance */
private MediaPlayer mPlayer = null;
private MediaPlayer mPlayer;
/** Reference to the system AudioManager */
private AudioManager mAudioManager = null;
private AudioManager mAudioManager;
/** Values to indicate the state of the service */
@@ -426,9 +426,9 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
private void tryToGetAudioFocus() {
if (mAudioFocus != AudioFocus.FOCUS
&& mAudioManager != null
&& (AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAudioManager.requestAudioFocus(this,
&& AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAudioManager.requestAudioFocus(this,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN))
AudioManager.AUDIOFOCUS_GAIN)
) {
mAudioFocus = AudioFocus.FOCUS;
}
@@ -700,7 +700,7 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
}
protected void setMediaContoller(MediaControlView mediaController) {
protected void setMediaController(MediaControlView mediaController) {
mMediaController = mediaController;
}
@@ -734,7 +734,7 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
protected void onPostExecute(String url) {
MediaService mediaService = mediaServiceWeakReference.get();
if (mediaService != null) {
if (mediaService != null && mediaService.getCurrentFile() != null) {
if (url != null) {
try {
mediaService.mPlayer.setDataSource(url);
@@ -118,7 +118,7 @@ public class MediaServiceBinder extends Binder implements MediaController.MediaP
@Override
public boolean isPlaying() {
MediaService.State currentState = mService.getState();
return (currentState == State.PLAYING || (currentState == State.PREPARING && mService.mPlayOnPrepared));
return currentState == State.PLAYING || (currentState == State.PREPARING && mService.mPlayOnPrepared);
}
@@ -157,27 +157,25 @@ public class MediaServiceBinder extends Binder implements MediaController.MediaP
public void registerMediaController(MediaControlView mediaController) {
mService.setMediaContoller(mediaController);
mService.setMediaController(mediaController);
}
public void unregisterMediaController(MediaControlView mediaController) {
if (mediaController != null && mediaController == mService.getMediaController()) {
mService.setMediaContoller(null);
mService.setMediaController(null);
}
}
public boolean isInPlaybackState() {
MediaService.State currentState = mService.getState();
return (currentState == MediaService.State.PLAYING || currentState == MediaService.State.PAUSED);
return currentState == MediaService.State.PLAYING || currentState == MediaService.State.PAUSED;
}
@Override
public int getAudioSessionId() {
return 1; // not really used
}
}
@@ -1,4 +1,4 @@
/* ownCloud Android client application
/* ownCloud Android client application
* Copyright (C) 2012-2014 ownCloud Inc.
*
* This program is free software: you can redistribute it and/or modify
@@ -12,7 +12,6 @@
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.owncloud.android.operations;
@@ -36,10 +35,8 @@ public class CopyFileOperation extends SyncOperation {
private String mSrcPath;
private String mTargetParentPath;
private OCFile mFile;
/**
* Constructor
*
@@ -63,8 +60,6 @@ public class CopyFileOperation extends SyncOperation {
*/
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result;
/// 1. check copy validity
if (mTargetParentPath.startsWith(mSrcPath)) {
return new RemoteOperationResult(ResultCode.INVALID_COPY_INTO_DESCENDANT);
@@ -84,7 +79,8 @@ public class CopyFileOperation extends SyncOperation {
targetPath,
false
);
result = operation.execute(client);
RemoteOperationResult result = operation.execute(client);
/// 3. local copy
if (result.isSuccess()) {
@@ -94,6 +90,4 @@ public class CopyFileOperation extends SyncOperation {
return result;
}
}
@@ -154,21 +154,21 @@ public class DownloadFileOperation extends RemoteOperation {
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result;
File newFile;
boolean moved;
/// download will be performed to a temporal file, then moved to the final location
File tmpFile = new File(getTmpPath());
String tmpFolder = getTmpFolder();
/// perform the download
synchronized(mCancellationRequested) {
if (mCancellationRequested.get()) {
return new RemoteOperationResult(new OperationCancelledException());
}
}
RemoteOperationResult result;
File newFile;
boolean moved;
/// download will be performed to a temporal file, then moved to the final location
File tmpFile = new File(getTmpPath());
String tmpFolder = getTmpFolder();
mDownloadOperation = new DownloadRemoteFileOperation(mFile.getRemotePath(), tmpFolder);
Iterator<OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
@@ -49,7 +49,6 @@ public class GetServerInfoOperation extends RemoteOperation {
private String mUrl;
private Context mContext;
private ServerInfo mResultData;
/**
@@ -62,11 +61,9 @@ public class GetServerInfoOperation extends RemoteOperation {
public GetServerInfoOperation(String url, Context context) {
mUrl = trimWebdavSuffix(url);
mContext = context;
mResultData = new ServerInfo();
}
/**
* Performs the operation
*
@@ -143,10 +140,10 @@ public class GetServerInfoOperation extends RemoteOperation {
public static class ServerInfo {
public OwnCloudVersion mVersion = null;
public OwnCloudVersion mVersion;
public String mBaseUrl = "";
public AuthenticationMethod mAuthMethod = AuthenticationMethod.UNKNOWN;
public boolean mIsSslConn = false;
public boolean mIsSslConn;
}
}
@@ -1,4 +1,4 @@
/**
/*
* ownCloud Android client application
*
* @author David A. Velasco
@@ -15,7 +15,6 @@
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.owncloud.android.operations;
@@ -37,7 +36,6 @@ public class MoveFileOperation extends SyncOperation {
private String mSrcPath;
private String mTargetParentPath;
private OCFile mFile;
/**
@@ -63,8 +61,6 @@ public class MoveFileOperation extends SyncOperation {
*/
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result;
/// 1. check move validity
if (mTargetParentPath.startsWith(mSrcPath)) {
return new RemoteOperationResult(ResultCode.INVALID_MOVE_INTO_DESCENDANT);
@@ -84,7 +80,7 @@ public class MoveFileOperation extends SyncOperation {
targetPath,
false
);
result = operation.execute(client);
RemoteOperationResult result = operation.execute(client);
/// 3. local move
if (result.isSuccess()) {
@@ -37,9 +37,11 @@ import java.util.Map;
public class OAuth2GetAccessToken extends RemoteOperation {
private static final String TAG = OAuth2GetAccessToken.class.getSimpleName();
private static final int KEY_INDEX = 0;
private static final int VALUE_INDEX = 1;
private String mClientId;
private String mRedirectUri;
private String mGrantType;
@@ -149,9 +151,9 @@ public class OAuth2GetAccessToken extends RemoteOperation {
String[] part = pairs[i].split("=");
while (part.length > j) {
String p = part[j];
if (j == 0) {
if (j == KEY_INDEX) {
key = p;
} else if (j == 1) {
} else if (j == VALUE_INDEX) {
value = p;
mOAuth2ParsedAuthorizationResponse.put(key, value);
}
@@ -1,18 +1,18 @@
/**
/*
* ownCloud Android client application
*
* @author David A. Velasco
* Copyright (C) 2015 ownCloud Inc.
* <p>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
* <p>
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
@@ -39,6 +39,7 @@ import com.owncloud.android.lib.resources.files.ReadRemoteFolderOperation;
import com.owncloud.android.lib.resources.files.RemoteFile;
import com.owncloud.android.lib.resources.shares.GetRemoteSharesForFileOperation;
import com.owncloud.android.lib.resources.shares.OCShare;
import com.owncloud.android.lib.resources.shares.ShareType;
import com.owncloud.android.syncadapter.FileSyncAdapter;
import com.owncloud.android.utils.DataHolderUtil;
import com.owncloud.android.utils.EncryptionUtils;
@@ -344,7 +345,7 @@ public class RefreshFolderOperation extends RemoteOperation {
*
* @param folderAndFiles Remote folder and children files in Folder
*/
private void synchronizeData(ArrayList<Object> folderAndFiles) {
private void synchronizeData(List<Object> folderAndFiles) {
// get 'fresh data' from the database
mLocalFolder = mStorageManager.getFileByPath(mLocalFolder.getRemotePath());
@@ -362,6 +363,9 @@ public class RefreshFolderOperation extends RemoteOperation {
boolean encryptedAncestor = FileStorageUtils.checkEncryptionStatus(mLocalFolder, mStorageManager);
mLocalFolder.setEncrypted(encryptedAncestor);
// update permission
mLocalFolder.setPermissions(remoteFolder.getPermissions());
DecryptedFolderMetadata metadata = getDecryptedFolderMetadata(encryptedAncestor);
// get current data about local contents of the folder to synchronize
@@ -397,10 +401,9 @@ public class RefreshFolderOperation extends RemoteOperation {
// prepare content synchronization for kept-in-sync files
if (updatedFile.isAvailableOffline()) {
SynchronizeFileOperation operation = new SynchronizeFileOperation(localFile, remoteFile, mAccount, true,
mContext);
mFilesToSyncContents.add(operation);
mFilesToSyncContents.add(
new SynchronizeFileOperation(localFile, remoteFile, mAccount, true, mContext)
);
}
// update file name for encrypted files
@@ -550,8 +553,13 @@ public class RefreshFolderOperation extends RemoteOperation {
if (result.isSuccess()) {
// update local database
ArrayList<OCShare> shares = new ArrayList<>();
OCShare share;
for (Object obj : result.getData()) {
shares.add((OCShare) obj);
share = (OCShare) obj;
if (!ShareType.NO_SHARED.equals(share.getShareType())) {
shares.add(share);
}
}
mStorageManager.saveSharesInFolder(shares, mLocalFolder);
}
@@ -82,8 +82,7 @@ public class RenameFileOperation extends SyncOperation {
return new RemoteOperationResult(ResultCode.INVALID_LOCAL_FILE_NAME);
}
String parent = (new File(mFile.getRemotePath())).getParent();
parent = (parent.endsWith(OCFile.PATH_SEPARATOR)) ? parent : parent +
OCFile.PATH_SEPARATOR;
parent = parent.endsWith(OCFile.PATH_SEPARATOR) ? parent : parent + OCFile.PATH_SEPARATOR;
mNewRemotePath = parent + mNewName;
if (mFile.isFolder()) {
mNewRemotePath += OCFile.PATH_SEPARATOR;
@@ -50,8 +50,7 @@ public class SynchronizeFileOperation extends SyncOperation {
private Account mAccount;
private boolean mSyncFileContents;
private Context mContext;
private boolean mTransferWasRequested = false;
private boolean mTransferWasRequested;
/**
* When 'false', uploads to the server are not done; only downloads or conflict detection.
@@ -172,7 +172,6 @@ public class SynchronizeFolderOperation extends SyncOperation {
Log_OC.d(TAG, "Checking changes in " + mAccount.name + mRemotePath);
mRemoteFolderChanged = true;
RemoteOperationResult result;
if (mCancellationRequested.get()) {
throw new OperationCancelledException();
@@ -180,7 +179,7 @@ public class SynchronizeFolderOperation extends SyncOperation {
// remote request
ReadRemoteFileOperation operation = new ReadRemoteFileOperation(mRemotePath);
result = operation.execute(client);
RemoteOperationResult result = operation.execute(client);
if (result.isSuccess()) {
OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
@@ -261,8 +260,6 @@ public class SynchronizeFolderOperation extends SyncOperation {
* @param folderAndFiles Remote folder and children files in Folder
*/
private void synchronizeData(List<Object> folderAndFiles) throws OperationCancelledException {
FileDataStorageManager storageManager = getStorageManager();
// parse data from remote folder
OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) folderAndFiles.get(0));
remoteFolder.setParentId(mLocalFolder.getParentId());
@@ -271,7 +268,6 @@ public class SynchronizeFolderOperation extends SyncOperation {
Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath()
+ " changed - starting update of local data ");
List<OCFile> updatedFiles = new Vector<>(folderAndFiles.size() - 1);
mFilesForDirectDownload.clear();
mFilesToSyncContents.clear();
@@ -279,6 +275,9 @@ public class SynchronizeFolderOperation extends SyncOperation {
throw new OperationCancelledException();
}
FileDataStorageManager storageManager = getStorageManager();
List<OCFile> updatedFiles = new Vector<>(folderAndFiles.size() - 1);
// get current data about local contents of the folder to synchronize
List<OCFile> localFiles = storageManager.getFolderContent(mLocalFolder, false);
Map<String, OCFile> localFilesMap = new HashMap<>(localFiles.size());
@@ -43,7 +43,8 @@ import java.util.List;
public class UnshareOperation extends SyncOperation {
private static final String TAG = UnshareOperation.class.getSimpleName();
private static final int SINGLY_SHARED = 1;
private String mRemotePath;
private ShareType mShareType;
private String mShareWith;
@@ -83,7 +84,7 @@ public class UnshareOperation extends SyncOperation {
List <OCShare> sharesWith = getStorageManager().
getSharesWithForAFile(mRemotePath,
getStorageManager().getAccount().name);
if (sharesWith.size() == 1) {
if (sharesWith.size() == SINGLY_SHARED) {
file.setShareWithSharee(false);
}
}
@@ -48,14 +48,10 @@ public class UpdateShareViaLinkOperation extends SyncOperation {
* @param path Full path of the file/folder being shared. Mandatory argument
*/
public UpdateShareViaLinkOperation(String path) {
mPath = path;
mPassword = null;
mExpirationDateInMillis = 0;
mPublicUpload = null;
}
/**
* Set password to update in public link.
*
@@ -67,7 +63,6 @@ public class UpdateShareViaLinkOperation extends SyncOperation {
mPassword = password;
}
/**
* Set expiration date to update in Share resource.
*
@@ -90,7 +85,6 @@ public class UpdateShareViaLinkOperation extends SyncOperation {
mPublicUpload = publicUpload;
}
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
@@ -157,6 +151,5 @@ public class UpdateShareViaLinkOperation extends SyncOperation {
getStorageManager().saveFile(file);
}
}
}
@@ -127,7 +127,7 @@ public class UploadFileOperation extends SyncOperation {
/**
* Local path to file which is to be uploaded (before any possible renaming or moving).
*/
private String mOriginalStoragePath = null;
private String mOriginalStoragePath;
private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<>();
private OnRenameListener mRenameUploadListener;
@@ -138,7 +138,7 @@ public class UploadFileOperation extends SyncOperation {
private UploadRemoteFileOperation mUploadOperation;
protected RequestEntity mEntity = null;
protected RequestEntity mEntity;
private Account mAccount;
private OCUpload mUpload;
@@ -699,12 +699,10 @@ public class UploadFileOperation extends SyncOperation {
private RemoteOperationResult unlockFolder(OCFile parentFolder, OwnCloudClient client, String token) {
if (token != null) {
UnlockFileOperation unlockFileOperation = new UnlockFileOperation(parentFolder.getLocalId(), token);
RemoteOperationResult unlockFileOperationResult = unlockFileOperation.execute(client, true);
return unlockFileOperationResult;
} else
return new UnlockFileOperation(parentFolder.getLocalId(), token).execute(client, true);
} else {
return new RemoteOperationResult(new Exception("No token available"));
}
}
private RemoteOperationResult checkConditions(File originalFile) {
@@ -86,18 +86,20 @@ public class FileContentProvider extends ContentProvider {
private static final String ADD_COLUMN = " ADD COLUMN ";
private static final String REMOVE_COLUMN = " REMOVE COLUMN ";
private static final String UPGRADE_VERSION_MSG = "OUT of the ADD in onUpgrade; oldVersion == %d, newVersion == %d";
private static final int SINGLE_PATH_SEGMENT = 1;
public static final int ARBITRARY_DATA_TABLE_INTRODUCTION_VERSION = 20;
private DataBaseHelper mDbHelper;
private Context mContext;
private UriMatcher mUriMatcher;
@Override
public int delete(@NonNull Uri uri, String where, String[] whereArgs) {
int count;
if (isCallerNotAllowed()) {
return -1;
}
int count;
SQLiteDatabase db = mDbHelper.getWritableDatabase();
db.beginTransaction();
try {
@@ -110,95 +112,20 @@ public class FileContentProvider extends ContentProvider {
return count;
}
private int delete(SQLiteDatabase db, Uri uri, String where, String[] whereArgs) {
private int delete(SQLiteDatabase db, Uri uri, String where, String... whereArgs) {
if (isCallerNotAllowed()) {
return -1;
}
int count = 0;
int count;
switch (mUriMatcher.match(uri)) {
case SINGLE_FILE:
Cursor c = query(db, uri, null, where, whereArgs, null);
String remoteId = "";
try {
if (c != null && c.moveToFirst()) {
remoteId = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_REMOTE_ID));
//ThumbnailsCacheManager.removeFileFromCache(remoteId);
}
Log_OC.d(TAG, "Removing FILE " + remoteId);
count = db.delete(ProviderTableMeta.FILE_TABLE_NAME,
ProviderTableMeta._ID
+ "="
+ uri.getPathSegments().get(1)
+ (!TextUtils.isEmpty(where) ? " AND (" + where + ")" : ""),
whereArgs);
} catch (Exception e) {
Log_OC.d(TAG, "DB-Error removing file!", e);
} finally {
if (c != null) {
c.close();
}
}
count = deleteSingleFile(db, uri, where, whereArgs);
break;
case DIRECTORY:
// deletion of folder is recursive
/*
Uri folderUri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, Long.parseLong(uri.getPathSegments().get(1)));
Cursor folder = query(db, folderUri, null, null, null, null);
String folderName = "(unknown)";
if (folder != null && folder.moveToFirst()) {
folderName = folder.getString(folder.getColumnIndex(ProviderTableMeta.FILE_PATH));
}
*/
Cursor children = query(uri, null, null, null, null);
if (children != null) {
if (children.moveToFirst()) {
long childId;
boolean isDir;
while (!children.isAfterLast()) {
childId = children.getLong(children.getColumnIndex(ProviderTableMeta._ID));
isDir = MimeType.DIRECTORY.equals(children.getString(
children.getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)
));
//remotePath = children.getString(children.getColumnIndex(ProviderTableMeta.FILE_PATH));
if (isDir) {
count += delete(
db,
ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, childId),
null,
null
);
} else {
count += delete(
db,
ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, childId),
null,
null
);
}
children.moveToNext();
}
}
children.close();
} /*else {
Log_OC.d(TAG, "No child to remove in DIRECTORY " + folderName);
}
Log_OC.d(TAG, "Removing DIRECTORY " + folderName + " (or maybe not) ");
*/
count += db.delete(ProviderTableMeta.FILE_TABLE_NAME,
ProviderTableMeta._ID
+ "="
+ uri.getPathSegments().get(1)
+ (!TextUtils.isEmpty(where) ? " AND (" + where
+ ")" : ""), whereArgs);
/* Just for log
if (folder != null) {
folder.close();
}*/
count = deleteDirectory(db, uri, where, whereArgs);
break;
case ROOT_DIRECTORY:
//Log_OC.d(TAG, "Removing ROOT!");
count = db.delete(ProviderTableMeta.FILE_TABLE_NAME, where, whereArgs);
break;
case SHARES:
@@ -226,9 +153,82 @@ public class FileContentProvider extends ContentProvider {
count = db.delete(ProviderTableMeta.FILESYSTEM_TABLE_NAME, where, whereArgs);
break;
default:
//Log_OC.e(TAG, "Unknown uri " + uri);
throw new IllegalArgumentException("Unknown uri: " + uri.toString());
}
return count;
}
private int deleteDirectory(SQLiteDatabase db, Uri uri, String where, String... whereArgs) {
int count = 0;
Cursor children = query(uri, null, null, null, null);
if (children != null) {
if (children.moveToFirst()) {
long childId;
boolean isDir;
while (!children.isAfterLast()) {
childId = children.getLong(children.getColumnIndex(ProviderTableMeta._ID));
isDir = MimeType.DIRECTORY.equals(children.getString(
children.getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)
));
//remotePath = children.getString(children.getColumnIndex(ProviderTableMeta.FILE_PATH));
if (isDir) {
count += delete(
db,
ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, childId),
null,
(String[]) null
);
} else {
count += delete(
db,
ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, childId),
null,
(String[]) null
);
}
children.moveToNext();
}
}
children.close();
}
count += db.delete(ProviderTableMeta.FILE_TABLE_NAME,
ProviderTableMeta._ID
+ "="
+ uri.getPathSegments().get(1)
+ (!TextUtils.isEmpty(where) ? " AND (" + where
+ ")" : ""), whereArgs);
return count;
}
private int deleteSingleFile(SQLiteDatabase db, Uri uri, String where, String... whereArgs) {
int count = 0;
Cursor c = query(db, uri, null, where, whereArgs, null);
String remoteId = "";
try {
if (c != null && c.moveToFirst()) {
remoteId = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_REMOTE_ID));
//ThumbnailsCacheManager.removeFileFromCache(remoteId);
}
Log_OC.d(TAG, "Removing FILE " + remoteId);
count = db.delete(ProviderTableMeta.FILE_TABLE_NAME,
ProviderTableMeta._ID
+ "="
+ uri.getPathSegments().get(1)
+ (!TextUtils.isEmpty(where) ? " AND (" + where + ")" : ""),
whereArgs);
} catch (Exception e) {
Log_OC.d(TAG, "DB-Error removing file!", e);
} finally {
if (c != null) {
c.close();
}
}
return count;
}
@@ -504,67 +504,66 @@ public class FileContentProvider extends ContentProvider {
case ROOT_DIRECTORY:
break;
case DIRECTORY:
String folderId = uri.getPathSegments().get(1);
sqlQuery.appendWhere(ProviderTableMeta.FILE_PARENT + "="
+ folderId);
+ uri.getPathSegments().get(1));
break;
case SINGLE_FILE:
if (uri.getPathSegments().size() > 1) {
if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {
sqlQuery.appendWhere(ProviderTableMeta._ID + "="
+ uri.getPathSegments().get(1));
}
break;
case SHARES:
sqlQuery.setTables(ProviderTableMeta.OCSHARES_TABLE_NAME);
if (uri.getPathSegments().size() > 1) {
if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {
sqlQuery.appendWhere(ProviderTableMeta._ID + "="
+ uri.getPathSegments().get(1));
}
break;
case CAPABILITIES:
sqlQuery.setTables(ProviderTableMeta.CAPABILITIES_TABLE_NAME);
if (uri.getPathSegments().size() > 1) {
if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {
sqlQuery.appendWhere(ProviderTableMeta._ID + "="
+ uri.getPathSegments().get(1));
}
break;
case UPLOADS:
sqlQuery.setTables(ProviderTableMeta.UPLOADS_TABLE_NAME);
if (uri.getPathSegments().size() > 1) {
if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {
sqlQuery.appendWhere(ProviderTableMeta._ID + "="
+ uri.getPathSegments().get(1));
}
break;
case SYNCED_FOLDERS:
sqlQuery.setTables(ProviderTableMeta.SYNCED_FOLDERS_TABLE_NAME);
if (uri.getPathSegments().size() > 1) {
if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {
sqlQuery.appendWhere(ProviderTableMeta._ID + "="
+ uri.getPathSegments().get(1));
}
break;
case EXTERNAL_LINKS:
sqlQuery.setTables(ProviderTableMeta.EXTERNAL_LINKS_TABLE_NAME);
if (uri.getPathSegments().size() > 1) {
if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {
sqlQuery.appendWhere(ProviderTableMeta._ID + "="
+ uri.getPathSegments().get(1));
}
break;
case ARBITRARY_DATA:
sqlQuery.setTables(ProviderTableMeta.ARBITRARY_DATA_TABLE_NAME);
if (uri.getPathSegments().size() > 1) {
if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {
sqlQuery.appendWhere(ProviderTableMeta._ID + "="
+ uri.getPathSegments().get(1));
}
break;
case VIRTUAL:
sqlQuery.setTables(ProviderTableMeta.VIRTUAL_TABLE_NAME);
if (uri.getPathSegments().size() > 1) {
if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {
sqlQuery.appendWhere(ProviderTableMeta._ID + "=" + uri.getPathSegments().get(1));
}
break;
case FILESYSTEM:
sqlQuery.setTables(ProviderTableMeta.FILESYSTEM_TABLE_NAME);
if (uri.getPathSegments().size() > 1) {
if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {
sqlQuery.appendWhere(ProviderTableMeta._ID + "="
+ uri.getPathSegments().get(1));
}
@@ -654,13 +653,12 @@ public class FileContentProvider extends ContentProvider {
return count;
}
private int update(
SQLiteDatabase db,
Uri uri,
ContentValues values,
String selection,
String[] selectionArgs
String... selectionArgs
) {
switch (mUriMatcher.match(uri)) {
case DIRECTORY:
@@ -1633,7 +1631,7 @@ public class FileContentProvider extends ContentProvider {
db.execSQL(ALTER_TABLE + ProviderTableMeta.FILE_TABLE_NAME +
ADD_COLUMN + ProviderTableMeta.FILE_ENCRYPTED_NAME + " TEXT ");
}
if (oldVersion > 20) {
if (oldVersion > ARBITRARY_DATA_TABLE_INTRODUCTION_VERSION) {
if (!checkIfColumnExists(db, ProviderTableMeta.CAPABILITIES_TABLE_NAME,
ProviderTableMeta.CAPABILITIES_END_TO_END_ENCRYPTION)) {
db.execSQL(ALTER_TABLE + ProviderTableMeta.CAPABILITIES_TABLE_NAME +
@@ -1,4 +1,4 @@
/**
/*
* ownCloud Android client application
*
* @author David A. Velasco
@@ -18,7 +18,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.providers;
import android.accounts.Account;
@@ -32,6 +31,7 @@ import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.provider.BaseColumns;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.widget.Toast;
@@ -52,6 +52,7 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
@@ -84,7 +85,7 @@ public class UsersAndGroupsSearchProvider extends ContentProvider {
private UriMatcher mUriMatcher;
private static HashMap<String, ShareType> sShareTypes = new HashMap<>();
private static Map<String, ShareType> sShareTypes = new HashMap<>();
public static ShareType getShareType(String authority) {
@@ -93,7 +94,7 @@ public class UsersAndGroupsSearchProvider extends ContentProvider {
@Nullable
@Override
public String getType(Uri uri) {
public String getType(@NonNull Uri uri) {
// TODO implement
return null;
}
@@ -119,7 +120,7 @@ public class UsersAndGroupsSearchProvider extends ContentProvider {
/**
* TODO description
* <p/>
*
* Reference: http://developer.android.com/guide/topics/search/adding-custom-suggestions.html#CustomContentProvider
*
* @param uri Content {@link Uri}, formattted as
@@ -133,7 +134,7 @@ public class UsersAndGroupsSearchProvider extends ContentProvider {
*/
@Nullable
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Log_OC.d(TAG, "query received in thread " + Thread.currentThread().getName());
int match = mUriMatcher.match(uri);
@@ -240,19 +241,19 @@ public class UsersAndGroupsSearchProvider extends ContentProvider {
@Nullable
@Override
public Uri insert(Uri uri, ContentValues values) {
public Uri insert(@NonNull Uri uri, ContentValues values) {
// TODO implementation
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
public int delete(@NonNull Uri uri, String selection, String[] selectionArgs) {
// TODO implementation
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
public int update(@NonNull Uri uri, ContentValues values, String selection, String[] selectionArgs) {
// TODO implementation
return 0;
}
@@ -283,5 +284,4 @@ public class UsersAndGroupsSearchProvider extends ContentProvider {
}
});
}
}
@@ -0,0 +1,45 @@
/*
* Nextcloud SingleSignOn
*
* @author David Luhmer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.services;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import com.nextcloud.android.sso.InputStreamBinder;
public class AccountManagerService extends Service {
private InputStreamBinder mBinder;
@Override
public IBinder onBind(Intent intent) {
if(mBinder == null) {
mBinder = new InputStreamBinder(this);
}
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
}
@@ -269,10 +269,9 @@ public class OperationsService extends Service {
* Map of listeners that will be reported about the end of operations from a
* {@link OperationsServiceBinder} instance
*/
private final ConcurrentMap<OnRemoteOperationListener, Handler> mBoundListeners =
new ConcurrentHashMap<OnRemoteOperationListener, Handler>();
private final ConcurrentMap<OnRemoteOperationListener, Handler> mBoundListeners = new ConcurrentHashMap<>();
private ServiceHandler mServiceHandler = null;
private ServiceHandler mServiceHandler;
public OperationsServiceBinder(ServiceHandler serviceHandler) {
mServiceHandler = serviceHandler;
@@ -355,7 +354,6 @@ public class OperationsService extends Service {
}
}
public boolean dispatchResultIfFinished(int operationId,
OnRemoteOperationListener listener) {
Pair<RemoteOperation, RemoteOperationResult> undispatched =
@@ -363,13 +361,11 @@ public class OperationsService extends Service {
if (undispatched != null) {
listener.onRemoteOperationFinish(undispatched.first, undispatched.second);
return true;
//Log_OC.e(TAG, "Sending callback later");
} else {
return (!mServiceHandler.mPendingOperations.isEmpty());
return !mServiceHandler.mPendingOperations.isEmpty();
}
}
/**
* Returns True when the file described by 'file' in the ownCloud account 'account' is
* downloading or waiting to download.
@@ -402,10 +398,10 @@ public class OperationsService extends Service {
private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations =
new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
private RemoteOperation mCurrentOperation = null;
private Target mLastTarget = null;
private OwnCloudClient mOwnCloudClient = null;
new ConcurrentLinkedQueue<>();
private RemoteOperation mCurrentOperation;
private Target mLastTarget;
private OwnCloudClient mOwnCloudClient;
private FileDataStorageManager mStorageManager;
@@ -423,7 +419,6 @@ public class OperationsService extends Service {
Log_OC.d(TAG, "Stopping after command with id " + msg.arg1);
mService.stopSelf(msg.arg1);
}
/**
* Performs the next operation in the queue
@@ -141,9 +141,6 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
SyncResult syncResult) {
mCancellation = false;
/* When 'true' the process was requested by the user through the user interface;
when 'false', it was requested automatically by the system */
boolean mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
mFailedResultsCounter = 0;
mLastFailedResult = null;
mConflictsFound = 0;
@@ -170,7 +167,10 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
sendLocalBroadcast(EVENT_FULL_SYNC_START, null, null); // message to signal the start
// of the synchronization to the UI
/* When 'true' the process was requested by the user through the user interface;
when 'false', it was requested automatically by the system */
boolean mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
try {
updateOCVersion();
mCurrentSyncTime = System.currentTimeMillis();
@@ -182,7 +182,6 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
"because cancellation request");
}
} finally {
// it's important making this although very unexpected errors occur;
// that's the reason for the finally
@@ -316,12 +315,12 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
* synchronization
*/
private boolean isFinisher(RemoteOperationResult failedResult) {
if (failedResult != null) {
if (failedResult != null) {
RemoteOperationResult.ResultCode code = failedResult.getCode();
return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||
code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||
code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||
code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));
return code.equals(RemoteOperationResult.ResultCode.SSL_ERROR)
|| code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)
|| code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION)
|| code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
}
return false;
}
@@ -522,8 +521,8 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
* @param builder
*/
private void showNotification(int id, NotificationCompat.Builder builder) {
NotificationManager notificationManager = ((NotificationManager) getContext().
getSystemService(Context.NOTIFICATION_SERVICE));
NotificationManager notificationManager = (NotificationManager) getContext().
getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
builder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_FILE_SYNC);
@@ -36,7 +36,7 @@ public class ExtendedListView extends ListView {
private static final String TAG = ExtendedListView.class.getSimpleName();
private int mPositionToSetAndCenter = 0;
private int mPositionToSetAndCenter;
public ExtendedListView(Context context) {
super(context);
@@ -38,7 +38,6 @@ import com.owncloud.android.utils.ThemeUtils;
/**
* Themeable switch preference
*/
public class ThemeableSwitchPreference extends SwitchPreference {
public ThemeableSwitchPreference(Context context) {
@@ -64,24 +63,31 @@ public class ThemeableSwitchPreference extends SwitchPreference {
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
private void findSwitch(ViewGroup viewGroup) {
ColorStateList thumbColorStateList = null;
ColorStateList trackColorStateList = null;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View child = viewGroup.getChildAt(i);
if (child instanceof Switch) {
Switch switchView = (Switch) child;
int color = ThemeUtils.primaryAccentColor(getContext());
int trackColor = Color.argb(77, Color.red(color), Color.green(color), Color.blue(color));
if(thumbColorStateList == null && trackColorStateList == null) {
int color = ThemeUtils.primaryAccentColor(getContext());
int trackColor = Color.argb(77, Color.red(color), Color.green(color), Color.blue(color));
thumbColorStateList = new ColorStateList(
new int[][]{new int[]{android.R.attr.state_checked}, new int[]{}},
new int[]{color, Color.WHITE});
trackColorStateList = new ColorStateList(
new int[][]{new int[]{android.R.attr.state_checked}, new int[]{}},
new int[]{trackColor, Color.parseColor("#4D000000")});
}
// setting the thumb color
DrawableCompat.setTintList(switchView.getThumbDrawable(), new ColorStateList(
new int[][]{new int[]{android.R.attr.state_checked}, new int[]{}},
new int[]{color, Color.WHITE}));
DrawableCompat.setTintList(switchView.getThumbDrawable(), thumbColorStateList);
// setting the track color
DrawableCompat.setTintList(switchView.getTrackDrawable(), new ColorStateList(
new int[][]{new int[]{android.R.attr.state_checked}, new int[]{}},
new int[]{trackColor, Color.parseColor("#4D000000")}));
DrawableCompat.setTintList(switchView.getTrackDrawable(), trackColorStateList);
break;
} else if (child instanceof ViewGroup) {
@@ -1,4 +1,4 @@
/**
/*
* Nextcloud Android client application
*
* Copyright (C) 2018 Edvard Holst
@@ -34,6 +34,8 @@ import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.activities.GetRemoteActivitiesOperation;
import org.apache.commons.httpclient.HttpStatus;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@@ -94,7 +96,7 @@ public class ActivitiesServiceApiImpl implements ActivitiesServiceApi {
Log_OC.d(TAG, result.getLogMessage());
// show error
errorMessage = result.getLogMessage();
if (result.getHttpCode() == 304) {
if (result.getHttpCode() == HttpStatus.SC_NOT_MODIFIED) {
errorMessage = context.getString(R.string.file_list_empty_headline_server_search);
}
return false;
@@ -663,7 +663,7 @@ public abstract class DrawerActivity extends ToolbarActivity implements DisplayU
*
* @param accounts list of accounts
*/
private void repopulateAccountList(ArrayList<Account> accounts) {
private void repopulateAccountList(List<Account> accounts) {
// remove all accounts from list
mNavigationView.getMenu().removeGroup(R.id.drawer_menu_accounts);
@@ -946,13 +946,13 @@ public abstract class DrawerActivity extends ToolbarActivity implements DisplayU
Thread t = new Thread(new Runnable() {
public void run() {
Context context = MainApp.getAppContext();
AccountManager mAccountMgr = AccountManager.get(context);
Account account = AccountUtils.getCurrentOwnCloudAccount(context);
if (account == null) {
return;
}
AccountManager mAccountMgr = AccountManager.get(context);
String userId = mAccountMgr.getUserData(account,
com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID);
@@ -24,6 +24,7 @@ package com.owncloud.android.ui.activity;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorException;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -77,14 +78,13 @@ import com.owncloud.android.utils.ErrorMessageAdapter;
import com.owncloud.android.utils.FilesSyncHelper;
import com.owncloud.android.utils.ThemeUtils;
import java.util.concurrent.ExecutionException;
/**
* Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
*/
public abstract class FileActivity extends DrawerActivity
implements OnRemoteOperationListener, ComponentsGetter, SslUntrustedCertDialog.OnSslUntrustedCertListener {
implements OnRemoteOperationListener, ComponentsGetter, SslUntrustedCertDialog.OnSslUntrustedCertListener,
LoadingVersionNumberTask.VersionDevInterface {
public static final String EXTRA_FILE = "com.owncloud.android.ui.activity.FILE";
public static final String EXTRA_ACCOUNT = "com.owncloud.android.ui.activity.ACCOUNT";
@@ -596,45 +596,51 @@ public abstract class FileActivity extends DrawerActivity
int count = arbitraryDataProvider.getIntegerValue(FilesSyncHelper.GLOBAL, APP_OPENED_COUNT);
if (count > 10 || count == -1) {
checkForNewDevVersion(view, context, false);
checkForNewDevVersion(this, context);
}
}
}
public static void checkForNewDevVersion(View view, Context context, boolean openDirectly) {
Integer latestVersion = -1;
@Override
public void returnVersion(Integer latestVersion) {
showDevSnackbar(this, latestVersion, false);
}
public static void checkForNewDevVersion(LoadingVersionNumberTask.VersionDevInterface callback, Context context) {
String url = context.getString(R.string.dev_latest);
LoadingVersionNumberTask loadTask = new LoadingVersionNumberTask(callback);
loadTask.execute(url);
}
public static void showDevSnackbar(Activity activity, Integer latestVersion, boolean openDirectly) {
Integer currentVersion = -1;
try {
currentVersion = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
String url = context.getString(R.string.dev_latest);
LoadingVersionNumberTask loadTask = new LoadingVersionNumberTask();
loadTask.execute(url);
latestVersion = loadTask.get();
} catch (InterruptedException | ExecutionException | PackageManager.NameNotFoundException e) {
Log_OC.e(TAG, "Error detecting app version", e);
currentVersion = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
Log_OC.e(TAG, "Package not found", e);
}
if (latestVersion == -1 || currentVersion == -1) {
Snackbar.make(view, R.string.dev_version_no_information_available, Snackbar.LENGTH_LONG).show();
DisplayUtils.showSnackMessage(activity, R.string.dev_version_no_information_available, Snackbar.LENGTH_LONG);
}
if (latestVersion > currentVersion) {
if (openDirectly) {
String devApkLink = (String) context.getText(R.string.dev_link) + latestVersion + ".apk";
String devApkLink = (String) activity.getText(R.string.dev_link) + latestVersion + ".apk";
Uri uriUrl = Uri.parse(devApkLink);
Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
context.startActivity(intent);
activity.startActivity(intent);
} else {
Integer finalLatestVersion = latestVersion;
Snackbar.make(view, R.string.dev_version_new_version_available, Snackbar.LENGTH_LONG)
.setAction(context.getString(R.string.version_dev_download), v -> {
String devApkLink = (String) context.getText(R.string.dev_link)
+ finalLatestVersion + ".apk";
Snackbar.make(activity.findViewById(android.R.id.content), R.string.dev_version_new_version_available,
Snackbar.LENGTH_LONG)
.setAction(activity.getString(R.string.version_dev_download), v -> {
String devApkLink = (String) activity.getText(R.string.dev_link) + latestVersion + ".apk";
Uri uriUrl = Uri.parse(devApkLink);
Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
context.startActivity(intent);
activity.startActivity(intent);
}).show();
}
} else {
Snackbar.make(view, R.string.dev_version_no_new_version_available, Snackbar.LENGTH_LONG).show();
DisplayUtils.showSnackMessage(activity, R.string.dev_version_no_new_version_available, Snackbar.LENGTH_LONG);
}
}
}
@@ -86,6 +86,7 @@ import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCo
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.shares.OCShare;
import com.owncloud.android.lib.resources.shares.ShareType;
import com.owncloud.android.lib.resources.status.OCCapability;
import com.owncloud.android.lib.resources.status.OwnCloudVersion;
import com.owncloud.android.media.MediaService;
import com.owncloud.android.media.MediaServiceBinder;
@@ -123,6 +124,7 @@ import com.owncloud.android.ui.preview.PreviewImageFragment;
import com.owncloud.android.ui.preview.PreviewMediaFragment;
import com.owncloud.android.ui.preview.PreviewTextFragment;
import com.owncloud.android.ui.preview.PreviewVideoActivity;
import com.owncloud.android.utils.ClipboardUtil;
import com.owncloud.android.utils.DataHolderUtil;
import com.owncloud.android.utils.DisplayUtils;
import com.owncloud.android.utils.ErrorMessageAdapter;
@@ -190,6 +192,8 @@ public class FileDisplayActivity extends HookActivity
public static final String TEXT_PREVIEW = "TEXT_PREVIEW";
private static final String VERSION_DOT = ".";
private OCFile mWaitingToPreview;
private boolean mSyncInProgress;
@@ -276,9 +280,7 @@ public class FileDisplayActivity extends HookActivity
PermissionUtil.requestWriteExternalStoreagePermission(FileDisplayActivity.this);
}
});
ThemeUtils.colorSnackbar(this, snackbar);
snackbar.show();
} else {
// No explanation needed, request the permission.
@@ -366,8 +368,14 @@ public class FileDisplayActivity extends HookActivity
if (MainApp.getVersionCode() > lastSeenVersion) {
OwnCloudVersion serverVersion = AccountUtils.getServerVersionForAccount(account, this);
if (serverVersion == null) {
OCCapability capability = getCapabilities();
serverVersion = new OwnCloudVersion(capability.getVersionMayor() + VERSION_DOT +
capability.getVersionMinor() + VERSION_DOT + capability.getVersionMicro());
}
if (serverVersion.compareTo(MainApp.OUTDATED_SERVER_VERSION) < 0) {
if (MainApp.OUTDATED_SERVER_VERSION.compareTo(serverVersion) >= 0) {
DisplayUtils.showServerOutdatedSnackbar(this);
}
@@ -705,8 +713,8 @@ public class FileDisplayActivity extends HookActivity
protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath,
boolean success) {
FileFragment secondFragment = getSecondFragment();
boolean waitedPreview = (mWaitingToPreview != null &&
mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
boolean waitedPreview = mWaitingToPreview != null
&& mWaitingToPreview.getRemotePath().equals(downloadedRemotePath);
if (secondFragment instanceof FileDetailFragment) {
FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
OCFile fileInFragment = detailsFragment.getFile();
@@ -746,7 +754,7 @@ public class FileDisplayActivity extends HookActivity
mWaitingToPreview = null;
}
if (!detailsFragmentChanged) {
detailsFragment.updateFileDetails(false, (success));
detailsFragment.updateFileDetails(false, success);
}
}
}
@@ -1498,12 +1506,8 @@ public class FileDisplayActivity extends HookActivity
// TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
private boolean isAscendant(String linkedToRemotePath) {
OCFile currentDir = getCurrentDir();
return (
currentDir != null &&
currentDir.getRemotePath().startsWith(linkedToRemotePath)
);
return currentDir != null && currentDir.getRemotePath().startsWith(linkedToRemotePath);
}
}
@@ -1907,9 +1911,6 @@ public class FileDisplayActivity extends HookActivity
if (result.isSuccess()) {
updateFileFromDB();
// Create dialog to allow the user choose an app to send the link
Intent intentToShareLink = new Intent(Intent.ACTION_SEND);
// if share to user and share via link multiple ocshares are returned,
// therefore filtering for public_link
String link = "";
@@ -1921,43 +1922,7 @@ public class FileDisplayActivity extends HookActivity
}
}
intentToShareLink.putExtra(Intent.EXTRA_TEXT, link);
intentToShareLink.setType("text/plain");
String username;
try {
OwnCloudAccount oca = new OwnCloudAccount(getAccount(), this);
if (oca.getDisplayName() != null && !oca.getDisplayName().isEmpty()) {
username = oca.getDisplayName();
} else {
username = AccountUtils.getUsernameForAccount(getAccount());
}
} catch (Exception e) {
username = AccountUtils.getUsernameForAccount(getAccount());
}
if (username != null) {
intentToShareLink.putExtra(
Intent.EXTRA_SUBJECT,
getString(
R.string.subject_user_shared_with_you,
username,
getFile().getFileName()
)
);
} else {
intentToShareLink.putExtra(
Intent.EXTRA_SUBJECT,
getString(
R.string.subject_shared_with_you,
getFile().getFileName()
)
);
}
String[] packagesToExclude = new String[]{getPackageName()};
DialogFragment chooserDialog = ShareLinkToDialog.newInstance(intentToShareLink, packagesToExclude);
chooserDialog.show(getSupportFragmentManager(), FTAG_CHOOSER_DIALOG);
copyAndShareFileLink(link);
if (fileDetailFragment != null && fileDetailFragment.getFileDetailSharingFragment() != null) {
fileDetailFragment.getFileDetailSharingFragment().refreshPublicShareFromDB();
@@ -1983,15 +1948,71 @@ public class FileDisplayActivity extends HookActivity
if (fileDetailFragment != null && fileDetailFragment.getFileDetailSharingFragment() != null) {
fileDetailFragment.getFileDetailSharingFragment().refreshPublicShareFromDB();
}
Snackbar.make(
Snackbar snackbar = Snackbar.make(
findViewById(android.R.id.content),
ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
Snackbar.LENGTH_LONG
).show();
);
ThemeUtils.colorSnackbar(this, snackbar);
snackbar.show();
}
}
}
private void copyAndShareFileLink(String link) {
ClipboardUtil.copyToClipboard(this, link, false);
Snackbar snackbar = Snackbar.make(
findViewById(android.R.id.content),
R.string.clipboard_text_copied,
Snackbar.LENGTH_LONG
).setAction(R.string.share, v -> showShareLinkDialog(link));
ThemeUtils.colorSnackbar(this, snackbar);
snackbar.show();
}
public void showShareLinkDialog(String link) {
// Create dialog to allow the user choose an app to send the link
Intent intentToShareLink = new Intent(Intent.ACTION_SEND);
intentToShareLink.putExtra(Intent.EXTRA_TEXT, link);
intentToShareLink.setType("text/plain");
String username;
try {
OwnCloudAccount oca = new OwnCloudAccount(getAccount(), this);
if (oca.getDisplayName() != null && !oca.getDisplayName().isEmpty()) {
username = oca.getDisplayName();
} else {
username = AccountUtils.getUsernameForAccount(getAccount());
}
} catch (Exception e) {
username = AccountUtils.getUsernameForAccount(getAccount());
}
if (username != null) {
intentToShareLink.putExtra(
Intent.EXTRA_SUBJECT,
getString(
R.string.subject_user_shared_with_you,
username,
getFile().getFileName()
)
);
} else {
intentToShareLink.putExtra(
Intent.EXTRA_SUBJECT,
getString(
R.string.subject_shared_with_you,
getFile().getFileName()
)
);
}
String[] packagesToExclude = new String[]{getPackageName()};
DialogFragment chooserDialog = ShareLinkToDialog.newInstance(intentToShareLink, packagesToExclude);
chooserDialog.show(getSupportFragmentManager(), FTAG_CHOOSER_DIALOG);
}
private void onUpdateShareInformation(RemoteOperationResult result, @StringRes int errorString) {
Fragment fileDetailFragment = getSecondFragment();
@@ -1999,7 +2020,9 @@ public class FileDisplayActivity extends HookActivity
updateFileFromDB();
refreshListOfFilesFragment(false);
} else if (fileDetailFragment.getView() != null) {
Snackbar.make(fileDetailFragment.getView(), errorString, Snackbar.LENGTH_LONG).show();
Snackbar snackbar = Snackbar.make(fileDetailFragment.getView(), errorString, Snackbar.LENGTH_LONG);
ThemeUtils.colorSnackbar(this, snackbar);
snackbar.show();
}
if (fileDetailFragment != null && fileDetailFragment instanceof FileDetailFragment) {
@@ -163,6 +163,13 @@ public class FirstRunActivity extends BaseActivity implements ViewPager.OnPageCh
PreferenceManager.setLastSeenVersionCode(this, MainApp.getVersionCode());
}
@Override
protected void onStop() {
onFinish();
super.onStop();
}
private static boolean isFirstRun(Context context) {
return AccountUtils.getCurrentOwnCloudAccount(context) == null;
}
@@ -209,10 +216,21 @@ public class FirstRunActivity extends BaseActivity implements ViewPager.OnPageCh
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (FIRST_RUN_RESULT_CODE == requestCode && RESULT_OK == resultCode) {
setAccount(AccountUtils.getCurrentOwnCloudAccount(this));
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
Account account = AccountUtils.getOwnCloudAccountByName(this, accountName);
if (account == null) {
DisplayUtils.showSnackMessage(this, R.string.account_creation_failed);
return;
}
setAccount(account);
AccountUtils.setCurrentOwnCloudAccount(this, account.name);
onAccountSet(false);
Intent i = new Intent(this, FileDisplayActivity.class);
i.setAction(FileDisplayActivity.RESTART);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
@@ -74,15 +74,17 @@ import java.util.Set;
public class ManageAccountsActivity extends FileActivity
implements AccountListAdapter.AccountListAdapterListener, AccountManagerCallback<Boolean>, ComponentsGetter {
private static final String TAG = ManageAccountsActivity.class.getSimpleName();
public static final String KEY_ACCOUNT_LIST_CHANGED = "ACCOUNT_LIST_CHANGED";
public static final String KEY_CURRENT_ACCOUNT_CHANGED = "CURRENT_ACCOUNT_CHANGED";
public static final String PENDING_FOR_REMOVAL = "PENDING_FOR_REMOVAL";
private static final String KEY_DISPLAY_NAME = "DISPLAY_NAME";
private static final int KEY_USER_INFO_REQUEST_CODE = 13;
private static final int KEY_DELETE_CODE = 101;
private static final int SINGLE_ACCOUNT = 1;
private static final int MIN_MULTI_ACCOUNT_SIZE = 2;
private ListView mListView;
private final Handler mHandler = new Handler();
@@ -90,8 +92,8 @@ public class ManageAccountsActivity extends FileActivity
private AccountListAdapter mAccountListAdapter;
private ServiceConnection mDownloadServiceConnection;
private ServiceConnection mUploadServiceConnection;
Set<String> mOriginalAccounts;
String mOriginalCurrentAccount;
private Set<String> mOriginalAccounts;
private String mOriginalCurrentAccount;
private Drawable mTintedCheck;
private ArbitraryDataProvider arbitraryDataProvider;
@@ -347,7 +349,7 @@ public class ManageAccountsActivity extends FileActivity
}
List<AccountListItem> accountListItemArray = getAccountListItems();
if (accountListItemArray.size() > 1) {
if (accountListItemArray.size() > SINGLE_ACCOUNT) {
mAccountListAdapter = new AccountListAdapter(this, accountListItemArray, mTintedCheck);
mListView.setAdapter(mAccountListAdapter);
} else {
@@ -452,7 +454,7 @@ public class ManageAccountsActivity extends FileActivity
}
// only one to be (deleted) account remaining
if (accounts.length < 2) {
if (accounts.length < MIN_MULTI_ACCOUNT_SIZE) {
Intent resultIntent = new Intent();
resultIntent.putExtra(KEY_ACCOUNT_LIST_CHANGED, true);
resultIntent.putExtra(KEY_CURRENT_ACCOUNT_CHANGED, true);
@@ -249,10 +249,8 @@ public class NotificationsActivity extends FileActivity {
recyclerView.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, layoutManager.getOrientation());
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(dividerItemDecoration);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation_view);
@@ -315,8 +315,7 @@ public class PassCodeActivity extends AppCompatActivity {
boolean result = true;
for (int i = 0; i < mPassCodeDigits.length && result; i++) {
result = (mPassCodeDigits[i] != null) &&
mPassCodeDigits[i].equals(savedPassCodeDigits[i]);
result = mPassCodeDigits[i] != null && mPassCodeDigits[i].equals(savedPassCodeDigits[i]);
}
return result;
}
@@ -332,7 +331,7 @@ public class PassCodeActivity extends AppCompatActivity {
boolean result = true;
for (int i = 0; i < mPassCodeEditTexts.length && result; i++) {
result = ((mPassCodeEditTexts[i].getText().toString()).equals(mPassCodeDigits[i]));
result = mPassCodeEditTexts[i].getText().toString().equals(mPassCodeDigits[i]);
}
return result;
}
@@ -71,6 +71,7 @@ import com.owncloud.android.lib.common.ExternalLinkType;
import com.owncloud.android.lib.common.OwnCloudAccount;
import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.ui.asynctasks.LoadingVersionNumberTask;
import com.owncloud.android.utils.DeviceCredentialUtils;
import com.owncloud.android.utils.DisplayUtils;
import com.owncloud.android.utils.EncryptionUtils;
@@ -85,7 +86,7 @@ import java.util.ArrayList;
* It proxies the necessary calls via {@link android.support.v7.app.AppCompatDelegate} to be used with AppCompat.
*/
public class Preferences extends PreferenceActivity
implements StorageMigration.StorageMigrationProgressListener {
implements StorageMigration.StorageMigrationProgressListener, LoadingVersionNumberTask.VersionDevInterface {
private static final String TAG = Preferences.class.getSimpleName();
@@ -191,7 +192,7 @@ public class Preferences extends PreferenceActivity
if (pDevLink != null) {
if (getResources().getBoolean(R.bool.dev_version_direct_download_enabled)) {
pDevLink.setOnPreferenceClickListener(preference -> {
FileActivity.checkForNewDevVersion(getListView(), getApplicationContext(), true);
FileActivity.checkForNewDevVersion(this, getApplicationContext());
return true;
});
} else {
@@ -1096,4 +1097,10 @@ public class Preferences extends PreferenceActivity
public void onCancelMigration() {
// Migration was canceled so we don't do anything
}
@Override
public void returnVersion(Integer latestVersion) {
FileActivity.showDevSnackbar(this, latestVersion, true);
}
}
@@ -98,6 +98,7 @@ import com.owncloud.android.utils.DataHolderUtil;
import com.owncloud.android.utils.DisplayUtils;
import com.owncloud.android.utils.ErrorMessageAdapter;
import com.owncloud.android.utils.FileSortOrder;
import com.owncloud.android.utils.MimeType;
import com.owncloud.android.utils.ThemeUtils;
import java.io.File;
@@ -131,6 +132,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
public static final String URL_FILE_SUFFIX = ".url";
public static final String WEBLOC_FILE_SUFFIX = ".webloc";
public static final String DESKTOP_FILE_SUFFIX = ".desktop";
public static final int SINGLE_PARENT = 1;
private AccountManager mAccountManager;
private Stack<String> mParents = new Stack<>();
@@ -313,9 +315,9 @@ public class ReceiveExternalFilesActivity extends FileActivity
*
* @return list of account list items
*/
private ArrayList<AccountListItem> getAccountListItems(ReceiveExternalFilesActivity activity) {
private List<AccountListItem> getAccountListItems(ReceiveExternalFilesActivity activity) {
Account[] accountList = activity.mAccountManager.getAccountsByType(MainApp.getAccountType(getActivity()));
ArrayList<AccountListItem> adapterAccountList = new ArrayList<>(accountList.length);
List<AccountListItem> adapterAccountList = new ArrayList<>(accountList.length);
for (Account account : accountList) {
adapterAccountList.add(new AccountListItem(account));
}
@@ -330,6 +332,8 @@ public class ReceiveExternalFilesActivity extends FileActivity
private static final int CATEGORY_URL = 1;
private static final int CATEGORY_MAPS_URL = 2;
private static final int EXTRA_TEXT_LENGTH = 3;
private static final int SINGLE_SPINNER_ENTRY = 1;
private List<String> mFilenameBase;
private List<String> mFilenameSuffix;
@@ -428,9 +432,8 @@ public class ReceiveExternalFilesActivity extends FileActivity
final Spinner spinner = view.findViewById(R.id.file_type);
setupSpinner(adapter, selectPos, userInput, spinner);
if (adapter.getCount() == 1) {
TextView label = view.findViewById(R.id.label_file_type);
label.setVisibility(View.GONE);
if (adapter.getCount() == SINGLE_SPINNER_ENTRY) {
view.findViewById(R.id.label_file_type).setVisibility(View.GONE);
spinner.setVisibility(View.GONE);
}
mSpinner = spinner;
@@ -526,7 +529,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
inputText.setText(filename);
int selectionStart = 0;
int extensionStart = filename.lastIndexOf(".");
int selectionEnd = (extensionStart >= 0) ? extensionStart : filename.length();
int selectionEnd = extensionStart >= 0 ? extensionStart : filename.length();
if (selectionEnd >= 0) {
inputText.setSelection(
Math.min(selectionStart, selectionEnd),
@@ -536,15 +539,19 @@ public class ReceiveExternalFilesActivity extends FileActivity
private boolean isIntentFromGoogleMap(String subjectText, String extraText) {
String texts[] = extraText.split("\n");
if (texts.length != 3)
if (texts.length != EXTRA_TEXT_LENGTH) {
return false;
if (texts[0].length() == 0 || !subjectText.equals(texts[0]))
}
if (texts[0].length() == 0 || !subjectText.equals(texts[0])) {
return false;
}
return texts[2].startsWith("https://goo.gl/maps/");
}
private boolean isIntentStartWithUrl(String extraText) {
return (extraText.startsWith("http://") || extraText.startsWith("https://"));
return extraText.startsWith("http://") || extraText.startsWith("https://");
}
@Nullable
@@ -623,7 +630,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
@Override
public void onBackPressed() {
if (mParents.size() <= 1) {
if (mParents.size() <= SINGLE_PARENT) {
super.onBackPressed();
} else {
mParents.pop();
@@ -728,7 +735,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
ListView mListView = findViewById(android.R.id.list);
String current_dir = mParents.peek();
boolean notRoot = (mParents.size() > 1);
boolean notRoot = mParents.size() > 1;
if (actionBar != null) {
if ("".equals(current_dir)) {
@@ -880,7 +887,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
}
private void saveTextsFromIntent(Intent intent) {
if (!"text/plain".equals(intent.getType())) {
if (!MimeType.TEXT_PLAIN.equals(intent.getType())) {
return;
}
mUploadFromTmpFile = true;
@@ -1063,7 +1070,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
dialog.show(getSupportFragmentManager(), CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT);
break;
case android.R.id.home:
if ((mParents.size() > 1)) {
if (mParents.size() > SINGLE_PARENT) {
onBackPressed();
}
break;
@@ -1115,8 +1122,8 @@ public class ReceiveExternalFilesActivity extends FileActivity
String syncFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
RemoteOperationResult syncResult = (RemoteOperationResult)
DataHolderUtil.getInstance().retrieve(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
boolean sameAccount = (getAccount() != null &&
accountName.equals(getAccount().name) && getStorageManager() != null);
boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name)
&& getStorageManager() != null;
if (sameAccount) {
@@ -1150,13 +1157,12 @@ public class ReceiveExternalFilesActivity extends FileActivity
mFile = currentFile;
}
mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
!RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
mSyncInProgress = !FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
!RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event);
if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
equals(event) &&
if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.equals(event)
/// TODO refactor and make common
syncResult != null && !syncResult.isSuccess()) {
&& syncResult != null && !syncResult.isSuccess()) {
if (syncResult.getCode() == ResultCode.UNAUTHORIZED ||
(syncResult.isException() && syncResult.getException()
@@ -148,8 +148,8 @@ public class ShareActivity extends FileActivity implements ShareFragmentListener
return OCShare.READ_PERMISSION_FLAG; // minimum permissions
} else if (isFederated) {
return (getFile().isFolder() ? OCShare.FEDERATED_PERMISSIONS_FOR_FOLDER_AFTER_OC9 :
OCShare.FEDERATED_PERMISSIONS_FOR_FILE_AFTER_OC9);
return getFile().isFolder() ? OCShare.FEDERATED_PERMISSIONS_FOR_FOLDER_AFTER_OC9 :
OCShare.FEDERATED_PERMISSIONS_FOR_FILE_AFTER_OC9;
} else {
return (getFile().isFolder() ? OCShare.MAXIMUM_PERMISSIONS_FOR_FOLDER :
OCShare.MAXIMUM_PERMISSIONS_FOR_FILE);
@@ -0,0 +1,213 @@
/*
* Nextcloud Android client application
*
* @author David Luhmer
* @author Andy Scherzinger
* Copyright (C) 2018 David Luhmer
* Copyright (C) 2018 Andy Scherzinger
*
* 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.ui.activity;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.nextcloud.android.sso.Constants;
import com.owncloud.android.MainApp;
import com.owncloud.android.R;
import com.owncloud.android.lib.common.OwnCloudAccount;
import com.owncloud.android.lib.common.accounts.AccountUtils;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.utils.EncryptionUtils;
import com.owncloud.android.utils.ThemeUtils;
import java.util.UUID;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import static com.nextcloud.android.sso.Constants.EXCEPTION_ACCOUNT_ACCESS_DECLINED;
import static com.nextcloud.android.sso.Constants.EXCEPTION_ACCOUNT_NOT_FOUND;
import static com.nextcloud.android.sso.Constants.NEXTCLOUD_FILES_ACCOUNT;
import static com.nextcloud.android.sso.Constants.NEXTCLOUD_SSO;
import static com.nextcloud.android.sso.Constants.NEXTCLOUD_SSO_EXCEPTION;
import static com.nextcloud.android.sso.Constants.SSO_SHARED_PREFERENCE;
/**
* Activity for granting access rights to a Nextcloud account, used for SSO.
*/
public class SsoGrantPermissionActivity extends BaseActivity {
private static final String TAG = SsoGrantPermissionActivity.class.getCanonicalName();
private String packageName;
private Account account;
private Unbinder unbinder;
@BindView(R.id.appIcon)
ImageView appIcon;
@BindView(R.id.permissionText)
TextView permissionText;
@BindView(R.id.btnGrant)
Button grantPermissionButton;
@BindView(R.id.btnDecline)
Button declinePermissionButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sso_grant_permission);
unbinder = ButterKnife.bind(this);
ComponentName callingActivity = getCallingActivity();
if (callingActivity != null) {
packageName = callingActivity.getPackageName();
String appName = getAppNameForPackage(packageName);
account = getIntent().getParcelableExtra(NEXTCLOUD_FILES_ACCOUNT);
permissionText.setText(makeSpecialPartsBold(
getString(R.string.single_sign_on_request_token, appName, account.name),
appName,
account.name)
);
Log.v(TAG, "TOKEN-REQUEST: Calling Package: " + packageName);
Log.v(TAG, "TOKEN-REQUEST: App Name: " + appName);
} else {
// Activity was not started using startActivityForResult!
Log.e(TAG, "Calling Package is null");
setResultAndExit("Request was not executed properly. Use startActivityForResult()");
}
try {
if (packageName != null) {
Drawable appIcon = getPackageManager().getApplicationIcon(packageName);
this.appIcon.setImageDrawable(appIcon);
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, e.getMessage());
}
int primaryColor = ThemeUtils.primaryColor(this, true);
grantPermissionButton.setTextColor(primaryColor);
declinePermissionButton.setTextColor(primaryColor);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbinder.unbind();
}
private SpannableStringBuilder makeSpecialPartsBold(String text, String... toBeStyledText) {
SpannableStringBuilder ssb = new SpannableStringBuilder(text);
for (String textBlock : toBeStyledText) {
int start = text.indexOf(textBlock);
int end = start + textBlock.length();
ssb.setSpan(new StyleSpan(Typeface.BOLD), start, end, 0);
ssb.setSpan(new ForegroundColorSpan(Color.BLACK), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return ssb;
}
private void setResultAndExit(String exception) {
Intent data = new Intent();
data.putExtra(NEXTCLOUD_SSO_EXCEPTION, exception);
setResult(RESULT_CANCELED, data);
finish();
}
private String getAppNameForPackage(String pkg) {
final PackageManager pm = getApplicationContext().getPackageManager();
ApplicationInfo ai = null;
try {
ai = pm.getApplicationInfo(pkg, 0);
} catch (final PackageManager.NameNotFoundException e) {
Log.e(TAG, e.getMessage());
}
return (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
}
@OnClick(R.id.btnDecline)
void exitFailed() {
setResultAndExit(EXCEPTION_ACCOUNT_ACCESS_DECLINED);
}
@OnClick(R.id.btnGrant)
void grantPermission() {
// create token
SharedPreferences sharedPreferences = getSharedPreferences(SSO_SHARED_PREFERENCE, Context.MODE_PRIVATE);
String token = UUID.randomUUID().toString().replaceAll("-", "");
String hashedTokenWithSalt = EncryptionUtils.generateSHA512(token);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(packageName, hashedTokenWithSalt);
editor.apply();
String serverUrl;
String userId;
try {
OwnCloudAccount ocAccount = new OwnCloudAccount(account, this);
serverUrl = ocAccount.getBaseUri().toString();
AccountManager accountManager = AccountManager.get(this);
userId = accountManager.getUserData(account,
com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID);
} catch (AccountUtils.AccountNotFoundException e) {
Log_OC.e(TAG, "Account not found");
setResultAndExit(EXCEPTION_ACCOUNT_NOT_FOUND);
return;
}
final Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType(this));
result.putString(AccountManager.KEY_AUTHTOKEN, NEXTCLOUD_SSO);
result.putString(Constants.SSO_USERNAME, userId);
result.putString(Constants.SSO_TOKEN, token);
result.putString(Constants.SSO_SERVER_URL, serverUrl);
Intent data = new Intent();
data.putExtra(NEXTCLOUD_SSO, result);
setResult(RESULT_OK, data);
finish();
}
}
@@ -269,13 +269,14 @@ public class StorageMigration {
}
}
protected void restoreAccountsSyncStatus(boolean oldSync[]) {
protected void restoreAccountsSyncStatus(boolean... oldSync) {
// If we don't have the old sync statuses, then
// probably migration failed even before saving states,
// which is weird and should be investigated.
// But its better than crashing on ArrayOutOfBounds.
if (oldSync == null)
if (oldSync == null) {
return;
}
for (int i = 0; i < mOcAccounts.length; ++i) {
ContentResolver.setSyncAutomatically(mOcAccounts[i], mAuthority, oldSync[i]);
}
@@ -423,7 +423,7 @@ public class SyncedFoldersActivity extends FileActivity implements SyncedFolderA
return files;
}
private List<String> getDisplayFilePathList(File[] files) {
private List<String> getDisplayFilePathList(File... files) {
List<String> filePaths = null;
if (files != null && files.length > 0) {
@@ -1,4 +1,4 @@
/**
/*
* ownCloud Android client application
*
* @author David A. Velasco
@@ -82,11 +82,12 @@ public class UploadFilesActivity extends FileActivity implements
OnClickListener, ConfirmationDialogFragmentListener, SortingOrderDialogFragment.OnSortingOrderListener {
private static final String SORT_ORDER_DIALOG_TAG = "SORT_ORDER_DIALOG";
private static final int SINGLE_DIR = 1;
private ArrayAdapter<String> mDirectories;
private File mCurrentDir = null;
private boolean mSelectAll = false;
private boolean mLocalFolderPickerMode = false;
private File mCurrentDir;
private boolean mSelectAll;
private boolean mLocalFolderPickerMode;
private LocalFileListFragment mFileListFragment;
protected Button mUploadBtn;
private Spinner mBehaviourSpinner;
@@ -333,7 +334,7 @@ public class UploadFilesActivity extends FileActivity implements
mSearchView.onActionViewCollapsed();
setDrawerIndicatorEnabled(isDrawerIndicatorAvailable());
} else {
if (mDirectories.getCount() <= 1) {
if (mDirectories.getCount() <= SINGLE_DIR) {
finish();
return;
}
@@ -148,7 +148,6 @@ public class UserInfoActivity extends FileActivity {
updateActionBarTitleAndHomeButtonByString("");
mUserInfoList.setAdapter(new UserInfoAdapter(null, ThemeUtils.primaryColor(getAccount(), true, this)));
mUserInfoList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
if (userInfo != null) {
populateUserInfoUi(userInfo);
@@ -302,8 +301,9 @@ public class UserInfoActivity extends FileActivity {
private void addToListIfNeeded(List<UserInfoDetailsItem> info, @DrawableRes int icon, String text,
@StringRes int contentDescriptionInt) {
if (!TextUtils.isEmpty(text))
if (!TextUtils.isEmpty(text)) {
info.add(new UserInfoDetailsItem(icon, text, getResources().getString(contentDescriptionInt)));
}
}
public static void openAccountRemovalConfirmationDialog(Account account, FragmentManager fragmentManager,
@@ -139,8 +139,7 @@ public class WhatsNewActivity extends FragmentActivity implements ViewPager.OnPa
}
public static void runIfNeeded(Context context) {
if (!context.getResources().getBoolean(R.bool.show_whats_new)
|| context instanceof WhatsNewActivity) {
if (!context.getResources().getBoolean(R.bool.show_whats_new) || context instanceof WhatsNewActivity) {
return;
}
@@ -174,7 +173,7 @@ public class WhatsNewActivity extends FragmentActivity implements ViewPager.OnPa
}
static private FeatureItem[] getWhatsNew(Context context) {
int itemVersionCode = 30030000;
int itemVersionCode = 30030099;
if (!isFirstRun(context) && MainApp.getVersionCode() >= itemVersionCode
&& PreferenceManager.getLastSeenVersionCode(context) < itemVersionCode) {
@@ -127,9 +127,9 @@ public class ActivityAndVersionListAdapter extends ActivityListAdapter {
public int getItemViewType(int position) {
Object value = values.get(position);
if (value instanceof Activity)
if (value instanceof Activity) {
return ACTIVITY_TYPE;
else if (value instanceof FileVersion) {
} else if (value instanceof FileVersion) {
return VERSION_TYPE;
} else {
return HEADER_TYPE;
@@ -239,7 +239,7 @@ public class ActivityListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
private void setBitmap(OCFile file, ImageView fileIcon, boolean isDetailView) {
// No Folder
if (!file.isFolder()) {
if ((MimeTypeUtil.isImage(file) || MimeTypeUtil.isVideo(file))) {
if (MimeTypeUtil.isImage(file) || MimeTypeUtil.isVideo(file)) {
int placeholder;
if (MimeTypeUtil.isImage(file)) {
@@ -332,8 +332,9 @@ public class ActivityListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
private RichObject searchObjectByName(List<RichObject> richObjectList, String name) {
for (RichObject richObject : richObjectList) {
if (richObject.getTag().equalsIgnoreCase(name))
if (richObject.getTag().equalsIgnoreCase(name)) {
return richObject;
}
}
return null;
}
@@ -341,10 +342,11 @@ public class ActivityListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
@Override
public int getItemViewType(int position) {
if (values.get(position) instanceof Activity)
if (values.get(position) instanceof Activity) {
return ACTIVITY_TYPE;
else
} else {
return HEADER_TYPE;
}
}
@Override
@@ -68,7 +68,7 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
private List<File> mFiles = new ArrayList<>();
private List<File> mFilesAll = new ArrayList<>();
private boolean mLocalFolderPicker;
private boolean gridView = false;
private boolean gridView;
private LocalFileListFragmentInterface localFileListFragmentInterface;
private Set<File> checkedFiles;
@@ -519,6 +519,10 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
return output;
}
public void setGridView(boolean gridView) {
this.gridView = gridView;
}
static class LocalFileListItemViewHolder extends LocalFileListGridViewHolder {
private final TextView fileSize;
private final TextView lastModification;
@@ -530,6 +534,8 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
fileSize = itemView.findViewById(R.id.file_size);
fileSeparator = itemView.findViewById(R.id.file_separator);
lastModification = itemView.findViewById(R.id.last_mod);
itemView.findViewById(R.id.overflow_menu).setVisibility(View.GONE);
}
}
@@ -547,7 +553,6 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
checkbox = itemView.findViewById(R.id.custom_checkbox);
itemLayout = itemView.findViewById(R.id.ListItemLayout);
itemView.findViewById(R.id.overflow_menu).setVisibility(View.GONE);
itemView.findViewById(R.id.sharedIcon).setVisibility(View.GONE);
itemView.findViewById(R.id.favorite_action).setVisibility(View.GONE);
itemView.findViewById(R.id.keptOfflineIcon).setVisibility(View.GONE);
@@ -54,7 +54,6 @@ import butterknife.ButterKnife;
/**
* Adapter for the trashbin view
*/
public class TrashbinListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TRASHBIN_ITEM = 100;
@@ -605,7 +605,7 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
return items[position];
}
public void setItems(OCUpload[] items) {
public void setItems(OCUpload... items) {
this.items = items;
}
@@ -71,7 +71,6 @@ public class UserListAdapter extends RecyclerView.Adapter<UserListAdapter.UserVi
private float avatarRadiusDimension;
private Account account;
private OCFile file;
private FileDataStorageManager storageManager;
public UserListAdapter(FragmentManager fragmentManager, Context context, List<OCShare> shares, Account account,
OCFile file, ShareeListAdapterListener listener) {
@@ -83,8 +82,7 @@ public class UserListAdapter extends RecyclerView.Adapter<UserListAdapter.UserVi
this.file = file;
accentColor = ThemeUtils.primaryAccentColor(context);
storageManager = new FileDataStorageManager(account, context.getContentResolver());
capabilities = storageManager.getCapability(account.name);
capabilities = new FileDataStorageManager(account, context.getContentResolver()).getCapability(account.name);
avatarRadiusDimension = context.getResources().getDimension(R.dimen.user_icon_radius);
}
@@ -16,7 +16,6 @@
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.owncloud.android.ui.adapter;
@@ -37,6 +37,12 @@ import java.net.URL;
public class LoadingVersionNumberTask extends AsyncTask<String, Void, Integer> {
private static final String TAG = LoadingVersionNumberTask.class.getSimpleName();
private VersionDevInterface callback;
public LoadingVersionNumberTask(VersionDevInterface callback) {
this.callback = callback;
}
protected Integer doInBackground(String... args) {
try {
URL url = new URL(args[0]);
@@ -51,4 +57,13 @@ public class LoadingVersionNumberTask extends AsyncTask<String, Void, Integer> {
}
return -1;
}
@Override
protected void onPostExecute(Integer latestVersion) {
callback.returnVersion(latestVersion);
}
public interface VersionDevInterface {
void returnVersion(Integer latestVersion);
}
}
@@ -42,10 +42,10 @@ import java.util.Collection;
public class RemoveFilesDialogFragment extends ConfirmationDialogFragment implements
ConfirmationDialogFragmentListener {
private Collection<OCFile> mTargetFiles;
private static final int SINGLE_SELECTION = 1;
private static final String ARG_TARGET_FILES = "TARGET_FILES";
private Collection<OCFile> mTargetFiles;
private ActionMode actionMode;
/**
@@ -81,7 +81,7 @@ public class RemoveFilesDialogFragment extends ConfirmationDialogFragment implem
containsFavorite |= file.isAvailableOffline();
}
if (files.size() == 1) {
if (files.size() == SINGLE_SELECTION) {
// choose message for a single file
OCFile file = files.get(0);
@@ -194,7 +194,7 @@ public class SamlWebViewDialog extends DialogFragment {
// Work around bug: http://code.google.com/p/android/issues/detail?id=17423
Dialog dialog = getDialog();
if ((dialog != null)) {
if (dialog != null) {
dialog.setOnDismissListener(null);
}
@@ -89,8 +89,6 @@ public class SendShareDialog extends BottomSheetDialogFragment {
// keep the state of the fragment on configuration changes
setRetainInstance(true);
view = null;
file = getArguments().getParcelable(KEY_OCFILE);
hideNcSharingOptions = getArguments().getBoolean(KEY_HIDE_NCSHARING_OPTIONS, false);
sharingPublicPasswordEnforced = getArguments().getBoolean(KEY_SHARING_PUBLIC_PASSWORD_ENFORCED, false);
@@ -185,6 +185,7 @@ public class SetupEncryptionDialogFragment extends DialogFragment {
try {
String privateKey = task.get();
String mnemonicUnchanged = passwordField.getText().toString();
String mnemonic = passwordField.getText().toString().replaceAll("\\s", "")
.toLowerCase(Locale.ROOT);
String decryptedPrivateKey = EncryptionUtils.decryptPrivateKey(privateKey,
@@ -197,7 +198,7 @@ public class SetupEncryptionDialogFragment extends DialogFragment {
Log_OC.d(TAG, "Private key successfully decrypted and stored");
arbitraryDataProvider.storeOrUpdateKeyValue(account.name, EncryptionUtils.MNEMONIC,
mnemonic);
mnemonicUnchanged);
Intent intentExisting = new Intent();
intentExisting.putExtra(SUCCESS, true);
@@ -345,7 +346,6 @@ public class SetupEncryptionDialogFragment extends DialogFragment {
// Create public/private key pair
KeyPair keyPair = EncryptionUtils.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
// get user id
String userID;
@@ -369,13 +369,13 @@ public class SetupEncryptionDialogFragment extends DialogFragment {
if (result.isSuccess()) {
Log_OC.d(TAG, "public key success");
publicKey = (String) result.getData().get(0);
} else {
keyResult = KEY_FAILED;
return "";
}
PrivateKey privateKey = keyPair.getPrivate();
String privateKeyString = EncryptionUtils.encodeBytesToBase64String(privateKey.getEncoded());
String privatePemKeyString = EncryptionUtils.privateKeyToPEM(privateKey);
String encryptedPrivateKey = EncryptionUtils.encryptPrivateKey(privatePemKeyString,
@@ -65,7 +65,7 @@ public class ShareLinkToDialog extends DialogFragment {
private ActivityAdapter mAdapter;
private Intent mIntent;
public static ShareLinkToDialog newInstance(Intent intent, String[] packagesToExclude) {
public static ShareLinkToDialog newInstance(Intent intent, String... packagesToExclude) {
ShareLinkToDialog f = new ShareLinkToDialog();
Bundle args = new Bundle();
args.putParcelable(ARG_INTENT, intent);
@@ -165,8 +165,8 @@ public class ShareLinkToDialog extends DialogFragment {
}
private View newView(ViewGroup parent) {
return(((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).
inflate(R.layout.activity_row, parent, false));
return((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).
inflate(R.layout.activity_row, parent, false);
}
private void bindView(int position, View row) {
@@ -176,5 +176,4 @@ public class ShareLinkToDialog extends DialogFragment {
icon.setImageDrawable(getItem(position).loadIcon(mPackageManager));
}
}
}
@@ -48,7 +48,7 @@ public class SortingOrderDialogFragment extends DialogFragment {
public static final String SORTING_ORDER_FRAGMENT = "SORTING_ORDER_FRAGMENT";
private static final String KEY_SORT_ORDER = "SORT_ORDER";
private View mView = null;
private View mView;
private View[] mTaggedViews;
private AppCompatButton mCancel;
private String mCurrentSortOrderName;
@@ -54,7 +54,7 @@ public class SslValidatorDialog extends Dialog {
private final static String TAG = SslValidatorDialog.class.getSimpleName();
private OnSslValidatorListener mListener;
private CertificateCombinedException mException = null;
private CertificateCombinedException mException;
private View mView;
@@ -83,14 +83,14 @@ public class SyncedFolderPreferencesDialogFragment extends DialogFragment {
private AlertDialog behaviourDialog;
public static SyncedFolderPreferencesDialogFragment newInstance(SyncedFolderDisplayItem syncedFolder, int section) {
SyncedFolderPreferencesDialogFragment dialogFragment = new SyncedFolderPreferencesDialogFragment();
if (syncedFolder == null) {
throw new IllegalArgumentException("SyncedFolder is mandatory but NULL!");
}
Bundle args = new Bundle();
args.putParcelable(SYNCED_FOLDER_PARCELABLE, new SyncedFolderParcelable(syncedFolder, section));
SyncedFolderPreferencesDialogFragment dialogFragment = new SyncedFolderPreferencesDialogFragment();
dialogFragment.setArguments(args);
dialogFragment.setStyle(STYLE_NORMAL, R.style.Theme_ownCloud_Dialog);
@@ -24,6 +24,7 @@ package com.owncloud.android.ui.fragment;
import android.animation.LayoutTransition;
import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.os.Handler;
@@ -101,7 +102,7 @@ public class ExtendedListFragment extends Fragment
private int maxColumnSizePortrait = 5;
private int maxColumnSizeLandscape = 10;
private ScaleGestureDetector mScaleGestureDetector = null;
private ScaleGestureDetector mScaleGestureDetector;
protected SwipeRefreshLayout mRefreshListLayout;
protected LinearLayout mEmptyListContainer;
protected TextView mEmptyListMessage;
@@ -115,9 +116,9 @@ public class ExtendedListFragment extends Fragment
private ArrayList<Integer> mIndexes;
private ArrayList<Integer> mFirstPositions;
private ArrayList<Integer> mTops;
private int mHeightCell = 0;
private int mHeightCell;
private SwipeRefreshLayout.OnRefreshListener mOnRefreshListener = null;
private SwipeRefreshLayout.OnRefreshListener mOnRefreshListener;
private EmptyRecyclerView mRecyclerView;
@@ -208,7 +209,7 @@ public class ExtendedListFragment extends Fragment
if (getActivity() != null && !(getActivity() instanceof FolderPickerActivity)) {
if (!(getActivity() instanceof UploadFilesActivity)) {
setFabEnabled(!hasFocus);
setFabVisible(!hasFocus);
}
boolean searchSupported = AccountUtils.hasSearchSupport(AccountUtils.
@@ -588,21 +589,42 @@ public class ExtendedListFragment extends Fragment
/**
* Sets the 'visibility' state of the FAB contained in the fragment.
* <p>
* When 'false' is set, FAB visibility is set to View.GONE programmatically,
*
* When 'false' is set, FAB visibility is set to View.GONE programmatically.
*
* @param visible Desired visibility for the FAB.
*/
public void setFabVisible(final boolean visible) {
if (getActivity() != null) {
getActivity().runOnUiThread(() -> {
if (visible) {
mFabMain.setVisibility(View.VISIBLE);
ThemeUtils.tintDrawable(mFabMain.getBackground(), ThemeUtils.primaryColor(getContext()));
} else {
mFabMain.setVisibility(View.GONE);
}
});
}
}
/**
* Sets the 'visibility' state of the FAB contained in the fragment.
*
* When 'false' is set, FAB is greyed out
*
* @param enabled Desired visibility for the FAB.
*/
public void setFabEnabled(final boolean enabled) {
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (enabled) {
mFabMain.setVisibility(View.VISIBLE);
} else {
mFabMain.setVisibility(View.GONE);
}
getActivity().runOnUiThread(() -> {
mFabMain.setVisibility(View.VISIBLE);
if (enabled) {
mFabMain.setEnabled(true);
ThemeUtils.tintDrawable(mFabMain.getBackground(), ThemeUtils.primaryColor(getContext()));
} else {
mFabMain.setEnabled(false);
ThemeUtils.tintDrawable(mFabMain.getBackground(), Color.GRAY);
}
});
}
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff. Show more