Compare commits

..
Author SHA1 Message Date
tobiasKaminsky 4221796da7 sort via db
Signed-off-by: tobiasKaminsky <[email protected]>
2025-03-19 12:04:53 +01:00
Tobias Kaminsky 3b5d0beca9 Merge pull request #14671 from nextcloud/bugfix/e2ee-image-preview
BugFix - E2EE Image Preview
2025-03-19 10:14:23 +01:00
Tobias Kaminsky 3cb91115a1 Merge pull request #14670 from nextcloud/bugfix/use-previous-etag-for-shared-folder-if-exists
BugFix - Use Previous eTag for Shared Folder If Exists
2025-03-19 10:07:01 +01:00
Tobias Kaminsky d9ebd1f3c2 Merge pull request #14640 from nextcloud/bugfix/e2ee-rename-name-collision
BugFix - E2EE Rename NameCollision
2025-03-19 09:41:57 +01:00
Tobias Kaminsky 8ebd8e1eb1 Merge pull request #14646 from nextcloud/keepPreviewWhenDeletingFiles
showDirectoryWhenDeletionCompleted set to false?
2025-03-19 09:39:38 +01:00
Nextcloud bot ae0d4ed7ca Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-03-19 03:07:20 +00:00
Tobias Kaminsky 531e140135 Merge pull request #14659 from nextcloud/bugfix/auto-rename-create-new-folder
BugFix - Auto Rename Creating New folder
2025-03-18 13:02:39 +01:00
Tobias Kaminsky fec6658bac Merge pull request #14676 from nextcloud/bugfix/sync-tablayout-with-viewpager-file-detail-fragment
BugFix - Highlight Tab Layout When Scrolled
2025-03-18 13:02:18 +01:00
Tobias Kaminsky fda71cc261 Merge pull request #14658 from nextcloud/fix/ChooseStorageLocationDialogFragment-NoSuchElementException
Fix -  ChooseStorageLocationDialogFragment NoSuchElementException
2025-03-18 12:45:56 +01:00
alperozturk 480c768083 get only once capabilities
Signed-off-by: alperozturk <[email protected]>
2025-03-18 12:06:55 +01:00
alperozturk ae58979fe1 auto rename new folder name
Signed-off-by: alperozturk <[email protected]>
2025-03-18 12:06:55 +01:00
alperozturk 0c897f1ced fix
Signed-off-by: alperozturk <[email protected]>
2025-03-18 11:47:22 +01:00
Tobias Kaminsky 71ccf2d0a9 Merge pull request #14690 from nextcloud/update-library-2025-03-16
Update library to 2025-03-16
2025-03-18 10:40:31 +01:00
Tobias Kaminsky 3bdcf2b3af Merge pull request #14698 from nextcloud/pinActions
pin actions
2025-03-18 08:02:07 +01:00
tobiasKaminsky 22e9066b7a pin actions
Signed-off-by: tobiasKaminsky <[email protected]>
2025-03-18 07:39:26 +01:00
Andy Scherzinger 582d2ec11b Merge pull request #14696 from nextcloud/repo-sync/android-config/master
🔄 synced file(s) with nextcloud/android-config
2025-03-17 19:57:29 +01:00
nextcloud-android-bot f1a2180f29 🔄 synced local '.github/workflows/' with remote 'config/workflows/'
Signed-off-by: nextcloud-android-bot <[email protected]>
2025-03-17 15:31:07 +00:00
alperozturk 04661f9574 Use prev etag if exists
Signed-off-by: alperozturk <[email protected]>
2025-03-17 14:27:32 +01:00
alperozturk bb538a02be if prev tag exist set etag
Signed-off-by: alperozturk <[email protected]>
2025-03-17 14:27:32 +01:00
alperozturk fdb9119024 fix android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. Expected: main Calling: DefaultDispatcher-worker-2
Signed-off-by: alperozturk <[email protected]>
2025-03-17 14:27:32 +01:00
alperozturk 47b57ee369 dont set etag
Signed-off-by: alperozturk <[email protected]>
2025-03-17 14:27:32 +01:00
alperozturk 3629909ea0 fix code analytics
Signed-off-by: alperozturk <[email protected]>
2025-03-17 14:17:36 +01:00
alperozturk 9a5704dec3 use find instead of first to prevent NoSuchElementException
Signed-off-by: alperozturk <[email protected]>
2025-03-17 14:17:36 +01:00
Tobias Kaminsky abc8787e59 Update library to 2025-03-16
Signed-off-by: Tobias Kaminsky <[email protected]>
2025-03-16 00:00:57 +01:00
Nextcloud bot 64b41b5066 Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-03-15 03:08:33 +00:00
alperozturk ad753247b1 check binding nullability
Signed-off-by: alperozturk <[email protected]>
2025-03-14 11:54:06 +01:00
alperozturk daa21016a2 clear import
Signed-off-by: alperozturk <[email protected]>
2025-03-14 11:49:27 +01:00
alperozturk 57a1a2469b highlight tab when scrolled
Signed-off-by: alperozturk <[email protected]>
2025-03-14 11:48:20 +01:00
Nextcloud bot e117934451 Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-03-14 03:11:31 +00:00
alperozturk afd468b346 max line lenght fix
Signed-off-by: alperozturk <[email protected]>
2025-03-13 16:17:55 +01:00
alperozturk f7d5fcce85 add comment for FileDownloadFragment usage
Signed-off-by: alperozturk <[email protected]>
2025-03-13 16:16:44 +01:00
alperozturk a154153c40 fix
Signed-off-by: alperozturk <[email protected]>
2025-03-13 13:55:24 +01:00
Nextcloud bot 063148e9a0 Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-03-12 03:07:08 +00:00
Tobias Kaminsky fd33f4fd1b Merge pull request #14663 from nextcloud/bugfix/authenticator-add-lifecycle-observer
BugFix - AuthenticatorActivity Add LifeCycle Observer For Both Condition
2025-03-11 10:13:26 +01:00
Tobias Kaminsky e75c0e7f6d Merge pull request #14589 from nextcloud/Java5
fix obsolete method plus force use of type
2025-03-11 10:12:21 +01:00
Tobias Kaminsky fa9f1fff79 Merge pull request #14590 from nextcloud/optionalFieldParameters2
Optional Tag Removal
2025-03-11 10:00:15 +01:00
alperozturk c6c6c7f9ae fix code formatting
Signed-off-by: alperozturk <[email protected]>
2025-03-11 09:39:59 +01:00
alperozturk 845db4320a do not rely on else condition of webViewLoginMethod
Signed-off-by: alperozturk <[email protected]>
2025-03-11 09:39:59 +01:00
Tobias Kaminsky e8659b0f4c Merge pull request #14544 from Minion3665/push-kzrrwrrwrxur
fix(richdocuments): Let new file load on creation
2025-03-11 09:32:51 +01:00
Nextcloud bot 4cca9f2da3 Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-03-11 03:05:46 +00:00
Nextcloud bot b16d598e0b Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-03-10 03:03:24 +00:00
Andy Scherzinger 6f0350c7d5 Merge pull request #14562 from nextcloud/DeprecatedGithubAction
Fix deprecated github action and simplify CI
2025-03-09 20:11:25 +01:00
Andy Scherzinger d24964c307 ci(assemble): Pin action with commit
Signed-off-by: Andy Scherzinger <[email protected]>
2025-03-09 19:54:53 +01:00
Hannes Achleitner 5656e6751c Fix deprecated github action and simplify CI
Signed-off-by: Hannes Achleitner <[email protected]>
2025-03-09 19:49:00 +01:00
Andy Scherzinger 086fcc945e Merge pull request #14561 from nextcloud/PrepareBuildKts
Prepare for build with *.kts files
2025-03-09 19:47:46 +01:00
Nextcloud bot e62ff3697d Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-03-09 13:24:17 +00:00
Andy Scherzinger f8d175af6d ci: raise commit range to hit lib change commit
Signed-off-by: Andy Scherzinger <[email protected]>
2025-03-09 13:55:42 +01:00
Hannes Achleitner 9cf3f151f6 Prepare for build with *.kts files
Signed-off-by: Hannes Achleitner <[email protected]>
2025-03-09 13:55:39 +01:00
Andy Scherzinger 30cd4d134c Merge pull request #14651 from nextcloud/update-library-2025-03-09
Update library to 2025-03-09
2025-03-09 13:55:06 +01:00
Andy Scherzinger 8419586774 ci: Add meta data
Signed-off-by: Andy Scherzinger <[email protected]>
2025-03-09 11:49:04 +01:00
Tobias Kaminsky c9097806f7 Update library to 2025-03-09
Signed-off-by: Tobias Kaminsky <[email protected]>
2025-03-09 00:03:04 +01:00
Andy Scherzinger ddc7f7463f Merge pull request #14641 from nextcloud/fix/noid/AGP890
Bump to AGP 8.9.0
2025-03-08 14:51:03 +01:00
Andy Scherzinger cbf3a28981 ci. Bump lint error score
Signed-off-by: Andy Scherzinger <[email protected]>
2025-03-08 11:23:59 +01:00
tobiasKaminsky 32ae47d6ac fix lint
Signed-off-by: tobiasKaminsky <[email protected]>
2025-03-08 11:22:58 +01:00
tobiasKaminsky 8e6bab2136 fix lint
Signed-off-by: tobiasKaminsky <[email protected]>
2025-03-08 11:22:57 +01:00
Andy Scherzinger 628428e185 fix(deps): Bump to AGP 8.9.0
Signed-off-by: Andy Scherzinger <[email protected]>
2025-03-08 11:22:53 +01:00
Andy Scherzinger 0ee8bb8f7c Merge pull request #14649 from nextcloud/repo-sync/android-config/master
🔄 synced file(s) with nextcloud/android-config
2025-03-08 07:15:34 +01:00
Nextcloud bot 237c3a9bff Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-03-08 03:01:49 +00:00
nextcloud-android-bot 4eefc73cf9 🔄 synced local '.github/workflows/' with remote 'config/workflows/'
Signed-off-by: nextcloud-android-bot <[email protected]>
2025-03-08 02:27:09 +00:00
Alper Öztürk 3140eafa6e Merge pull request #14566 from nextcloud/bugfix/auto-rename-file-extension
BugFix - Auto Rename File Extension
2025-03-07 13:18:14 +01:00
tobiasKaminsky c994d34828 keep slideshow when deleting file
Signed-off-by: tobiasKaminsky <[email protected]>
2025-03-07 11:14:01 +01:00
Andy Scherzinger 95e793a7aa Merge pull request #14644 from nextcloud/renovate/com.github.spotbugs.snom-spotbugs-gradle-plugin-6.x
Update dependency com.github.spotbugs.snom:spotbugs-gradle-plugin to v6.1.7
2025-03-07 09:27:38 +01:00
renovate[bot] 9b110d4227 Update dependency com.github.spotbugs.snom:spotbugs-gradle-plugin to v6.1.7
Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-03-07 07:19:19 +00:00
Andy Scherzinger 75b6912fb9 Merge pull request #14643 from nextcloud/repo-sync/android-config/master
🔄 synced file(s) with nextcloud/android-config
2025-03-07 08:11:01 +01:00
Nextcloud bot cb9cd7ad09 Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-03-07 03:03:12 +00:00
nextcloud-android-bot cd984564db 🔄 synced local '.github/workflows/' with remote 'config/workflows/'
Signed-off-by: nextcloud-android-bot <[email protected]>
2025-03-07 02:53:24 +00:00
Andy Scherzinger 2f7c925d2c Merge pull request #14614 from nextcloud/renovate/mockkversion
Update mockkVersion to v1.13.17
2025-03-06 19:16:51 +01:00
alperozturk 2037190398 remove isFolder parameter
Signed-off-by: alperozturk <[email protected]>
2025-03-05 10:22:42 +01:00
alperozturk c51c488805 add e2ee test
Signed-off-by: alperozturk <[email protected]>
2025-03-05 10:22:17 +01:00
alperozturk 5539231094 add e2ee test
Signed-off-by: alperozturk <[email protected]>
2025-03-05 10:22:17 +01:00
alperozturk 4872774416 fix tests
Signed-off-by: alperozturk <[email protected]>
2025-03-05 10:22:17 +01:00
alperozturk 68fbb073f4 add DOT between file name and extension
Signed-off-by: alperozturk <[email protected]>
2025-03-05 10:22:17 +01:00
alperozturk 90091a12d7 use FilenameUtils, add tests and only change lowercaseFileExtension for files not folders
Signed-off-by: alperozturk <[email protected]>
2025-03-05 10:22:17 +01:00
Tobias Kaminsky 530a19e786 Merge pull request #14626 from nextcloud/simplify-e2ee-dialog-enter-passphrase-info-text
Improve E2EE dialog description for better clarity
2025-03-05 10:04:57 +01:00
Tobias Kaminsky 030838bc52 Merge pull request #14625 from nextcloud/remove-airplane-mode-check
Remove Airplane mode Check Due to Configurable Unmetered Wi-Fi
2025-03-05 10:03:01 +01:00
Tobias Kaminsky affaa2b5b6 Merge pull request #14565 from nextcloud/use-configure-system-bar-from-common-ui
Use Common Library For System Bars
2025-03-05 09:01:44 +01:00
Tobias Kaminsky e1cb118b85 Merge pull request #14528 from nextcloud/fix/resume-paused-media-fragment
Do not release video player on pause
2025-03-05 09:01:08 +01:00
Nextcloud bot 350568c1a0 Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-03-05 03:03:56 +00:00
alperozturk 27cd781d08 use 0.25.0
Signed-off-by: alperozturk <[email protected]>
2025-03-04 17:32:27 +01:00
Alper Öztürk 2fa87b9963 Merge branch 'master' into use-configure-system-bar-from-common-ui 2025-03-04 16:29:44 +01:00
Alper Öztürk 396f6e516c Merge pull request #14630 from nextcloud/fix/ecosystem-app-switcher-spacing
Fix ecosystem app switcher spacing
2025-03-04 16:28:46 +01:00
alperozturk 0979998b91 update androidCommonLibraryVersion
Signed-off-by: alperozturk <[email protected]>
2025-03-04 15:30:19 +01:00
alperozturk 7d01ba4c08 use common ui
Signed-off-by: alperozturk <[email protected]>
2025-03-04 15:21:51 +01:00
alperozturk e814e47862 reduce lint
Signed-off-by: alperozturk <[email protected]>
2025-03-04 15:17:39 +01:00
alperozturk a687c6f79d change description
Signed-off-by: alperozturk <[email protected]>
2025-03-04 15:17:39 +01:00
ZetaTom 69f692e68e Update screenshot
Signed-off-by: ZetaTom <[email protected]>
2025-03-04 15:17:03 +01:00
ZetaTom 3f978decba Fix ecosystem app switcher spacing
Signed-off-by: ZetaTom <[email protected]>
2025-03-04 15:17:03 +01:00
Nextcloud bot d94fbcc61b Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-03-04 03:05:50 +00:00
Andy Scherzinger ab3e40a524 Merge pull request #14623 from nextcloud/renovate/ksp-monorepo
Update plugin com.google.devtools.ksp to v2.1.10-1.0.31
2025-03-03 21:20:03 +01:00
alperozturk 4af1ff225e remove airplane mode check due to configurable unmetered Wi-Fi
Signed-off-by: alperozturk <[email protected]>
2025-03-03 15:03:56 +01:00
Alper Öztürk b306bc729b Merge pull request #13975 from nextcloud/improve-file-download-worker
Improve File Download Worker
2025-03-03 09:46:32 +01:00
renovate[bot] 5f9c369ccf Update plugin com.google.devtools.ksp to v2.1.10-1.0.31
Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-03-03 08:42:44 +00:00
alperozturk 869c9916f5 fix code analytics
Signed-off-by: alperozturk <[email protected]>
2025-03-03 08:35:09 +01:00
alperozturk 946528cc64 add comment
Signed-off-by: alperozturk <[email protected]>
2025-03-03 08:35:09 +01:00
alperozturk 9a3bddc3b5 fix code analytics
Signed-off-by: alperozturk <[email protected]>
2025-03-03 08:35:09 +01:00
alperozturk ed89ed607c reduce lint, delete unused translations
Signed-off-by: alperozturk <[email protected]>
2025-03-03 08:35:09 +01:00
alperozturk 5ac07d984a If there is existing pending (uncompleted) work with the same unique name, do nothing.
Signed-off-by: alperozturk <[email protected]>
2025-03-03 08:35:09 +01:00
alperozturk 9fcf24d919 fix code analytics
Signed-off-by: alperozturk <[email protected]>
2025-03-03 08:35:09 +01:00
alperozturk d67bff414d improve file download worker
Signed-off-by: alperozturk <[email protected]>
2025-03-03 08:35:09 +01:00
Tobias Kaminsky 9344f4506f Merge pull request #14619 from nextcloud/update-library-2025-03-02
Update library to 2025-03-02
2025-03-03 07:44:04 +01:00
Nextcloud bot 5238dbc960 Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-03-03 03:04:10 +00:00
Nextcloud bot 71fefa41ee Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-03-02 03:03:29 +00:00
Tobias Kaminsky 87e0c284b7 Update library to 2025-03-02
Signed-off-by: Tobias Kaminsky <[email protected]>
2025-03-02 00:04:52 +01:00
Nextcloud bot 6fec4f629b Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-03-01 03:27:14 +00:00
renovate[bot] 651f372281 Update mockkVersion to v1.13.17
Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-02-27 23:56:28 +00:00
Andy Scherzinger 176973cd27 Merge pull request #14613 from nextcloud/renovate/actions-cache-4.x
Update actions/cache action to v4.2.2
2025-02-28 00:51:05 +01:00
renovate[bot] d03939fb81 Update actions/cache action to v4.2.2
Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-02-27 23:43:29 +00:00
Andy Scherzinger 37f2494397 Merge pull request #14610 from nextcloud/renovate/androidx.exifinterface-exifinterface-1.x
Update dependency androidx.exifinterface:exifinterface to v1.4.0
2025-02-28 00:42:39 +01:00
renovate[bot] c8a924a042 Update dependency androidx.exifinterface:exifinterface to v1.4.0
Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-02-27 23:40:33 +01:00
Nextcloud bot 76cde56d85 Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-02-27 22:39:17 +00:00
Nextcloud bot 042bb55d6a Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-02-27 16:14:17 +00:00
Andy Scherzinger f459b11144 Merge pull request #14607 from nextcloud/renovate/androidpluginversion
Update dependency com.android.tools.build:gradle to v8.8.2
2025-02-27 13:34:36 +01:00
Andy Scherzinger 35cc3451e4 Merge pull request #14606 from nextcloud/renovate/androidx.constraintlayout-constraintlayout-2.x
Update dependency androidx.constraintlayout:constraintlayout to v2.2.1
2025-02-27 13:33:54 +01:00
Andy Scherzinger 7f357c9d3e Merge pull request #14608 from nextcloud/renovate/com.github.spotbugs.snom-spotbugs-gradle-plugin-6.x
Update dependency com.github.spotbugs.snom:spotbugs-gradle-plugin to v6.1.6
2025-02-27 13:33:04 +01:00
Andy Scherzinger c2ae28ca40 Merge pull request #14609 from nextcloud/renovate/codecov-codecov-action-5.x
Update codecov/codecov-action action to v5.4.0
2025-02-27 13:32:34 +01:00
renovate[bot] 4e110fcb90 Update codecov/codecov-action action to v5.4.0
Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-02-27 07:21:56 +00:00
renovate[bot] 81a1200a5d Update dependency com.github.spotbugs.snom:spotbugs-gradle-plugin to v6.1.6
Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-02-27 07:20:43 +00:00
renovate[bot] e199f582d4 Update dependency com.android.tools.build:gradle to v8.8.2
Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-02-27 07:19:40 +00:00
renovate[bot] 4c77a41646 Update dependency androidx.constraintlayout:constraintlayout to v2.2.1
Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-02-27 07:17:10 +00:00
Nextcloud bot dcdbc5c4e9 Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-02-27 03:07:06 +00:00
Andy Scherzinger 0eac53a2cc Merge pull request #14602 from nextcloud/renovate/gradle-8.x
Update dependency gradle to v8.13
2025-02-26 11:00:38 +01:00
renovate[bot] 7b578d62da Update dependency gradle to v8.13
Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-02-26 10:40:15 +01:00
Andy Scherzinger 89b92b4706 Merge pull request #14600 from nextcloud/renovate/io.gitlab.arturbosch.detekt-detekt-gradle-plugin-1.x
Update dependency io.gitlab.arturbosch.detekt:detekt-gradle-plugin to v1.23.8
2025-02-26 10:40:03 +01:00
Andy Scherzinger 7aedbad347 Merge pull request #14599 from nextcloud/renovate/actions-upload-artifact-4.x
Update actions/upload-artifact action to v4.6.1
2025-02-26 10:30:55 +01:00
Tobias Kaminsky 4e14d2cd38 Merge pull request #14556 from nextcloud/update-thumbnail-if-needed-after-conflict-resolve
Update Thumbnail After Resolving Conflict
2025-02-26 10:20:17 +01:00
Tobias Kaminsky f07d1fe231 Merge pull request #14557 from nextcloud/bugfix/update-recommended-files-changes
BugFix - Update Recommended File List When Needed
2025-02-26 10:09:13 +01:00
renovate[bot] c86492f73d Update dependency io.gitlab.arturbosch.detekt:detekt-gradle-plugin to v1.23.8
Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-02-26 09:06:38 +00:00
renovate[bot] 563404f999 Update actions/upload-artifact action to v4.6.1
Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-02-26 08:59:40 +00:00
Tobias Kaminsky f10ce3ed64 Merge pull request #14568 from nextcloud/bugfix/on-sync-folder-setting-click-anr
Fix - onSyncFolderSettingsClick ANR
2025-02-26 09:52:18 +01:00
Tobias Kaminsky 116e42ffd0 Merge pull request #14497 from nextcloud/feature/open-in-notes
Tighter integration - Open in Notes Button
2025-02-26 09:42:38 +01:00
ZetaTom a76859c8c6 Set is_beta back to false
Signed-off-by: ZetaTom <[email protected]>
2025-02-26 09:41:54 +01:00
Nextcloud bot 92a57cf054 Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-02-26 03:03:21 +00:00
Alex Knop 291a7d3b7a fix obsolete method plus force use of type
Signed-off-by: Alex Knop <[email protected]>
2025-02-25 22:00:15 +01:00
Andy Scherzinger 86b95c5005 Merge pull request #14588 from nextcloud/Java16
Use of Pattern Variables
2025-02-25 21:52:43 +01:00
Andy Scherzinger a74f515f7e Merge pull request #14585 from nextcloud/CStyleArrays
Fix C-Style Arrays
2025-02-25 21:52:12 +01:00
ZetaTom 832039854e Update library version
Signed-off-by: ZetaTom <[email protected]>
2025-02-25 13:06:17 +01:00
ZetaTom db22caebaf Update library version
Signed-off-by: ZetaTom <[email protected]>
2025-02-25 13:06:16 +01:00
ZetaTom a6e9586896 Use material text button
Signed-off-by: ZetaTom <[email protected]>
2025-02-25 13:06:16 +01:00
ZetaTom a74d600cd3 Place open in notes button in card view
Signed-off-by: ZetaTom <[email protected]>
2025-02-25 13:06:16 +01:00
ZetaTom 0c606f9209 Update library version
Signed-off-by: ZetaTom <[email protected]>
2025-02-25 13:06:16 +01:00
ZetaTom 55f8fcbf02 Fix lint
Signed-off-by: ZetaTom <[email protected]>
2025-02-25 13:06:16 +01:00
ZetaTom 8313981bdf Extend OCFileListAdapter to handle open in notes button
Signed-off-by: ZetaTom <[email protected]>
2025-02-25 13:06:16 +01:00
ZetaTom 156773e722 Extract openAppOrStore() and openAppStore() to LinkHelper
Signed-off-by: ZetaTom <[email protected]>
2025-02-25 13:06:16 +01:00
ZetaTom a6c3b29904 Extend capability to include notes folder location
Signed-off-by: ZetaTom <[email protected]>
2025-02-25 13:06:15 +01:00
ZetaTom 0f5e3670d1 Extend list_header.xml to add open in notes button
Signed-off-by: ZetaTom <[email protected]>
2025-02-25 13:06:11 +01:00
Andy Scherzinger 87a2bc7e70 Merge pull request #14581 from nextcloud/emptyMethod
remove methods that only call super
2025-02-25 11:00:45 +01:00
alperozturk 2582e51b12 updateThumbnailIfNeeded
Signed-off-by: alperozturk <[email protected]>
2025-02-25 09:03:39 +01:00
alperozturk 7f9be17a5e updateThumbnailIfNeeded
Signed-off-by: alperozturk <[email protected]>
2025-02-25 09:03:39 +01:00
Tobias Kaminsky 3f8527ef66 Merge pull request #14578 from nextcloud/clipboard
enhance clipboard
2025-02-25 08:06:55 +01:00
Tobias Kaminsky f3b55a3466 Merge pull request #14559 from nextcloud/simplifiedShareLayout
Simplified share layout
2025-02-25 08:06:22 +01:00
Alex Knop b1c7cb06ca finish job
Signed-off-by: Alex Knop <[email protected]>
2025-02-25 01:19:41 -05:00
Alex Knop 3eaaab41e7 small fix
Signed-off-by: Alex Knop <[email protected]>
2025-02-25 00:29:43 -05:00
Nextcloud bot 76c50d1494 Fix(l10n): Update translations from Transifex
Signed-off-by: Nextcloud bot <[email protected]>
2025-02-25 03:11:25 +00:00
Alex Knop ce589ac616 fix onResume
Signed-off-by: Alex Knop <[email protected]>
2025-02-24 19:33:27 -05:00
Alex Knop f4fe799ad7 use of pattern variables
Signed-off-by: Alex Knop <[email protected]>
2025-02-24 17:28:04 -05:00
Alex Knop f3e14cb3de use of pattern variables
Signed-off-by: Alex Knop <[email protected]>
2025-02-24 16:57:51 -05:00
Alex Knop 807d45b508 Fix C-Style Arrays
Signed-off-by: Alex Knop <[email protected]>
2025-02-24 15:45:48 -05:00
Alex Knop 20db7b6662 remove methods that only call super
Signed-off-by: Alex Knop <[email protected]>
2025-02-24 14:47:12 -05:00
tobiasKaminsky 47ea22db5c enhance clipboard
Signed-off-by: tobiasKaminsky <[email protected]>
2025-02-24 15:56:17 +01:00
tobiasKaminsky 8cbebf2bc8 simplified share layout
Signed-off-by: tobiasKaminsky <[email protected]>
2025-02-24 13:53:47 +01:00
ZetaTom 5b61aecdda Do not release video player on pause
- player would be released when swiping to next fragment
- player became unresponsive when going back to fragment

Signed-off-by: ZetaTom <[email protected]>
2025-02-24 13:07:08 +01:00
alperozturk b6211e1637 fix code analytics
Signed-off-by: alperozturk <[email protected]>
2025-02-24 10:21:50 +01:00
alperozturk 1740121be5 no need add
Signed-off-by: alperozturk <[email protected]>
2025-02-24 10:20:55 +01:00
alperozturk 7e30cfe3c6 fix code analytics
Signed-off-by: alperozturk <[email protected]>
2025-02-24 10:20:55 +01:00
alperozturk f664b3760a commit transaction
Signed-off-by: alperozturk <[email protected]>
2025-02-24 10:20:55 +01:00
alperozturk b1582a37d3 use lifecycleScope
Signed-off-by: alperozturk <[email protected]>
2025-02-24 10:20:55 +01:00
alperozturk cebffff8e0 only refresh when its necessary
Signed-off-by: alperozturk <[email protected]>
2025-02-19 13:50:23 +01:00
alperozturk f56ab108b9 add refresh
Signed-off-by: alperozturk <[email protected]>
2025-02-19 13:50:23 +01:00
Skyler Grey 812448f419 fix(richdocuments): Let new file load on creation
Previously when trying to create a file, it would always fail to load,
making you spin forever until you re-entered the file picker.

Upon closer inspection it seems like this is due to a 403 response to
the /direct/ editor URL

    100.64.0.1 - - [12/Feb/2025:13:03:43 +0000] "GET /index.php/apps/richdocuments/direct/Zj4Xu3mKQRUhb53b10FT3nwrLlxOauaWsrb23v9HczGwDK9MDqAukfwGFQwa5w9N HTTP/1.1" 403 26870 "-" "Mozilla/5.0 (Android) Nextcloud-android/20250207"

Normally, this would load the editor which would then query WOPI, etc.
as normal...

    100.64.0.1 - - [12/Feb/2025:13:08:18 +0000] "GET /index.php/apps/richdocuments/direct/wC0K6A6Zkwy6MwFtdEjwU4VJdTbWmIUFWgXuP8SOUrNFxTUg8Hcz9cgvCOZVAt82 HTTP/1.1" 200 9533 "-" "Mozilla/5.0 (Android) Nextcloud-android/20250207"
    100.64.0.40 - - [12/Feb/2025:13:08:18 +0000] "GET /index.php/apps/files/api/v1/stats HTTP/1.1" 200 1042 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:135.0) Gecko/20100101 Firefox/135.0"
    fe80::e7b2:72eb:8e62:74eb%enx908d6e3ca1f5 - - [12/Feb/2025:13:08:19 +0000] "GET /index.php/apps/richdocuments/wopi/files/61_ocyrhf1mv22k?access_token=jSI97GAbzmQc7ckm3RVdvy8PG1pLek7r&access_token_ttl=0 HTTP/1.1" 200 2418 "-" "COOLWSD HTTP Agent 24.04.13.0"
    fe80::e7b2:72eb:8e62:74eb%enx908d6e3ca1f5 - - [12/Feb/2025:13:08:19 +0000] "GET /index.php/apps/richdocuments/wopi/files/61_ocyrhf1mv22k/contents?access_token=jSI97GAbzmQc7ckm3RVdvy8PG1pLek7r&access_token_ttl=1739401698000 HTTP/1.1" 200 1501 "-" "COOLWSD HTTP Agent 24.04.13.0"

Upon further inspection, it looked like we were reusing a token...
commenting the deletion of the token in lib/Controller/DirectViewController.php
on the server also let us access the editor

    -               $this->directMapper->delete($direct);
    +               // $this->directMapper->delete($direct);

And on closer inspection I noticed that there was 2 requests to /direct/
 - the first of which worked!

Finally, that led me here: it seems like both ExternalSiteWebView.java
and EditorWebView.java were calling loadUrl with *the same /direct/ url*
which made it expire before the editor could actually load...

...no good...!

Commenting either of these solved the problem but I wasn't thoroughly
sure that they weren't important for something else, therefore I devised
the cunning plan you see before you: in the editor web view, never
*re*load the url. If we're loading something else, that's fine. If not,
we shouldn't reuse the token since as this will invalidate it.

Signed-off-by: Skyler Grey <[email protected]>
Fixes: nextcloud/android#14548
2025-02-17 10:04:17 +00:00
226 changed files with 5446 additions and 1835 deletions

No files matched your search

+18 -8
View File
@@ -1,9 +1,11 @@
# synced from @nextcloud/android-config
# SPDX-FileCopyrightText: 2023-2024 Nextcloud GmbH and Nextcloud contributors
# SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
# SPDX-FileCopyrightText: 2023 Tobias Kaminsky <[email protected]>
# SPDX-FileCopyrightText: 2023 Andy Scherzinger <[email protected]>
# SPDX-FileCopyrightText: 2023 Josh Richards <[email protected]>
# SPDX-FileCopyrightText: 2025 Marcel Hibbe <[email protected]>
# SPDX-License-Identifier: GPL-3.0-or-later
name: "Analysis"
@@ -24,9 +26,14 @@ concurrency:
jobs:
analysis:
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
steps:
- name: Setup variables
- name: Disabled on forks
if: ${{ github.event.pull_request.head.repo.full_name != github.repository }}
run: |
echo 'Can not analyze PRs from forks'
exit 1
- name: Setup variables # zizmor: ignore[template-injection]
id: get-vars
run: |
if [ -z "$GITHUB_HEAD_REF" ]; then
@@ -46,6 +53,7 @@ jobs:
fi
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
repository: ${{ steps.get-vars.outputs.repo }}
ref: ${{ steps.get-vars.outputs.branch }}
- name: Set up JDK 17
@@ -61,9 +69,11 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
mkdir -p "$HOME/.gradle"
echo "org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" > "$HOME/.gradle/gradle.properties"
echo "org.gradle.caching=true" >> $HOME/.gradle/gradle.properties
echo "org.gradle.parallel=true" >> $HOME/.gradle/gradle.properties
echo "org.gradle.configureondemand=true" >> $HOME/.gradle/gradle.properties
echo "kapt.incremental.apt=true" >> $HOME/.gradle/gradle.properties
scripts/analysis/analysis-wrapper.sh ${{ steps.get-vars.outputs.branch }} ${{ secrets.LOG_USERNAME }} ${{ secrets.LOG_PASSWORD }} "$GITHUB_RUN_NUMBER" ${{ steps.get-vars.outputs.pr }}
{
echo "org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g"
echo "org.gradle.caching=true"
echo "org.gradle.parallel=true"
echo "org.gradle.configureondemand=true"
echo "kapt.incremental.apt=true"
} > "$HOME/.gradle/gradle.properties"
scripts/analysis/analysis-wrapper.sh "${{ steps.get-vars.outputs.branch }}" "${{ secrets.LOG_USERNAME }}" "${{ secrets.LOG_PASSWORD }}" "$GITHUB_RUN_NUMBER" "${{ steps.get-vars.outputs.pr }}"
+1
View File
@@ -28,6 +28,7 @@ jobs:
with:
distribution: "temurin"
java-version: 17
- uses: gradle/actions/wrapper-validation@94baf225fe0a508e581a564467443d0e2379123b # v4.3.0
- name: Build ${{ matrix.flavor }}
run: |
echo "org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" >> gradle.properties
+1 -1
View File
@@ -6,7 +6,7 @@
name: Auto approve sync
on:
pull_request_target:
pull_request_target: # zizmor: ignore[dangerous-triggers]
branches:
- master
- main
+7 -3
View File
@@ -4,6 +4,7 @@
# SPDX-FileCopyrightText: 2023-2024 Andy Scherzinger <[email protected]>
# SPDX-FileCopyrightText: 2022 Tobias Kaminsky <[email protected]>
# SPDX-FileCopyrightText: 2022 Álvaro Brey <[email protected]>
# SPDX-FileCopyrightText: 2025 Marcel Hibbe <[email protected]>
# SPDX-License-Identifier: GPL-3.0-or-later
name: "CodeQL"
@@ -22,7 +23,7 @@ permissions:
jobs:
analyze:
name: Analyze
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
@@ -34,12 +35,15 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- name: Set Swap Space
if: runner.environment == 'github-hosted'
uses: pierotofy/set-swap-space@49819abfb41bd9b44fb781159c033dba90353a7c # v1.0
with:
swap-size-gb: 10
- name: Initialize CodeQL
uses: github/codeql-action/init@b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d # v3.28.10
uses: github/codeql-action/init@6bb031afdd8eb862ea3fc1848194185e076637e5 # v3.28.11
with:
languages: ${{ matrix.language }}
- name: Set up JDK 17
@@ -53,4 +57,4 @@ jobs:
echo "org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError" > "$HOME/.gradle/gradle.properties"
./gradlew assembleDebug
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d # v3.28.10
uses: github/codeql-action/analyze@6bb031afdd8eb862ea3fc1848194185e076637e5 # v3.28.11
@@ -1,29 +0,0 @@
# synced from @nextcloud/android-config
# SPDX-FileCopyrightText: 2023-2024 Nextcloud GmbH and Nextcloud contributors
# SPDX-FileCopyrightText: 2023 Andy Scherzinger <[email protected]>
# SPDX-FileCopyrightText: 2023 Tobias Kaminsky <[email protected]>
# SPDX-FileCopyrightText: 2023 Álvaro Brey <[email protected]>
# SPDX-License-Identifier: GPL-3.0-or-later
name: "Validate Gradle Wrapper"
on:
pull_request:
branches: [ master, stable-* ]
push:
branches: [ master, stable-* ]
# Declare default permissions as read only.
permissions: read-all
concurrency:
group: validate-gradle-wrapper-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
validation:
name: "Validation"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: gradle/wrapper-validation-action@f9c9c575b8b21b6485636a91ffecd10e558c62f6 # v3.5.0
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
blocklist=$(curl https://raw.githubusercontent.com/nextcloud/.github/master/non-community-usernames.txt | paste -s -d, -)
echo "blocklist=$blocklist" >> "$GITHUB_OUTPUT"
- uses: marcelklehr/pr-feedback-action@1883b38a033fb16f576875e0cf45f98b857655c4
- uses: nextcloud/pr-feedback-action@1883b38a033fb16f576875e0cf45f98b857655c4 # main
with:
feedback-message: |
Hello there,
+3 -3
View File
@@ -9,7 +9,7 @@
name: Auto approve renovate PRs
on:
pull_request_target:
pull_request_target: # zizmor: ignore[dangerous-triggers]
branches:
- main
- master
@@ -24,7 +24,7 @@ concurrency:
jobs:
auto-approve-merge:
if: github.actor == 'renovate[bot]'
if: github.event.pull_request.user.login == 'renovate[bot]'
runs-on: ubuntu-latest
permissions:
# for hmarr/auto-approve-action to approve PRs
@@ -52,7 +52,7 @@ jobs:
# Enable GitHub auto merge
- name: Auto merge
uses: alexwilson/enable-github-automerge-action@main
uses: alexwilson/enable-github-automerge-action@56e3117d1ae1540309dc8f7a9f2825bc3c5f06ff # v2.0.0
if: startsWith(steps.branchname.outputs.branch, 'renovate/')
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
+1 -1
View File
@@ -42,6 +42,6 @@ jobs:
# Upload the results to GitHub's code scanning dashboard.
- name: "Upload to code-scanning"
uses: github/codeql-action/upload-sarif@b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d # v3.28.10
uses: github/codeql-action/upload-sarif@6bb031afdd8eb862ea3fc1848194185e076637e5 # v3.28.11
with:
sarif_file: results.sarif
+3 -3
View File
@@ -28,14 +28,14 @@ jobs:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Gradle cache
uses: actions/cache@0c907a75c2c80ebcb7f088228285e798b750cf8f # v4.2.1
uses: actions/cache@d4323d4df104b026a6aa633fdb11d772146be0bf # v4.2.2
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*') }}-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties') }}
- name: AVD cache
uses: actions/cache@0c907a75c2c80ebcb7f088228285e798b750cf8f # v4.2.1
uses: actions/cache@d4323d4df104b026a6aa633fdb11d772146be0bf # v4.2.2
id: avd-cache
with:
path: |
@@ -102,7 +102,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: scripts/uploadReport.sh "${{ secrets.LOG_USERNAME }}" "${{ secrets.LOG_PASSWORD }}" ${{github.event.number}} "${{ matrix.color }}-${{ matrix.scheme }}" "Screenshot" ${{github.event.number}}
- name: Archive Espresso results
uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0
uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1
if: ${{ always() }}
with:
name: Report-${{ matrix.color }}-${{ matrix.scheme }}
+2 -2
View File
@@ -42,14 +42,14 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: scripts/uploadReport.sh "${{ secrets.LOG_USERNAME }}" "${{ secrets.LOG_PASSWORD }}" ${{github.event.number}} "test" "Unit" ${{github.event.number}}
- name: Upload coverage to codecov
uses: codecov/codecov-action@13ce06bfc6bbe3ecf90edbbf1bc32fe5978ca1d3 # v5.3.1
uses: codecov/codecov-action@0565863a31f2c772f9f0395002a31e3f06189574 # v5.4.0
with:
token: ${{ secrets.CODECOV_TOKEN }}
flags: unit
fail_ci_if_error: true
- name: Upload jacoco artifacts
if: ${{ failure() }}
uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0
uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1
with:
name: test-results
path: app/build/reports/tests/testGplayDebugUnitTest/
+94 -94
View File
@@ -16,11 +16,11 @@ import org.gradle.internal.jvm.Jvm
buildscript {
dependencies {
classpath "com.android.tools.build:gradle:$androidPluginVersion"
classpath 'com.github.spotbugs.snom:spotbugs-gradle-plugin:6.1.5'
classpath "com.github.spotbugs.snom:spotbugs-gradle-plugin:6.1.7"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.23.7"
classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.23.8"
classpath "commons-httpclient:commons-httpclient:3.1@jar" // remove after entire switch to lib v2
classpath 'com.karumi:shot:6.1.0'
classpath "com.karumi:shot:6.1.0"
classpath "org.jacoco:org.jacoco.core:$jacoco_version"
classpath "org.jacoco:org.jacoco.report:$jacoco_version"
classpath "org.jacoco:org.jacoco.agent:$jacoco_version"
@@ -31,36 +31,36 @@ plugins {
id "org.jetbrains.kotlin.plugin.compose" version "2.1.10"
id "com.diffplug.spotless" version "6.25.0"
id "org.jetbrains.kotlin.kapt" version "2.1.10"
id 'com.google.devtools.ksp' version '2.1.10-1.0.30' apply false
id "com.google.devtools.ksp" version "2.1.10-1.0.31" apply false
}
apply plugin: 'com.android.application'
apply plugin: "com.android.application"
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-parcelize'
apply plugin: 'checkstyle'
apply plugin: 'pmd'
apply plugin: "kotlin-android"
apply plugin: "kotlin-parcelize"
apply plugin: "checkstyle"
apply plugin: "pmd"
apply from: "$rootProject.projectDir/jacoco.gradle"
apply plugin: 'com.github.spotbugs'
apply plugin: 'io.gitlab.arturbosch.detekt'
apply plugin: "com.github.spotbugs"
apply plugin: "io.gitlab.arturbosch.detekt"
// needed to make renovate run without shot, as shot requires Android SDK
// https://github.com/pedrovgs/Shot/issues/300
if (shotTest) {
apply plugin: 'shot'
apply plugin: "shot"
}
apply plugin: 'com.google.devtools.ksp'
apply plugin: "com.google.devtools.ksp"
println "Gradle uses Java ${Jvm.current()}"
configurations {
configureEach {
exclude group: 'org.jetbrains', module: 'annotations-java5' // via prism4j, already using annotations explicitly
exclude group: "org.jetbrains", module: "annotations-java5" // via prism4j, already using annotations explicitly
// check for updates every build
resolutionStrategy {
cacheChangingModulesFor 0, 'seconds'
cacheChangingModulesFor 0, "seconds"
exclude group: "org.jetbrains.kotlinx", module: "kotlinx-coroutines-debug"
}
}
@@ -85,18 +85,18 @@ def versionBuild = 0 // 0-50=Alpha / 51-98=RC / 90-99=stable
def ndkEnv = new HashMap<String, String>()
file("$project.rootDir/ndk.env").readLines().each() {
def (key, value) = it.tokenize('=')
def (key, value) = it.tokenize("=")
ndkEnv.put(key, value)
}
def perfAnalysis = project.hasProperty('perfAnalysis')
def perfAnalysis = project.hasProperty("perfAnalysis")
android {
// install this NDK version and Cmake to produce smaller APKs. Build will still work if not installed
ndkVersion "${ndkEnv.get("NDK_VERSION")}"
namespace 'com.owncloud.android'
namespace "com.owncloud.android"
testNamespace "${namespace}.test"
androidResources {
@@ -109,8 +109,8 @@ android {
targetSdkVersion 35
compileSdk 35
buildConfigField 'boolean', 'CI', ciBuild.toString()
buildConfigField 'boolean', 'RUNTIME_PERF_ANALYSIS', perfAnalysis.toString()
buildConfigField "boolean", "CI", ciBuild.toString()
buildConfigField "boolean", "RUNTIME_PERF_ANALYSIS", perfAnalysis.toString()
javaCompileOptions {
annotationProcessorOptions {
@@ -127,7 +127,7 @@ android {
testInstrumentationRunnerArgument "TEST_SERVER_URL", "${NC_TEST_SERVER_BASEURL}"
testInstrumentationRunnerArgument "TEST_SERVER_USERNAME", "${NC_TEST_SERVER_USERNAME}"
testInstrumentationRunnerArgument "TEST_SERVER_PASSWORD", "${NC_TEST_SERVER_PASSWORD}"
testInstrumentationRunnerArguments disableAnalytics: 'true'
testInstrumentationRunnerArguments disableAnalytics: "true"
versionCode versionMajor * 10000000 + versionMinor * 10000 + versionPatch * 100 + versionBuild
@@ -146,7 +146,7 @@ android {
buildTypes {
debug {
testCoverageEnabled(project.hasProperty('coverage'))
testCoverageEnabled(project.hasProperty("coverage"))
resConfigs "xxxhdpi"
}
}
@@ -158,17 +158,17 @@ android {
productFlavors {
// used for f-droid
generic {
applicationId 'com.nextcloud.client'
applicationId "com.nextcloud.client"
dimension "default"
}
gplay {
applicationId 'com.nextcloud.client'
applicationId "com.nextcloud.client"
dimension "default"
}
huawei {
applicationId 'com.nextcloud.client'
applicationId "com.nextcloud.client"
dimension "default"
}
@@ -197,18 +197,18 @@ android {
// see http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Configuring-the-Structure
packagingOptions {
resources {
excludes += 'META-INF/LICENSE*'
excludes += 'META-INF/versions/9/OSGI-INF/MANIFEST*'
pickFirst 'MANIFEST.MF' // workaround for duplicated manifest on some dependencies
excludes += "META-INF/LICENSE*"
excludes += "META-INF/versions/9/OSGI-INF/MANIFEST*"
pickFirst "MANIFEST.MF" // workaround for duplicated manifest on some dependencies
}
}
tasks.register("checkstyle", Checkstyle) {
configFile = file("${rootProject.projectDir}/checkstyle.xml")
configProperties.checkstyleSuppressionsPath = file("${project.rootDir}/config/quality/checkstyle/suppressions.xml").absolutePath
source 'src'
include '**/*.java'
exclude '**/gen/**'
source "src"
include "**/*.java"
exclude "**/gen/**"
classpath = files()
}
@@ -217,9 +217,9 @@ android {
ignoreFailures = true // should continue checking
ruleSets = []
source 'src'
include '**/*.java'
exclude '**/gen/**'
source "src"
include "**/*.java"
exclude "**/gen/**"
reports {
xml {
@@ -231,7 +231,7 @@ android {
}
}
check.dependsOn 'checkstyle', 'spotbugsGplayDebug', 'pmd', 'lint', 'spotlessKotlinCheck', 'detekt'
check.dependsOn "checkstyle", "spotbugsGplayDebug", "pmd", "lint", "spotlessKotlinCheck", "detekt"
buildFeatures {
dataBinding true
@@ -252,7 +252,7 @@ android {
lint {
abortOnError false
checkGeneratedSources true
disable 'MissingTranslation', 'GradleDependency', 'VectorPath', 'IconMissingDensityFolder', 'IconDensities', 'GoogleAppIndexingWarning', 'MissingDefaultResource', 'InvalidPeriodicWorkRequestInterval', 'StringFormatInvalid', 'MissingQuantity'
disable "MissingTranslation", "GradleDependency", "VectorPath", "IconMissingDensityFolder", "IconDensities", "GoogleAppIndexingWarning", "MissingDefaultResource", "InvalidPeriodicWorkRequestInterval", "StringFormatInvalid", "MissingQuantity"
htmlOutput file("$project.buildDir/reports/lint/lint.html")
htmlReport true
}
@@ -269,7 +269,7 @@ android {
dependencies {
implementation("com.github.nextcloud:android-library:$androidLibraryVersion") {
exclude group: 'org.ogce', module: 'xpp3' // unused in Android and brings wrong Junit version
exclude group: "org.ogce", module: "xpp3" // unused in Android and brings wrong Junit version
}
// Jetpack Compose
@@ -280,51 +280,51 @@ dependencies {
debugImplementation("androidx.compose.ui:ui-tooling")
implementation("androidx.compose.ui:ui-tooling-preview")
compileOnly 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
compileOnly "org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2"
// remove after entire switch to lib v2
implementation "commons-httpclient:commons-httpclient:3.1@jar" // remove after entire switch to lib v2
implementation 'org.apache.jackrabbit:jackrabbit-webdav:2.13.5' // remove after entire switch to lib v2
implementation 'androidx.constraintlayout:constraintlayout:2.2.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.12.0'
implementation 'com.jakewharton:disklrucache:2.0.2'
implementation "org.apache.jackrabbit:jackrabbit-webdav:2.13.5" // remove after entire switch to lib v2
implementation "androidx.constraintlayout:constraintlayout:2.2.1"
implementation "androidx.legacy:legacy-support-v4:1.0.0"
implementation "com.google.android.material:material:1.12.0"
implementation "com.jakewharton:disklrucache:2.0.2"
implementation "androidx.appcompat:appcompat:$appCompatVersion"
implementation 'androidx.webkit:webkit:1.12.1'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.exifinterface:exifinterface:1.3.7'
implementation "androidx.webkit:webkit:1.12.1"
implementation "androidx.cardview:cardview:1.0.0"
implementation "androidx.exifinterface:exifinterface:1.4.0"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.7"
implementation "androidx.lifecycle:lifecycle-service:2.8.7"
implementation "androidx.work:work-runtime:$workRuntime"
implementation "androidx.work:work-runtime-ktx:$workRuntime"
implementation "androidx.fragment:fragment-ktx:1.8.6"
implementation 'com.github.albfernandez:juniversalchardet:2.0.3' // need this version for Android <7
compileOnly 'com.google.code.findbugs:annotations:3.0.1u2'
implementation 'commons-io:commons-io:2.18.0'
implementation 'org.greenrobot:eventbus:3.3.1'
implementation 'com.googlecode.ez-vcard:ez-vcard:0.12.1'
implementation 'org.lukhnos:nnio:0.3.1'
implementation 'org.bouncycastle:bcpkix-jdk18on:1.80'
implementation 'com.google.code.gson:gson:2.12.1'
implementation 'com.github.nextcloud-deps:sectioned-recyclerview:0.6.1'
implementation 'com.github.chrisbanes:PhotoView:2.3.0'
implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.29'
implementation 'com.github.nextcloud-deps:qrcodescanner:0.1.2.4' // 'com.github.blikoon:QRCodeScanner:0.1.2'
implementation 'com.google.android.flexbox:flexbox:3.0.0'
implementation('com.github.bumptech.glide:glide:3.8.0') {
implementation "com.github.albfernandez:juniversalchardet:2.0.3" // need this version for Android <7
compileOnly "com.google.code.findbugs:annotations:3.0.1u2"
implementation "commons-io:commons-io:2.18.0"
implementation "org.greenrobot:eventbus:3.3.1"
implementation "com.googlecode.ez-vcard:ez-vcard:0.12.1"
implementation "org.lukhnos:nnio:0.3.1"
implementation "org.bouncycastle:bcpkix-jdk18on:1.80"
implementation "com.google.code.gson:gson:2.12.1"
implementation "com.github.nextcloud-deps:sectioned-recyclerview:0.6.1"
implementation "com.github.chrisbanes:PhotoView:2.3.0"
implementation "pl.droidsonroids.gif:android-gif-drawable:1.2.29"
implementation "com.github.nextcloud-deps:qrcodescanner:0.1.2.4" // "com.github.blikoon:QRCodeScanner:0.1.2"
implementation "com.google.android.flexbox:flexbox:3.0.0"
implementation("com.github.bumptech.glide:glide:3.8.0") {
exclude group: "com.android.support"
}
implementation 'com.caverock:androidsvg:1.4'
implementation 'androidx.annotation:annotation:1.9.1'
implementation 'com.vanniktech:emoji-google:0.21.0'
implementation "com.caverock:androidsvg:1.4"
implementation "androidx.annotation:annotation:1.9.1"
implementation "com.vanniktech:emoji-google:0.21.0"
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.7")
// document scanner not available on FDroid (generic) due to OpenCV binaries
gplayImplementation project(':appscan')
huaweiImplementation project(':appscan')
qaImplementation project(':appscan')
gplayImplementation project(":appscan")
huaweiImplementation project(":appscan")
qaImplementation project(":appscan")
spotbugsPlugins 'com.h3xstream.findsecbugs:findsecbugs-plugin:1.13.0'
spotbugsPlugins 'com.mebigfatguy.fb-contrib:fb-contrib:7.6.9'
spotbugsPlugins "com.h3xstream.findsecbugs:findsecbugs-plugin:1.13.0"
spotbugsPlugins "com.mebigfatguy.fb-contrib:fb-contrib:7.6.9"
implementation "com.google.dagger:dagger:$daggerVersion"
implementation "com.google.dagger:dagger-android:$daggerVersion"
@@ -332,17 +332,17 @@ dependencies {
kapt "com.google.dagger:dagger-compiler:$daggerVersion"
kapt "com.google.dagger:dagger-android-processor:$daggerVersion"
implementation 'org.conscrypt:conscrypt-android:2.5.3'
implementation "org.conscrypt:conscrypt-android:2.5.3"
implementation "androidx.media3:media3-ui:$androidxMediaVersion"
implementation "androidx.media3:media3-session:$androidxMediaVersion"
implementation "androidx.media3:media3-exoplayer:$androidxMediaVersion"
implementation "androidx.media3:media3-datasource-okhttp:$androidxMediaVersion"
implementation 'me.zhanghai.android.fastscroll:library:1.3.0'
implementation "me.zhanghai.android.fastscroll:library:1.3.0"
// Shimmer animation
implementation 'io.github.elye:loaderviewlibrary:3.0.0'
implementation "io.github.elye:loaderviewlibrary:3.0.0"
// dependencies for markdown rendering
implementation "io.noties.markwon:core:$markwonVersion"
@@ -356,33 +356,33 @@ dependencies {
kapt "io.noties:prism4j-bundler:$prismVersion"
// dependencies for image cropping and rotation
implementation 'com.vanniktech:android-image-cropper:4.6.0'
implementation "com.vanniktech:android-image-cropper:4.6.0"
implementation 'org.osmdroid:osmdroid-android:6.1.20'
implementation "org.osmdroid:osmdroid-android:6.1.20"
implementation('org.mnode.ical4j:ical4j:3.0.0') {
['org.apache.commons', 'commons-logging'].each {
implementation("org.mnode.ical4j:ical4j:3.0.0") {
["org.apache.commons", "commons-logging"].each {
exclude group: "$it"
}
}
if (perfAnalysis) {
debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.14'
debugImplementation "com.squareup.leakcanary:leakcanary-android:2.14"
}
// dependencies for local unit tests
testImplementation 'junit:junit:4.13.2'
testImplementation "junit:junit:4.13.2"
testImplementation "org.mockito:mockito-core:$mockitoVersion"
testImplementation "androidx.test:core:$androidxTestVersion"
testImplementation 'org.json:json:20250107'
testImplementation "org.json:json:20250107"
testImplementation "org.mockito.kotlin:mockito-kotlin:$mockitoKotlinVersion"
testImplementation 'androidx.arch.core:core-testing:2.2.0'
testImplementation "androidx.arch.core:core-testing:2.2.0"
testImplementation "io.mockk:mockk:$mockkVersion"
testImplementation "io.mockk:mockk-android:$mockkVersion"
// dependencies for instrumented tests
// JUnit4 Rules
androidTestImplementation 'androidx.test.ext:junit:1.2.1'
androidTestImplementation "androidx.test.ext:junit:1.2.1"
androidTestImplementation "androidx.test:rules:$androidxTestVersion"
// Android JUnit Runner
androidTestImplementation "androidx.test:runner:1.6.2"
@@ -398,29 +398,29 @@ dependencies {
androidTestImplementation "androidx.test.espresso:espresso-idling-resource:$espressoVersion"
// Mocking support
androidTestImplementation 'com.github.tmurakami:dexopener:2.0.5' // required to allow mocking on API 27 and older
androidTestImplementation "com.github.tmurakami:dexopener:2.0.5" // required to allow mocking on API 27 and older
androidTestImplementation "org.mockito.kotlin:mockito-kotlin:$mockitoKotlinVersion"
androidTestImplementation "org.mockito:mockito-core:$mockitoVersion"
androidTestImplementation("org.mockito:mockito-android:$mockitoVersion")
androidTestImplementation "io.mockk:mockk-android:$mockkVersion"
androidTestImplementation 'androidx.arch.core:core-testing:2.2.0'
androidTestImplementation "androidx.arch.core:core-testing:2.2.0"
androidTestImplementation "com.facebook.testing.screenshot:core:0.15.0"
// UIAutomator - for cross-app UI tests, and to grant screen is turned on in Espresso tests
// androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
// androidTestImplementation "androidx.test.uiautomator:uiautomator:2.2.0"
// fix conflict in dependencies; see http://g.co/androidstudio/app-test-app-conflict for details
//androidTestImplementation "com.android.support:support-annotations:${supportLibraryVersion}"
androidTestImplementation 'tools.fastlane:screengrab:2.1.1'
androidTestImplementation "tools.fastlane:screengrab:2.1.1"
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "com.github.stateless4j:stateless4j:2.6.0"
// upon each update first test: new registration, receive push
gplayImplementation "com.google.firebase:firebase-messaging:24.1.0"
gplayImplementation 'com.google.android.gms:play-services-base:18.5.0'
gplayImplementation 'com.google.android.play:review-ktx:2.0.2'
gplayImplementation "com.google.android.gms:play-services-base:18.5.0"
gplayImplementation "com.google.android.play:review-ktx:2.0.2"
implementation 'com.github.nextcloud.android-common:ui:0.24.0'
implementation "com.github.nextcloud.android-common:ui:$androidCommonLibraryVersion"
implementation "androidx.room:room-runtime:$roomVersion"
ksp "androidx.room:room-compiler:$roomVersion"
@@ -429,15 +429,15 @@ dependencies {
implementation "io.coil-kt:coil:2.7.0"
// splash screen dependency ref: https://developer.android.com/develop/ui/views/launch/splash-screen/migrate
implementation 'androidx.core:core-splashscreen:1.0.1'
implementation "androidx.core:core-splashscreen:1.0.1"
}
configurations.configureEach {
resolutionStrategy {
cacheChangingModulesFor 0, 'seconds'
force 'org.objenesis:objenesis:3.4'
cacheChangingModulesFor 0, "seconds"
force "org.objenesis:objenesis:3.4"
eachDependency { details ->
if ('org.jacoco' == details.requested.group) {
if ("org.jacoco" == details.requested.group) {
details.useVersion "$jacoco_version"
}
}
@@ -483,7 +483,7 @@ jacoco {
spotbugs {
ignoreFailures = true // should continue checking
effort = Effort.MAX
reportLevel = Confidence.valueOf('MEDIUM')
reportLevel = Confidence.valueOf("MEDIUM")
}
tasks.withType(SpotBugsTask){task ->
@@ -500,11 +500,11 @@ tasks.withType(SpotBugsTask){task ->
html {
required = true
outputLocation = file("$project.buildDir/reports/spotbugs/spotbugs.html")
stylesheet = 'fancy.xsl'
stylesheet = "fancy.xsl"
}
}
}
ksp {
arg('room.schemaLocation', "$projectDir/schemas")
arg("room.schemaLocation", "$projectDir/schemas")
}
@@ -2,7 +2,7 @@
"formatVersion": 1,
"database": {
"version": 86,
"identityHash": "277489b9d4a6ee84f96d09dea39591ba",
"identityHash": "277489b9d4a6ee84f96d09dea39591ba",
"entities": [
{
"tableName": "arbitrary_data",
@@ -796,7 +796,7 @@
"_id"
]
},
"indices": [],
"indices": [],
"foreignKeys": []
},
{
@@ -1325,7 +1325,7 @@
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '277489b9d4a6ee84f96d09dea39591ba')"
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '277489b9d4a6ee84f96d09dea39591ba')"
]
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

@@ -9,6 +9,7 @@ package com.nextcloud.utils
import com.nextcloud.utils.autoRename.AutoRename
import com.owncloud.android.AbstractOnServerIT
import com.owncloud.android.datamodel.e2e.v2.decrypted.DecryptedFile
import com.owncloud.android.lib.resources.status.NextcloudVersion
import com.owncloud.android.lib.resources.status.OCCapability
import org.junit.Before
@@ -122,25 +123,25 @@ class AutoRenameTests : AbstractOnServerIT() {
@Test
fun testMiddleInvalidFolderChar() {
val folderPath = "abc/def/kg$forbiddenFilenameCharacter/lmo/pp"
val result = AutoRename.rename(folderPath, capability, true)
val expectedFolderName = "abc/def/kg_/lmo/pp"
val folderPath = "abc/def/kg$forbiddenFilenameCharacter/lmo/pp/"
val result = AutoRename.rename(folderPath, capability)
val expectedFolderName = "abc/def/kg_/lmo/pp/"
assert(result == expectedFolderName) { "Expected $expectedFolderName but got $result" }
}
@Test
fun testEndInvalidFolderChar() {
val folderPath = "abc/def/kg/lmo/pp$forbiddenFilenameCharacter"
val result = AutoRename.rename(folderPath, capability, true)
val expectedFolderName = "abc/def/kg/lmo/pp_"
val folderPath = "abc/def/kg/lmo/pp$forbiddenFilenameCharacter/"
val result = AutoRename.rename(folderPath, capability)
val expectedFolderName = "abc/def/kg/lmo/pp_/"
assert(result == expectedFolderName) { "Expected $expectedFolderName but got $result" }
}
@Test
fun testStartInvalidFolderChar() {
val folderPath = "${forbiddenFilenameCharacter}abc/def/kg/lmo/pp"
val result = AutoRename.rename(folderPath, capability, true)
val expectedFolderName = "_abc/def/kg/lmo/pp"
val folderPath = "${forbiddenFilenameCharacter}abc/def/kg/lmo/pp/"
val result = AutoRename.rename(folderPath, capability)
val expectedFolderName = "_abc/def/kg/lmo/pp/"
assert(result == expectedFolderName) { "Expected $expectedFolderName but got $result" }
}
@@ -155,16 +156,16 @@ class AutoRenameTests : AbstractOnServerIT() {
@Test
fun testStartsWithPathSeparator() {
val folderPath = "/abc/def/kg/lmo/pp$forbiddenFilenameCharacter/file.txt/"
val result = AutoRename.rename(folderPath, capability, true)
val result = AutoRename.rename(folderPath, capability)
val expectedFolderName = "/abc/def/kg/lmo/pp_/file.txt/"
assert(result == expectedFolderName) { "Expected $expectedFolderName but got $result" }
}
@Test
fun testStartsWithPathSeparatorAndValidFilepath() {
val folderPath = "/COm02/2569.webp"
val result = AutoRename.rename(folderPath, capability, true)
val expectedFolderName = "/COm02/2569.webp"
val folderPath = "/COm02/2569.webp/"
val result = AutoRename.rename(folderPath, capability)
val expectedFolderName = "/COm02/2569.webp/"
assert(result == expectedFolderName) { "Expected $expectedFolderName but got $result" }
}
@@ -175,4 +176,58 @@ class AutoRenameTests : AbstractOnServerIT() {
val expectedFilename = "_file.txt"
assert(result == expectedFilename) { "Expected $expectedFilename but got $result" }
}
@Test
fun testRenameExtensionForFolder() {
val filename = "/Pictures/@User/SubDir/08.16.07 Ka Yel/"
val result = AutoRename.rename(filename, capability)
assert(result == filename) { "Expected $filename but got $result" }
}
@Test
fun testRenameExtensionForFile() {
val filename = "/Pictures/@User/SubDir/08.16.07 Ka Yel.TXT"
val result = AutoRename.rename(filename, capability)
val expectedFilename = "/Pictures/@User/SubDir/08.16.07 Ka Yel.txt"
assert(result == expectedFilename) { "Expected $expectedFilename but got $result" }
}
@Test
fun testE2EEFile() {
val decryptedFile = DecryptedFile(
authenticationTag = "HQlWBdm+gYC5kZwWnqXR1Q==",
filename = "a:a.jpg",
nonce = "sigyys8SfPZSScDJ860vYw==",
mimetype = "image/jpeg",
key = "sigyys8SfPZSScDJ860vYw=="
)
val result = AutoRename.rename(decryptedFile.filename, capability)
val expectedFilename = "a_a.jpg"
assert(result == expectedFilename) { "Expected $expectedFilename but got $result" }
}
@Test
fun testRemovingLeadingWhitespace() {
val filename = " readme.txt"
val result = AutoRename.rename(filename, capability)
val expectedFilename = "readme.txt"
assert(result == expectedFilename) { "Expected $expectedFilename but got $result" }
}
@Test
fun testRemovingTrailingWhitespace() {
val filename = "readme.txt "
val result = AutoRename.rename(filename, capability)
val expectedFilename = "readme.txt"
assert(result == expectedFilename) { "Expected $expectedFilename but got $result" }
}
@Test
fun testRemovingTrailingAndLeadingWhitespace() {
val filename = " readme.txt "
val result = AutoRename.rename(filename, capability)
val expectedFilename = "readme.txt"
assert(result == expectedFilename) { "Expected $expectedFilename but got $result" }
}
}
@@ -528,11 +528,8 @@ public abstract class AbstractIT {
}
protected static User getUser(Account account) {
User optionalUser = UserAccountManagerImpl.fromContext(targetContext).getUser(account.name);
if (optionalUser == null) {
throw new IllegalAccessError("User not found");
}
return optionalUser;
Optional<User> optionalUser = UserAccountManagerImpl.fromContext(targetContext).getUser(account.name);
return optionalUser.orElseThrow(IllegalAccessError::new);
}
protected static Account createAccount(String name) {
@@ -13,7 +13,6 @@ import android.accounts.OperationCanceledException;
import android.content.ActivityNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import com.nextcloud.client.account.User;
import com.nextcloud.client.account.UserAccountManager;
@@ -95,11 +94,8 @@ public abstract class AbstractOnServerIT extends AbstractIT {
throw new ActivityNotFoundException();
}
User optionalUser = userAccountManager.getUser(account.name);
if (optionalUser == null) {
throw new IllegalAccessError("User not found");
}
user = optionalUser;
Optional<User> optionalUser = userAccountManager.getUser(account.name);
user = optionalUser.orElseThrow(IllegalAccessError::new);
client = OwnCloudClientFactory.createOwnCloudClient(account, targetContext);
nextcloudClient = OwnCloudClientFactory.createNextcloudClient(user, targetContext);
@@ -120,7 +116,7 @@ public abstract class AbstractOnServerIT extends AbstractIT {
@After
public void after() {
deleteAllFilesOnServer();
// deleteAllFilesOnServer();
super.after();
}
@@ -53,4 +53,9 @@ class FileDataStorageManagerContentResolverIT : FileDataStorageManagerIT() {
// check file count is correct
Assert.assertEquals(MANY_FILES_AMOUNT, sut.getFolderContent(folderA, false).size)
}
@Test
fun runQuery() {
testQuery()
}
}
@@ -20,7 +20,9 @@ import com.owncloud.android.lib.resources.status.CapabilityBooleanType;
import com.owncloud.android.lib.resources.status.GetCapabilitiesRemoteOperation;
import com.owncloud.android.lib.resources.status.OCCapability;
import com.owncloud.android.operations.RefreshFolderOperation;
import com.owncloud.android.utils.FileSortOrder;
import com.owncloud.android.utils.FileStorageUtils;
import com.owncloud.android.utils.MimeType;
import junit.framework.TestCase;
@@ -31,6 +33,7 @@ import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.owncloud.android.lib.resources.files.SearchRemoteOperation.SearchType.GALLERY_SEARCH;
@@ -135,6 +138,232 @@ abstract public class FileDataStorageManagerIT extends AbstractOnServerIT {
assertEquals(3, sut.getFolderContent(sut.getFileByDecryptedRemotePath("/1/1/"), false).size());
}
@Test
public void testQuery() {
assertEquals(0, sut.getAllFiles().size());
OCFile root = new OCFile("/");
root.setRemoteId("00000001");
root.setMimeType(MimeType.WEBDAV_FOLDER);
root.setOwnerId(getUserId(user));
sut.saveFile(root);
root = sut.getFileByEncryptedRemotePath("/");
OCFile file1 = new OCFile("/1/");
file1.setRemoteId("00000002");
file1.setMimeType(MimeType.WEBDAV_FOLDER);
file1.setParentId(root.getFileId());
file1.setOwnerId(getUserId(user));
file1.setCreationTimestamp(50L);
file1.setFileLength(100L);
sut.saveFile(file1);
OCFile file2 = new OCFile("/2/");
file2.setRemoteId("00000003");
file2.setMimeType(MimeType.WEBDAV_FOLDER);
file2.setParentId(root.getFileId());
file2.setOwnerId(getUserId(user));
file2.setFavorite(true);
file2.setCreationTimestamp(30L);
file2.setFileLength(2L);
sut.saveFile(file2);
OCFile file3 = new OCFile("/.hidden/");
file3.setRemoteId("00000004");
file3.setMimeType(MimeType.WEBDAV_FOLDER);
file3.setParentId(root.getFileId());
file3.setOwnerId(getUserId(user));
file3.setCreationTimestamp(90L);
file3.setFileLength(99L);
sut.saveFile(file3);
OCFile file4 = new OCFile("/test.png");
file4.setRemoteId("00000005");
file4.setMimeType(MimeType.PNG);
file4.setParentId(root.getFileId());
file4.setCreationTimestamp(22L);
file4.setFileLength(12L);
sut.saveFile(file4);
OCFile file5 = new OCFile("/test.jpg");
file5.setRemoteId("00000006");
file5.setMimeType(MimeType.JPEG);
file5.setParentId(root.getFileId());
file5.setOwnerId(getUserId(user));
file5.setCreationTimestamp(2L);
file5.setFileLength(55L);
sut.saveFile(file5);
OCFile file6 = new OCFile("/sharedWithMe/");
file6.setRemoteId("00000006");
file6.setMimeType(MimeType.WEBDAV_FOLDER);
file6.setParentId(root.getFileId());
file6.setPermissions("S");
file6.setOwnerId(getUserId(user));
file6.setCreationTimestamp(100L);
file6.setFileLength(111L);
sut.saveFile(file6);
OCFile file7 = new OCFile("/groupfolder/");
file7.setRemoteId("00000006");
file7.setMimeType(MimeType.WEBDAV_FOLDER);
file7.setParentId(root.getFileId());
file7.setPermissions("M");
file7.setOwnerId(getUserId(user));
file7.setCreationTimestamp(120L);
file7.setFileLength(90L);
sut.saveFile(file7);
assertEquals(8, sut.getAllFiles().size());
// all files
assertEquals(7, sut.getFolderContent(root,
false,
true,
"",
false,
FileSortOrder.SORT_A_TO_Z).size());
// no hidden files
assertEquals(6, sut.getFolderContent(root,
false,
false,
"",
false,
FileSortOrder.SORT_A_TO_Z).size());
// mimetype - PNG
assertEquals(1, sut.getFolderContent(root,
false,
false,
MimeType.PNG,
false,
FileSortOrder.SORT_A_TO_Z).size());
// mimetype - all images
assertEquals(2, sut.getFolderContent(root,
false,
false,
MimeType.IMAGES,
false,
FileSortOrder.SORT_A_TO_Z).size());
// personal files
assertEquals(4, sut.getFolderContent(root,
false,
true,
"",
true,
FileSortOrder.SORT_A_TO_Z).size());
// sort A-Z
List<OCFile> sortedA_Z = Arrays.asList(
file2,
file3,
file1,
file7,
file6,
file5,
file4
);
List<OCFile> actualA_Z = sut.getFolderContent(root,
false,
true,
"",
false,
FileSortOrder.SORT_A_TO_Z);
assertTrue(testSorting(sortedA_Z, actualA_Z));
// sort Z-A
List<OCFile> sortedZ_A = Arrays.asList(
file2,
file4,
file5,
file6,
file7,
file1,
file3
);
List<OCFile> actualZ_A = sut.getFolderContent(root,
false,
true,
"",
false,
FileSortOrder.SORT_Z_TO_A);
assertTrue(testSorting(sortedZ_A, actualZ_A));
// sort old-new
List<OCFile> sortedOld_New = Arrays.asList(
file2,
file5,
file4,
file1,
file3,
file6,
file7
);
List<OCFile> actualOld_New = sut.getFolderContent(root,
false,
true,
"",
false,
FileSortOrder.SORT_OLD_TO_NEW);
assertTrue(testSorting(sortedOld_New, actualOld_New));
// sort new-old
List<OCFile> sortedNew_Old = Arrays.asList(
file2,
file7,
file6,
file3,
file1,
file4,
file5
);
List<OCFile> actualNew_Old = sut.getFolderContent(root,
false,
true,
"",
false,
FileSortOrder.SORT_NEW_TO_OLD);
assertTrue(testSorting(sortedNew_Old, actualNew_Old));
// sort small-big
List<OCFile> sortedSmall_Big = Arrays.asList(
file2,
file4, // 22
file5, // 55
file7, // 90
file3, // 99
file1, // 100
file6 // 111
);
List<OCFile> actualSmall_Big = sut.getFolderContent(root,
false,
true,
"",
false,
FileSortOrder.SORT_SMALL_TO_BIG);
assertTrue(testSorting(sortedSmall_Big, actualSmall_Big));
// sort big-small
List<OCFile> sortedBig_Small = Arrays.asList(
file2,
file6, // 111
file1, // 100
file3, // 99
file7, // 90
file5, // 55
file4 // 22
);
List<OCFile> actualBig_Small = sut.getFolderContent(root,
false,
true,
"",
false,
FileSortOrder.SORT_BIG_TO_SMALL);
assertTrue(testSorting(sortedBig_Small, actualBig_Small));
}
/**
* This test creates an image, does a photo search (now returned image is not yet in file hierarchy), then root
* folder is refreshed and it is verified that the same image file is used in database
@@ -355,4 +584,39 @@ abstract public class FileDataStorageManagerIT extends AbstractOnServerIT {
assertEquals(capability.getUserStatus(), newCapability.getUserStatus());
}
private boolean testSorting(List<OCFile> target, List<OCFile> actual) {
for (int i = 0; i < target.size(); i++) {
boolean compare;
compare = target.get(i).getRemoteId().equals(actual.get(i).getRemoteId());
if (!compare) {
System.out.println("target:");
for (OCFile item : target) {
if (item == null) {
System.out.println("null");
} else {
System.out.println(item.getFileName());
}
}
System.out.println();
System.out.println("actual:");
for (OCFile item : actual) {
if (item == null) {
System.out.println("null");
} else {
System.out.println(item.getFileName());
}
}
return false;
}
}
return true;
}
}
@@ -77,11 +77,7 @@ public class UploadStorageManagerTest extends AbstractIT {
}
final UserAccountManager userAccountManager = UserAccountManagerImpl.fromContext(targetContext);
User user = userAccountManager.getUser("[email protected]");
if (user == null) {
throw new ActivityNotFoundException("Activity not found");
}
user2 = user;
user2 = userAccountManager.getUser("[email protected]").orElseThrow(ActivityNotFoundException::new);
}
@Test
@@ -72,11 +72,7 @@ public class DrawerActivityIT extends AbstractIT {
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_USER_ID, loginName); // same as userId
account1 = userAccountManager.getAccountByName(loginName + "@" + baseUrl);
User user = userAccountManager.getUser(account1.name);
if (user == null) {
throw new IllegalArgumentException("User not found");
}
user1 = user;
user1 = userAccountManager.getUser(account1.name).orElseThrow(IllegalAccessError::new);
loginName = "user2";
password = "user2";
@@ -100,7 +96,7 @@ public class DrawerActivityIT extends AbstractIT {
sut.setUser(user1);
assertEquals(account1, sut.getUser().toPlatformAccount());
assertEquals(account1, sut.getUser().get().toPlatformAccount());
onView(withId(R.id.switch_account_button)).perform(click());
@@ -108,7 +104,7 @@ public class DrawerActivityIT extends AbstractIT {
waitForIdleSync();
assertEquals(account2, sut.getUser().toPlatformAccount());
assertEquals(account2, sut.getUser().get().toPlatformAccount());
onView(withId(R.id.switch_account_button)).perform(click());
onView(withText(account1.name)).perform(click());
@@ -234,10 +234,7 @@ public class DialogFragmentIT extends AbstractIT {
accountManager.setUserData(newAccount, AccountUtils.Constants.KEY_OC_BASE_URL, SERVER_URL);
accountManager.setUserData(newAccount, AccountUtils.Constants.KEY_USER_ID, "test");
accountManager.setAuthToken(newAccount, AccountTypeUtils.getAuthTokenTypePass(newAccount.type), "password");
User newUser = userAccountManager.getUser(newAccount.name);
if (newUser == null) {
throw new RuntimeException("User not found");
}
User newUser = userAccountManager.getUser(newAccount.name).orElseThrow(RuntimeException::new);
userAccountManager.setCurrentOwnCloudAccount(newAccount.name);
Account newAccount2 = new Account("[email protected]", MainApp.getAccountType(targetContext));
@@ -316,11 +313,7 @@ public class DialogFragmentIT extends AbstractIT {
FileDisplayActivity fda = getFileDisplayActivity();
UserAccountManager userAccountManager = fda.getUserAccountManager();
User newUser = userAccountManager.getUser(newAccount.name);
if (newUser == null) {
throw new RuntimeException("User not found");
}
User newUser = userAccountManager.getUser(newAccount.name).get();
FileDataStorageManager fileDataStorageManager = new FileDataStorageManager(newUser,
targetContext.getContentResolver());
@@ -288,7 +288,6 @@ class FileDetailSharingFragmentIT : AbstractIT() {
onView(ViewMatchers.withId(R.id.menu_share_send_new_email)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_send_link)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_unshare)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_add_another_link)).check(matches(isDisplayed()))
// click event
onView(ViewMatchers.withId(R.id.menu_share_advanced_permissions)).perform(ViewActions.click())
@@ -416,7 +415,6 @@ class FileDetailSharingFragmentIT : AbstractIT() {
onView(ViewMatchers.withId(R.id.menu_share_send_new_email)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_send_link)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_unshare)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_add_another_link)).check(matches(isDisplayed()))
// click event
onView(ViewMatchers.withId(R.id.menu_share_advanced_permissions)).perform(ViewActions.click())
@@ -531,7 +529,6 @@ class FileDetailSharingFragmentIT : AbstractIT() {
onView(ViewMatchers.withId(R.id.menu_share_send_new_email)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_send_link)).check(matches(not(isDisplayed())))
onView(ViewMatchers.withId(R.id.menu_share_unshare)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_add_another_link)).check(matches(not(isDisplayed())))
// click event
onView(ViewMatchers.withId(R.id.menu_share_advanced_permissions)).perform(ViewActions.click())
@@ -657,7 +654,6 @@ class FileDetailSharingFragmentIT : AbstractIT() {
onView(ViewMatchers.withId(R.id.menu_share_send_new_email)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_send_link)).check(matches(not(isDisplayed())))
onView(ViewMatchers.withId(R.id.menu_share_unshare)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_add_another_link)).check(matches(not(isDisplayed())))
// click event
onView(ViewMatchers.withId(R.id.menu_share_advanced_permissions)).perform(ViewActions.click())
@@ -39,22 +39,15 @@ class UriUploaderIT : AbstractIT() {
}
private fun testPrivatePath(activity: TestActivity, path: String) {
val user = activity.user
if (user == null) {
throw RuntimeException("User not found")
}
val sut = UriUploader(
activity,
listOf(Uri.parse(path)),
"",
user,
activity.user.orElseThrow(::RuntimeException),
FileUploadWorker.LOCAL_BEHAVIOUR_MOVE,
false,
null
)
val uploadResult = sut.uploadUris()
Assert.assertEquals(
"Wrong result code",
@@ -124,7 +124,7 @@ class TestActivity :
override fun getStorageManager(): FileDataStorageManager {
if (!this::storage.isInitialized) {
storage = FileDataStorageManager(user, contentResolver)
storage = FileDataStorageManager(user.get(), contentResolver)
if (!storage.capabilityExistsForAccount(account.name)) {
val ocCapability = OCCapability()
@@ -67,8 +67,8 @@ public interface UserAccountManager extends CurrentAccountProvider {
* @param accountName Account name of the requested user
* @return User or empty optional if user does not exist.
*/
User getUser(CharSequence accountName);
@NonNull
Optional<User> getUser(CharSequence accountName);
User getAnonymousUser();
@@ -293,13 +293,11 @@ public class UserAccountManagerImpl implements UserAccountManager {
}
@Override
public User getUser(CharSequence accountName) {
@NonNull
public Optional<User> getUser(CharSequence accountName) {
Account account = getAccountByName(accountName.toString());
User user = createUserFromAccount(account);
if (user == null) {
throw new RuntimeException("User not found");
}
return user;
return Optional.ofNullable(user);
}
@Override
@@ -69,7 +69,8 @@ import com.owncloud.android.db.ProviderMeta
AutoMigration(from = 82, to = 83),
AutoMigration(from = 83, to = 84),
AutoMigration(from = 84, to = 85, spec = DatabaseMigrationUtil.DeleteColumnSpec::class),
AutoMigration(from = 85, to = 86, spec = DatabaseMigrationUtil.ResetCapabilitiesPostMigration::class)
AutoMigration(from = 85, to = 86, spec = DatabaseMigrationUtil.ResetCapabilitiesPostMigration::class),
AutoMigration(from = 86, to = 87, spec = DatabaseMigrationUtil.ResetCapabilitiesPostMigration::class)
],
exportSchema = true
)
@@ -9,6 +9,8 @@ package com.nextcloud.client.database.dao
import androidx.room.Dao
import androidx.room.Query
import androidx.room.RawQuery
import androidx.sqlite.db.SupportSQLiteQuery
import com.nextcloud.client.database.entity.FileEntity
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
@@ -32,9 +34,15 @@ interface FileDao {
@Query("SELECT * FROM filelist WHERE remote_id = :remoteId AND file_owner = :fileOwner LIMIT 1")
fun getFileByRemoteId(remoteId: String, fileOwner: String): FileEntity?
@Query("SELECT * FROM filelist WHERE parent = :parentId ORDER BY ${ProviderTableMeta.FILE_DEFAULT_SORT_ORDER}")
@Query("SELECT * FROM filelist WHERE parent = :parentId")
fun getFolderContent(parentId: Long): List<FileEntity>
@RawQuery
fun getFolderContentByQuery(query: SupportSQLiteQuery): List<FileEntity>
@Query("SELECT count(_id) == 0 FROM filelist WHERE parent = :parentId")
fun getFolderIsEmpty(parentId: Long): Boolean
@Query(
"SELECT * FROM filelist WHERE modified >= :startDate" +
" AND modified < :endDate" +
@@ -136,5 +136,7 @@ data class CapabilityEntity(
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_FILES_DOWNLOAD_LIMIT_DEFAULT)
val filesDownloadLimitDefault: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_RECOMMENDATION)
val recommendation: Int?
val recommendation: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_NOTES_FOLDER_PATH)
val notesFolderPath: String?
)
@@ -9,10 +9,14 @@ package com.nextcloud.client.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
@Entity(tableName = ProviderTableMeta.FILE_TABLE_NAME)
@Entity(
tableName = ProviderTableMeta.FILE_TABLE_NAME,
indices = [Index(ProviderTableMeta.FILE_PARENT)]
)
data class FileEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = ProviderTableMeta._ID)
@@ -54,7 +54,7 @@ class GeneratePdfFromImagesWork(
}
val user = userAccountManager.getUser(accountName)
require(user!= null && user !is AnonymousUser) { "Invalid or not found user" }
require(user.isPresent && user.get() !is AnonymousUser) { "Invalid or not found user" }
logger.d(
TAG,
@@ -66,7 +66,7 @@ class GeneratePdfFromImagesWork(
val result = generatePdfUseCase.execute(inputPaths, outputFilePath)
notificationManager.cancel(notificationId)
if (result) {
uploadFile(user, uploadFolder, outputFilePath)
uploadFile(user.get(), uploadFolder, outputFilePath)
cleanupImages(inputPaths)
} else {
logger.w(TAG, "PDF generation failed")
@@ -16,6 +16,7 @@ import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
@@ -51,9 +52,9 @@ class EtmBackgroundJobsFragment : EtmBaseFragment(), Injectable {
private val executionLogRow = view.findViewById<View>(R.id.etm_background_execution_logs_row)
val executionTimesRow = view.findViewById<View>(R.id.etm_background_execution_times_row)
var progressEnabled: Boolean = progressRow.visibility == View.VISIBLE
var progressEnabled: Boolean = progressRow.isVisible
get() {
return progressRow.visibility == View.VISIBLE
return progressRow.isVisible
}
set(value) {
field = value
@@ -64,9 +65,9 @@ class EtmBackgroundJobsFragment : EtmBaseFragment(), Injectable {
}
}
var logsEnabled: Boolean = executionLogRow.visibility == View.VISIBLE
var logsEnabled: Boolean = executionLogRow.isVisible
get() {
return executionLogRow.visibility == View.VISIBLE
return executionLogRow.isVisible
}
set(value) {
field = value
@@ -165,11 +166,13 @@ class EtmBackgroundJobsFragment : EtmBaseFragment(), Injectable {
return view
}
@Deprecated("Deprecated in Java")
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.fragment_etm_background_jobs, menu)
}
@Deprecated("Deprecated in Java")
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.etm_background_jobs_cancel -> {
@@ -15,6 +15,7 @@ import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
@@ -46,9 +47,9 @@ class EtmFileTransferFragment : EtmBaseFragment() {
val progress = view.findViewById<TextView>(R.id.etm_transfer_progress)
private val progressRow = view.findViewById<View>(R.id.etm_transfer_progress_row)
var progressEnabled: Boolean = progressRow.visibility == View.VISIBLE
var progressEnabled: Boolean = progressRow.isVisible
get() {
return progressRow.visibility == View.VISIBLE
return progressRow.isVisible
}
set(value) {
field = value
@@ -75,13 +75,13 @@ class AccountRemovalWork(
return Result.failure()
}
val optionalUser = userAccountManager.getUser(accountName)
if (optionalUser == null) {
if (!optionalUser.isPresent) {
// trying to delete non-existing user
return Result.failure()
}
val remoteWipe = inputData.getBoolean(REMOTE_WIPE, false)
val arbitraryDataProvider: ArbitraryDataProvider = ArbitraryDataProviderImpl(context)
val user = optionalUser
val user = optionalUser.get()
backgroundJobManager.cancelPeriodicContactsBackup(user)
val userRemoved = userAccountManager.removeUser(user)
val storageManager = FileDataStorageManager(user, context.contentResolver)
@@ -631,7 +631,9 @@ internal class BackgroundJobManagerImpl(
.setInputData(data)
.build()
workManager.enqueueUniqueWork(tag, ExistingWorkPolicy.REPLACE, request)
// Since for each file new FileDownloadWorker going to be scheduled,
// better to use ExistingWorkPolicy.KEEP policy.
workManager.enqueueUniqueWork(tag, ExistingWorkPolicy.KEEP, request)
}
override fun getFileUploads(user: User): LiveData<List<JobInfo>> {
@@ -37,7 +37,7 @@ class CalendarBackupWork(
override fun doWork(): Result {
val accountName = inputData.getString(ACCOUNT) ?: ""
val optionalUser = accountManager.getUser(accountName)
if (optionalUser == null || TextUtils.isEmpty(accountName)) {
if (!optionalUser.isPresent || TextUtils.isEmpty(accountName)) {
// no account provided
Log_OC.d(TAG, "User not present")
return Result.failure()
@@ -53,7 +53,7 @@ class CalendarBackupWork(
applicationContext,
calendar,
preferences,
optionalUser
optionalUser.get()
).start()
}
@@ -73,10 +73,10 @@ class ContactsBackupWork(
return Result.failure()
}
val optionalUser = accountManager.getUser(accountName)
if (optionalUser == null) {
if (!optionalUser.isPresent) {
return Result.failure()
}
val user = optionalUser
val user = optionalUser.get()
val lastExecution = arbitraryDataProvider.getLongValue(
user,
ContactsPreferenceActivity.PREFERENCE_CONTACTS_LAST_BACKUP
@@ -101,8 +101,8 @@ class FilesSyncWork(
}
val user = userAccountManager.getUser(syncedFolder.account)
if (user != null) {
backgroundJobManager.startFilesUploadJob(user)
if (user.isPresent) {
backgroundJobManager.startFilesUploadJob(user.get())
}
// Get changed files from ContentObserverWork (only images and videos) or by scanning filesystem
@@ -232,11 +232,11 @@ class FilesSyncWork(
val accountName = syncedFolder.account
val optionalUser = userAccountManager.getUser(accountName)
if (optionalUser == null) {
if (!optionalUser.isPresent) {
return
}
val user = optionalUser
val user = optionalUser.get()
val arbitraryDataProvider = if (lightVersion) {
ArbitraryDataProviderImpl(context)
} else {
@@ -107,7 +107,7 @@ class NotificationWork constructor(
notificationManager.cancelAll()
} else {
val user = accountManager.getUser(signatureVerification.account?.name)
?: throw RuntimeException("User not found or invalid")
.orElseThrow { RuntimeException() }
fetchCompleteNotification(user, decryptedPushMessage)
}
}
@@ -231,11 +231,11 @@ class NotificationWork constructor(
@Suppress("TooGenericExceptionCaught") // legacy code
private fun fetchCompleteNotification(account: User, decryptedPushMessage: DecryptedPushMessage) {
val optionalUser = accountManager.getUser(account.accountName)
if (optionalUser == null) {
if (!optionalUser.isPresent) {
Log_OC.e(this, "Account may not be null")
return
}
val user = optionalUser
val user = optionalUser.get()
try {
val client = OwnCloudClientFactory.createNextcloudClient(user, context)
val result = GetNotificationRemoteOperation(decryptedPushMessage.nid)
@@ -283,8 +283,8 @@ class NotificationWork constructor(
cancel(context, numericNotificationId)
try {
val optionalUser = accountManager.getUser(accountName)
if (optionalUser != null) {
val user = optionalUser
if (optionalUser.isPresent) {
val user = optionalUser.get()
val client = OwnCloudClientManagerFactory.getDefaultSingleton()
.getClientFor(user.toOwnCloudAccount(), context)
val nextcloudClient = OwnCloudClientFactory.createNextcloudClient(user, context)
@@ -0,0 +1,52 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2024 Alper Ozturk <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.client.jobs.clipboard
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.owncloud.android.lib.common.utils.Log_OC
class ClipboardClearWorker(
private val context: Context,
params: WorkerParameters
) : Worker(context, params) {
private val tag = ClipboardClearWorker::class.java.name
companion object {
const val CLIPBOARD_TEXT = "clipboard_text"
}
@Suppress("TooGenericExceptionCaught", "ReturnCount")
override fun doWork(): Result {
try {
val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val currentClip = clipboardManager.primaryClip ?: return Result.success()
val clipboardText = currentClip.getItemAt(0).text?.toString() ?: return Result.success()
val copiedText = inputData.getString(CLIPBOARD_TEXT)
if (copiedText != clipboardText) {
return Result.success()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
clipboardManager.clearPrimaryClip()
} else {
val newEmptyClip = ClipData.newPlainText("EmptyClipContent", "")
clipboardManager.setPrimaryClip(newEmptyClip)
}
return Result.success()
} catch (e: Exception) {
Log_OC.e(tag, "Error in clipboard clear worker", e)
return Result.retry()
}
}
}
@@ -11,6 +11,7 @@ import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import com.nextcloud.client.jobs.notification.WorkerNotificationManager
import com.nextcloud.utils.numberFormatter.NumberFormatter
import com.owncloud.android.R
import com.owncloud.android.operations.DownloadFileOperation
import com.owncloud.android.utils.theme.ViewThemeUtils
@@ -25,17 +26,8 @@ class DownloadNotificationManager(
) : WorkerNotificationManager(id, context, viewThemeUtils, R.string.downloader_download_in_progress_ticker) {
@Suppress("MagicNumber")
fun prepareForStart(operation: DownloadFileOperation, currentDownloadIndex: Int, totalDownloadSize: Int) {
currentOperationTitle = if (totalDownloadSize > 1) {
String.format(
context.getString(R.string.downloader_notification_manager_download_text),
currentDownloadIndex,
totalDownloadSize,
File(operation.savePath).name
)
} else {
File(operation.savePath).name
}
fun prepareForStart(operation: DownloadFileOperation) {
currentOperationTitle = File(operation.savePath).name
notificationBuilder.run {
setContentTitle(currentOperationTitle)
@@ -55,7 +47,8 @@ class DownloadNotificationManager(
@Suppress("MagicNumber")
fun updateDownloadProgress(percent: Int, totalToTransfer: Long) {
setProgress(percent, R.string.downloader_notification_manager_in_progress_text, totalToTransfer < 0)
val progressText = NumberFormatter.getPercentageText(percent)
setProgress(percent, progressText, totalToTransfer < 0)
showNotification()
}
@@ -16,7 +16,8 @@ import android.util.Pair
import androidx.core.util.component1
import androidx.core.util.component2
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.work.Worker
import androidx.work.CoroutineWorker
import androidx.work.ForegroundInfo
import androidx.work.WorkerParameters
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
@@ -38,10 +39,10 @@ import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.operations.DownloadFileOperation
import com.owncloud.android.operations.DownloadType
import com.owncloud.android.utils.theme.ViewThemeUtils
import java.security.SecureRandom
import java.util.AbstractList
import java.util.Optional
import java.util.Vector
import kotlin.random.Random
@Suppress("LongParameterList", "TooManyFunctions")
class FileDownloadWorker(
@@ -50,7 +51,7 @@ class FileDownloadWorker(
private var localBroadcastManager: LocalBroadcastManager,
private val context: Context,
params: WorkerParameters
) : Worker(context, params), OnAccountsUpdateListener, OnDatatransferProgressListener {
) : CoroutineWorker(context, params), OnAccountsUpdateListener, OnDatatransferProgressListener {
companion object {
private val TAG = FileDownloadWorker::class.java.simpleName
@@ -74,7 +75,6 @@ class FileDownloadWorker(
const val ACTIVITY_NAME = "ACTIVITY_NAME"
const val PACKAGE_NAME = "PACKAGE_NAME"
const val CONFLICT_UPLOAD_ID = "CONFLICT_UPLOAD_ID"
const val EXTRA_DOWNLOAD_RESULT = "EXTRA_DOWNLOAD_RESULT"
const val EXTRA_REMOTE_PATH = "EXTRA_REMOTE_PATH"
const val EXTRA_LINKED_TO_PATH = "EXTRA_LINKED_TO_PATH"
@@ -96,7 +96,7 @@ class FileDownloadWorker(
private val intents = FileDownloadIntents(context)
private var notificationManager = DownloadNotificationManager(
SecureRandom().nextInt(),
Random.nextInt(),
context,
viewThemeUtils
)
@@ -104,28 +104,27 @@ class FileDownloadWorker(
private var downloadProgressListener = FileDownloadProgressListener()
private var user: User? = null
private var currentUser: User? = null
private var currentUser = Optional.empty<User>()
private var currentUserFileStorageManager: FileDataStorageManager? = null
private var fileDataStorageManager: FileDataStorageManager? = null
private var downloadError: FileDownloadError? = null
@Suppress("TooGenericExceptionCaught")
override fun doWork(): Result {
@Suppress("TooGenericExceptionCaught", "ReturnCount")
override suspend fun doWork(): Result {
val foregroundInfo = createWorkerForegroundInfo()
setForeground(foregroundInfo)
return try {
val requestDownloads = getRequestDownloads()
setUser()
val remotePath = inputData.keyValueMap[FILE_REMOTE_PATH] as String? ?: return Result.failure()
val ocFile = fileDataStorageManager?.getFileByEncryptedRemotePath(remotePath) ?: return Result.failure()
val requestDownloads = getRequestDownloads(ocFile)
addAccountUpdateListener()
val foregroundInfo = ForegroundServiceHelper.createWorkerForegroundInfo(
notificationManager.getId(),
notificationManager.getNotification(),
ForegroundServiceType.DataSync
)
setForegroundAsync(foregroundInfo)
requestDownloads.forEachIndexed { currentDownloadIndex, requestedDownload ->
downloadFile(requestedDownload, currentDownloadIndex, requestDownloads.size)
requestDownloads.forEach {
downloadFile(it)
}
downloadError?.let {
@@ -133,26 +132,25 @@ class FileDownloadWorker(
notificationManager.dismissNotification()
}
setIdleWorkerState()
Log_OC.e(TAG, "FilesDownloadWorker successfully completed")
Result.success()
} catch (t: Throwable) {
notificationManager.dismissNotification()
notificationManager.showNewNotification(context.getString(R.string.downloader_unexpected_error))
Log_OC.e(TAG, "Error caught at FilesDownloadWorker(): " + t.localizedMessage)
setIdleWorkerState()
Result.failure()
} finally {
Log_OC.e(TAG, "FilesDownloadWorker cleanup")
notificationManager.dismissNotification()
setIdleWorkerState()
}
}
override fun onStopped() {
Log_OC.e(TAG, "FilesDownloadWorker stopped")
notificationManager.dismissNotification()
setIdleWorkerState()
super.onStopped()
private fun createWorkerForegroundInfo(): ForegroundInfo {
return ForegroundServiceHelper.createWorkerForegroundInfo(
notificationManager.getId(),
notificationManager.getNotification(),
ForegroundServiceType.DataSync
)
}
private fun setWorkerState(user: User?) {
@@ -167,9 +165,8 @@ class FileDownloadWorker(
pendingDownloads.remove(accountName)
}
private fun getRequestDownloads(): AbstractList<String> {
setUser()
val files = getFiles()
private fun getRequestDownloads(ocFile: OCFile): AbstractList<String> {
val files = getFiles(ocFile)
val downloadType = getDownloadType()
conflictUploadId = inputData.keyValueMap[CONFLICT_UPLOAD_ID] as Long?
@@ -218,14 +215,11 @@ class FileDownloadWorker(
private fun setUser() {
val accountName = inputData.keyValueMap[ACCOUNT_NAME] as String
user = accountManager.getUser(accountName)
user = accountManager.getUser(accountName).get()
fileDataStorageManager = FileDataStorageManager(user, context.contentResolver)
}
private fun getFiles(): List<OCFile> {
val remotePath = inputData.keyValueMap[FILE_REMOTE_PATH] as String?
val file = fileDataStorageManager?.getFileByEncryptedRemotePath(remotePath) ?: return listOf()
private fun getFiles(file: OCFile): List<OCFile> {
return if (file.isFolder) {
fileDataStorageManager?.getAllFilesRecursivelyInsideFolder(file) ?: listOf()
} else {
@@ -252,7 +246,7 @@ class FileDownloadWorker(
}
@Suppress("TooGenericExceptionCaught", "DEPRECATION")
private fun downloadFile(downloadKey: String, currentDownloadIndex: Int, totalDownloadSize: Int) {
private fun downloadFile(downloadKey: String) {
currentDownload = pendingDownloads.get(downloadKey)
if (currentDownload == null) {
@@ -269,9 +263,8 @@ class FileDownloadWorker(
}
lastPercent = 0
notificationManager.run {
prepareForStart(currentDownload!!, currentDownloadIndex + 1, totalDownloadSize)
prepareForStart(currentDownload!!)
setContentIntent(intents.detailsIntent(currentDownload!!), PendingIntent.FLAG_IMMUTABLE)
}
@@ -301,9 +294,9 @@ class FileDownloadWorker(
val currentDownloadUser = accountManager.getUser(currentDownloadAccount?.name)
if (currentUser != currentDownloadUser) {
currentUser = currentDownloadUser
currentUserFileStorageManager = FileDataStorageManager(currentUser, context.contentResolver)
currentUserFileStorageManager = FileDataStorageManager(currentUser.get(), context.contentResolver)
}
return currentDownloadUser.toOwnCloudAccount()
return currentDownloadUser.get().toOwnCloudAccount()
}
private fun getCurrentFile(): OCFile? {
@@ -51,16 +51,14 @@ open class WorkerNotificationManager(
}
@Suppress("MagicNumber")
fun setProgress(percent: Int, progressTextId: Int, indeterminate: Boolean) {
val progressText = String.format(
context.getString(progressTextId),
percent
)
fun setProgress(percent: Int, progressText: String?, indeterminate: Boolean) {
notificationBuilder.run {
setProgress(100, percent, indeterminate)
setContentTitle(currentOperationTitle)
setContentText(progressText)
progressText?.let {
setContentText(progressText)
}
}
}
@@ -150,7 +150,7 @@ class FileUploadHelper {
val connectivity = connectivityService.connectivity
val batteryStatus = powerManagementService.battery
val accountNames = accountManager.accounts.filter { account ->
accountManager.getUser(account.name) != null
accountManager.getUser(account.name).isPresent
}.map { account ->
account.name
}.toHashSet()
@@ -185,8 +185,8 @@ class FileUploadHelper {
accountNames.forEach { accountName ->
val user = accountManager.getUser(accountName)
if (user != null) {
backgroundJobManager.startFilesUploadJob(user)
if (user.isPresent) {
backgroundJobManager.startFilesUploadJob(user.get())
}
}
@@ -222,7 +222,7 @@ class FileUploadHelper {
fun removeFileUpload(remotePath: String, accountName: String) {
try {
val user = accountManager.getUser(accountName)
val user = accountManager.getUser(accountName).get()
// need to update now table in mUploadsStorageManager,
// since the operation will not get to be run by FileUploader#uploadFile
@@ -252,7 +252,7 @@ class FileUploadHelper {
}
try {
val user = accountManager.getUser(accountName)
val user = accountManager.getUser(accountName).get()
cancelAndRestartUploadJob(user)
} catch (e: NoSuchElementException) {
Log_OC.e(TAG, "Error restarting upload job because user does not exist!")
@@ -426,7 +426,7 @@ class FileUploadHelper {
fun cancel(accountName: String) {
uploadsStorageManager.removeUploads(accountName)
cancelAndRestartUploadJob(accountManager.getUser(accountName))
cancelAndRestartUploadJob(accountManager.getUser(accountName).get())
}
fun addUploadTransferProgressListener(listener: OnDatatransferProgressListener, targetKey: String) {
@@ -9,7 +9,6 @@ package com.nextcloud.client.jobs.upload
import android.app.PendingIntent
import android.content.Context
import android.provider.Settings
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.work.Worker
import androidx.work.WorkerParameters
@@ -148,7 +147,6 @@ class FileUploadWorker(
}
if (canExitEarly()) {
Log_OC.d(TAG, "Airplane mode is enabled or no internet connection, stopping worker.")
notificationManager.showConnectionErrorNotification()
return Result.failure()
}
@@ -171,27 +169,23 @@ class FileUploadWorker(
private fun canExitEarly(): Boolean {
val result = !connectivityService.isConnected ||
connectivityService.isInternetWalled ||
isStopped ||
isAirplaneModeEnabled()
isStopped
if (!result) {
if (result) {
Log_OC.d(TAG, "No internet connection, stopping worker.")
} else {
notificationManager.dismissErrorNotification()
}
return result
}
private fun isAirplaneModeEnabled(): Boolean {
return Settings.Global.getInt(context.contentResolver, Settings.Global.AIRPLANE_MODE_ON, 0) != 0
}
@Suppress("NestedBlockDepth")
private fun uploadFiles(totalUploadSize: Int, uploadsPerPage: List<OCUpload>, accountName: String) {
val user = userAccountManager.getUser(accountName)
setWorkerState(user, uploadsPerPage)
setWorkerState(user.get(), uploadsPerPage)
if (canExitEarly()) {
Log_OC.d(TAG, "Airplane mode is enabled or no internet connection, stopping worker.")
notificationManager.showConnectionErrorNotification()
return
}
@@ -203,8 +197,8 @@ class FileUploadWorker(
return@uploads
}
if (user != null) {
val uploadFileOperation = createUploadFileOperation(upload, user)
if (user.isPresent) {
val uploadFileOperation = createUploadFileOperation(upload, user.get())
currentUploadFileOperation = uploadFileOperation
@@ -216,7 +210,7 @@ class FileUploadWorker(
totalUploadSize = totalUploadSize
)
val result = upload(uploadFileOperation, user)
val result = upload(uploadFileOperation, user.get())
if (result.isSuccess) {
currentUploadIndex += 1
@@ -11,6 +11,7 @@ import android.app.PendingIntent
import android.content.Context
import com.nextcloud.client.jobs.notification.WorkerNotificationManager
import com.nextcloud.utils.extensions.isFileSpecificError
import com.nextcloud.utils.numberFormatter.NumberFormatter
import com.owncloud.android.R
import com.owncloud.android.lib.common.operations.RemoteOperationResult
import com.owncloud.android.operations.UploadFileOperation
@@ -43,10 +44,7 @@ class UploadNotificationManager(private val context: Context, viewThemeUtils: Vi
uploadFileOperation.fileName
}
val progressText = String.format(
context.getString(R.string.upload_notification_manager_upload_in_progress_text),
0
)
val progressText = NumberFormatter.getPercentageText(0)
notificationBuilder.run {
setProgress(100, 0, false)
@@ -71,7 +69,8 @@ class UploadNotificationManager(private val context: Context, viewThemeUtils: Vi
@Suppress("MagicNumber")
fun updateUploadProgress(percent: Int, currentOperation: UploadFileOperation?) {
setProgress(percent, R.string.upload_notification_manager_upload_in_progress_text, false)
val progressText = NumberFormatter.getPercentageText(percent)
setProgress(percent, progressText, false)
showNotification()
dismissOldErrorNotification(currentOperation)
}
@@ -7,6 +7,7 @@
package com.nextcloud.client.migrations
import android.content.SharedPreferences
import androidx.core.content.edit
import java.util.TreeSet
class MigrationsDb(private val migrationsDb: SharedPreferences) {
@@ -39,12 +40,12 @@ class MigrationsDb(private val migrationsDb: SharedPreferences) {
addAll(oldApplied)
addAll(migrations.map { it.toString() })
}
migrationsDb.edit().putStringSet(DB_KEY_APPLIED_MIGRATIONS, newApplied).apply()
migrationsDb.edit { putStringSet(DB_KEY_APPLIED_MIGRATIONS, newApplied) }
}
var lastMigratedVersion: Int
set(value) {
migrationsDb.edit().putInt(DB_KEY_LAST_MIGRATED_VERSION, value).apply()
migrationsDb.edit { putInt(DB_KEY_LAST_MIGRATED_VERSION, value) }
}
get() {
return migrationsDb.getInt(DB_KEY_LAST_MIGRATED_VERSION, NO_LAST_MIGRATED_VERSION)
@@ -56,17 +57,17 @@ class MigrationsDb(private val migrationsDb: SharedPreferences) {
fun setFailed(id: Int, error: String) {
migrationsDb
.edit()
.putBoolean(DB_KEY_FAILED, true)
.putString(DB_KEY_FAILED_MIGRATION_ERROR_MESSAGE, error)
.putInt(DB_KEY_FAILED_MIGRATION_ID, id)
.apply()
.edit {
putBoolean(DB_KEY_FAILED, true)
.putString(DB_KEY_FAILED_MIGRATION_ERROR_MESSAGE, error)
.putInt(DB_KEY_FAILED_MIGRATION_ID, id)
}
}
fun clearMigrations() {
migrationsDb.edit()
.putStringSet(DB_KEY_APPLIED_MIGRATIONS, emptySet())
.putInt(DB_KEY_LAST_MIGRATED_VERSION, 0)
.apply()
migrationsDb.edit {
putStringSet(DB_KEY_APPLIED_MIGRATIONS, emptySet())
.putInt(DB_KEY_LAST_MIGRATED_VERSION, 0)
}
}
}
@@ -33,8 +33,9 @@ class SessionMixin(
private set
val capabilities: OCCapability?
get() = getUser()?.let { CapabilityUtils.getCapability(it, activity) }
get() = getUser()
.map { CapabilityUtils.getCapability(it, activity) }
.orElse(null)
fun setAccount(account: Account) {
val validAccount = (accountManager.setCurrentOwnCloudAccount(account.name))
@@ -50,9 +51,9 @@ class SessionMixin(
setAccount(user.toPlatformAccount())
}
fun getUser(): User? {
fun getUser(): Optional<User> {
return if (currentAccount.isAnonymous(activity)) {
null
Optional.empty()
} else {
accountManager.getUser(currentAccount.name)
}
@@ -15,6 +15,7 @@ import android.net.Uri
import android.view.View
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import androidx.core.net.toUri
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.model.StreamEncoder
@@ -84,7 +85,7 @@ class StackRemoteViewsFactory(
widgetConfiguration = widgetRepository.getWidget(appWidgetId)
if (widgetConfiguration.user == null) {
if (!widgetConfiguration.user.isPresent) {
// TODO show error
Log_OC.e(this, "No user found!")
}
@@ -95,12 +96,12 @@ class StackRemoteViewsFactory(
override fun onDataSetChanged() {
CoroutineScope(Dispatchers.IO).launch {
try {
if (widgetConfiguration.user == null) {
if (!widgetConfiguration.user.isPresent) {
Log_OC.w(TAG, "User not present for widget update")
return@launch
}
val client = clientFactory.createNextcloudClient(widgetConfiguration.user)
val client = clientFactory.createNextcloudClient(widgetConfiguration.user.get())
val result = DashboardGetWidgetItemsRemoteOperation(widgetConfiguration.widgetId, LIMIT_SIZE)
.execute(client)
widgetItems = if (result.isSuccess) {
@@ -141,7 +142,7 @@ class StackRemoteViewsFactory(
private fun createLoadMoreView(): RemoteViews {
return RemoteViews(context.packageName, R.layout.widget_item_load_more).apply {
val clickIntent = Intent(Intent.ACTION_VIEW, Uri.parse(widgetConfiguration.moreButton?.link))
val clickIntent = Intent(Intent.ACTION_VIEW, widgetConfiguration.moreButton?.link?.toUri())
setTextViewText(R.id.load_more, widgetConfiguration.moreButton?.text)
setOnClickFillInIntent(R.id.load_more_container, clickIntent)
}
@@ -165,7 +166,7 @@ class StackRemoteViewsFactory(
updateTexts(widgetItem, this)
if (widgetItem.link.isNotEmpty()) {
val clickIntent = Intent(Intent.ACTION_VIEW, Uri.parse(widgetItem.link))
val clickIntent = Intent(Intent.ACTION_VIEW, widgetItem.link.toUri())
setOnClickFillInIntent(R.id.text_container, clickIntent)
}
}
@@ -173,7 +174,7 @@ class StackRemoteViewsFactory(
@Suppress("TooGenericExceptionCaught")
private fun loadIcon(widgetItem: DashboardWidgetItem, remoteViews: RemoteViews) {
val isIconSVG = Uri.parse(widgetItem.iconUrl).encodedPath!!.endsWith(".svg")
val isIconSVG = widgetItem.iconUrl.toUri().encodedPath!!.endsWith(".svg")
val source: FutureTarget<Bitmap> = if (isIconSVG) {
loadSVGIcon(widgetItem)
} else {
@@ -207,13 +208,13 @@ class StackRemoteViewsFactory(
.cacheDecoder(FileToStreamDecoder(SvgOrImageDecoder()))
.decoder(SvgOrImageDecoder())
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.load(Uri.parse(widgetItem.iconUrl))
.load(widgetItem.iconUrl.toUri())
.into(SVG_SIZE, SVG_SIZE)
}
private fun loadBitmapIcon(widgetItem: DashboardWidgetItem): FutureTarget<Bitmap> {
return Glide.with(context)
.using(CustomGlideStreamLoader(widgetConfiguration.user, clientFactory))
.using(CustomGlideStreamLoader(widgetConfiguration.user.get(), clientFactory))
.load(widgetItem.iconUrl)
.asBitmap()
.into(SVG_SIZE, SVG_SIZE)
@@ -16,6 +16,7 @@ import android.net.Uri
import android.os.Build
import android.view.View
import android.widget.RemoteViews
import androidx.core.net.toUri
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.model.StreamEncoder
@@ -50,7 +51,7 @@ class DashboardWidgetUpdater @Inject constructor(
) {
val intent = Intent(context, DashboardWidgetService::class.java).apply {
putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
data = Uri.parse(toUri(Intent.URI_INTENT_SCHEME))
data = toUri(Intent.URI_INTENT_SCHEME).toUri()
}
val views = RemoteViews(context.packageName, R.layout.dashboard_widget).apply {
@@ -130,7 +131,7 @@ class DashboardWidgetUpdater @Inject constructor(
val intent = Intent(context, DashboardWidgetProvider::class.java).apply {
setPackage(context.packageName)
action = DashboardWidgetProvider.OPEN_INTENT
data = Uri.parse(addButton.link)
data = addButton.link.toUri()
}
return PendingIntent.getBroadcast(
@@ -177,7 +178,7 @@ class DashboardWidgetUpdater @Inject constructor(
.cacheDecoder(FileToStreamDecoder(SvgOrImageDecoder()))
.decoder(SvgOrImageDecoder())
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.load(Uri.parse(iconUrl))
.load(iconUrl.toUri())
.into(iconTarget)
}
}
@@ -16,7 +16,7 @@ data class WidgetConfiguration(
val title: String,
val iconUrl: String,
val roundIcon: Boolean,
val user: User?,
val user: Optional<User>,
val addButton: DashboardButton?,
val moreButton: DashboardButton?
)
@@ -8,6 +8,7 @@
package com.nextcloud.client.widget
import android.content.SharedPreferences
import androidx.core.content.edit
import com.nextcloud.android.lib.resources.dashboard.DashBoardButtonType
import com.nextcloud.android.lib.resources.dashboard.DashboardButton
import com.nextcloud.android.lib.resources.dashboard.DashboardWidget
@@ -21,52 +22,52 @@ class WidgetRepository @Inject constructor(
val preferences: SharedPreferences
) {
fun saveWidget(widgetId: Int, widget: DashboardWidget, user: User) {
val editor: SharedPreferences.Editor = preferences
.edit()
.putString(PREF__WIDGET_ID + widgetId, widget.id)
.putString(PREF__WIDGET_TITLE + widgetId, widget.title)
.putString(PREF__WIDGET_ICON + widgetId, widget.iconUrl)
.putBoolean(PREF__WIDGET_ROUND_ICON + widgetId, widget.roundIcons)
.putString(PREF__WIDGET_USER + widgetId, user.accountName)
val buttonList = widget.buttons
if (buttonList != null && buttonList.isNotEmpty()) {
for (button in buttonList) {
if (button.type == DashBoardButtonType.NEW) {
editor
.putString(PREF__WIDGET_ADD_BUTTON_TYPE + widgetId, button.type.toString())
.putString(PREF__WIDGET_ADD_BUTTON_URL + widgetId, button.link)
.putString(PREF__WIDGET_ADD_BUTTON_TEXT + widgetId, button.text)
}
if (button.type == DashBoardButtonType.MORE) {
editor
.putString(PREF__WIDGET_MORE_BUTTON_TYPE + widgetId, button.type.toString())
.putString(PREF__WIDGET_MORE_BUTTON_URL + widgetId, button.link)
.putString(PREF__WIDGET_MORE_BUTTON_TEXT + widgetId, button.text)
preferences
.edit {
putString(PREF__WIDGET_ID + widgetId, widget.id)
.putString(PREF__WIDGET_TITLE + widgetId, widget.title)
.putString(PREF__WIDGET_ICON + widgetId, widget.iconUrl)
.putBoolean(PREF__WIDGET_ROUND_ICON + widgetId, widget.roundIcons)
.putString(PREF__WIDGET_USER + widgetId, user.accountName)
val buttonList = widget.buttons
if (!buttonList.isNullOrEmpty()) {
for (button in buttonList) {
if (button.type == DashBoardButtonType.NEW) {
this
.putString(PREF__WIDGET_ADD_BUTTON_TYPE + widgetId, button.type.toString())
.putString(PREF__WIDGET_ADD_BUTTON_URL + widgetId, button.link)
.putString(PREF__WIDGET_ADD_BUTTON_TEXT + widgetId, button.text)
}
if (button.type == DashBoardButtonType.MORE) {
this
.putString(PREF__WIDGET_MORE_BUTTON_TYPE + widgetId, button.type.toString())
.putString(PREF__WIDGET_MORE_BUTTON_URL + widgetId, button.link)
.putString(PREF__WIDGET_MORE_BUTTON_TEXT + widgetId, button.text)
}
}
}
}
}
editor.apply()
}
fun deleteWidget(widgetId: Int) {
preferences
.edit()
.remove(PREF__WIDGET_ID + widgetId)
.remove(PREF__WIDGET_TITLE + widgetId)
.remove(PREF__WIDGET_ICON + widgetId)
.remove(PREF__WIDGET_ROUND_ICON + widgetId)
.remove(PREF__WIDGET_USER + widgetId)
.remove(PREF__WIDGET_ADD_BUTTON_TEXT + widgetId)
.remove(PREF__WIDGET_ADD_BUTTON_URL + widgetId)
.remove(PREF__WIDGET_ADD_BUTTON_TYPE + widgetId)
.remove(PREF__WIDGET_MORE_BUTTON_TEXT + widgetId)
.remove(PREF__WIDGET_MORE_BUTTON_URL + widgetId)
.remove(PREF__WIDGET_MORE_BUTTON_TYPE + widgetId)
.apply()
.edit {
remove(PREF__WIDGET_ID + widgetId)
.remove(PREF__WIDGET_TITLE + widgetId)
.remove(PREF__WIDGET_ICON + widgetId)
.remove(PREF__WIDGET_ROUND_ICON + widgetId)
.remove(PREF__WIDGET_USER + widgetId)
.remove(PREF__WIDGET_ADD_BUTTON_TEXT + widgetId)
.remove(PREF__WIDGET_ADD_BUTTON_URL + widgetId)
.remove(PREF__WIDGET_ADD_BUTTON_TYPE + widgetId)
.remove(PREF__WIDGET_MORE_BUTTON_TEXT + widgetId)
.remove(PREF__WIDGET_MORE_BUTTON_URL + widgetId)
.remove(PREF__WIDGET_MORE_BUTTON_TYPE + widgetId)
}
}
fun getWidget(widgetId: Int): WidgetConfiguration {
val userOptional: User? =
val userOptional: Optional<User> =
userAccountManager.getUser(preferences.getString(PREF__WIDGET_USER + widgetId, ""))
val addButton = createAddButton(widgetId)
@@ -86,8 +86,9 @@ class ChooseStorageLocationDialogFragment : DialogFragment(), Injectable {
private fun setupLocationSelection() {
updateStorageTypeSelection()
val currentStorageLocation = getCurrentStorageLocation() ?: return
val radioButton = when (getCurrentStorageLocation().storageType) {
val radioButton = when (currentStorageLocation.storageType) {
StorageType.EXTERNAL -> binding.storageExternalRadio
else -> binding.storageInternalRadio
}
@@ -103,7 +104,7 @@ class ChooseStorageLocationDialogFragment : DialogFragment(), Injectable {
}
val storagePath =
storagePoints.firstOrNull { it.storageType == storageType && it.privacyType == privacyType }?.path
storagePoints.find { it.storageType == storageType && it.privacyType == privacyType }?.path
return storagePath?.let {
val file = File(it)
@@ -136,16 +137,17 @@ class ChooseStorageLocationDialogFragment : DialogFragment(), Injectable {
binding.storageExternalRadio.text = getStoragePointLabel(StorageType.EXTERNAL, selectedPrivacyType)
}
private fun getCurrentStorageLocation(): StoragePoint {
private fun getCurrentStorageLocation(): StoragePoint? {
val appContext = MainApp.getAppContext()
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(appContext)
val storagePath = sharedPreferences.getString(AppPreferencesImpl.STORAGE_PATH, appContext.filesDir.absolutePath)
return storagePoints.first { it.path == storagePath }
return storagePoints.find { it.path == storagePath }
}
private fun notifyResult() {
val newPath =
storagePoints.first { it.storageType == selectedStorageType && it.privacyType == selectedPrivacyType }
storagePoints.find { it.storageType == selectedStorageType && it.privacyType == selectedPrivacyType }
?: return
val resultBundle = Bundle().apply {
putString(KEY_RESULT_STORAGE_LOCATION, newPath.path)
@@ -11,7 +11,6 @@ import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.drawable.LayerDrawable
import android.net.Uri
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
@@ -19,6 +18,7 @@ import android.view.View
import android.view.ViewGroup
import androidx.annotation.VisibleForTesting
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.fragment.app.Fragment
import com.nextcloud.android.common.ui.theme.utils.ColorRole
import com.nextcloud.client.NominatimClient
@@ -356,7 +356,7 @@ class ImageDetailFragment : Fragment(), Injectable {
private fun markerOnGestureListener(latitude: Double, longitude: Double) =
object : OnItemGestureListener<OverlayItem> {
override fun onItemSingleTapUp(index: Int, item: OverlayItem): Boolean {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=$latitude,$longitude"))
val intent = Intent(Intent.ACTION_VIEW, "geo:0,0?q=$latitude,$longitude".toUri())
DisplayUtils.startIntentIfAppAvailable(intent, activity, R.string.no_map_app_availble)
return true
}
@@ -0,0 +1,73 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 ZetaTom <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.utils
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import androidx.core.net.toUri
import com.nextcloud.client.account.User
import com.owncloud.android.ui.activity.FileDisplayActivity
import java.util.Optional
import kotlin.jvm.optionals.getOrNull
object LinkHelper {
const val APP_NEXTCLOUD_NOTES = "it.niedermann.owncloud.notes"
const val APP_NEXTCLOUD_TALK = "com.nextcloud.talk2"
/**
* Open specified app and, if not installed redirect to corresponding download.
*
* @param packageName of app to be opened
* @param user to pass in intent
*/
fun openAppOrStore(packageName: String, user: Optional<User>, context: Context) {
openAppOrStore(packageName, user.getOrNull(), context)
}
/**
* Open specified app and, if not installed redirect to corresponding download.
*
* @param packageName of app to be opened
* @param user to pass in intent
*/
fun openAppOrStore(packageName: String, user: User?, context: Context) {
val intent = context.packageManager.getLaunchIntentForPackage(packageName)
if (intent != null) {
// app installed - open directly
// TODO handle null user?
intent.putExtra(FileDisplayActivity.KEY_ACCOUNT, user.hashCode())
context.startActivity(intent)
} else {
// app not found - open market (Google Play Store, F-Droid, etc.)
openAppStore(packageName, false, context)
}
}
/**
* Open app store page of specified app or search for specified string. Will attempt to open browser when no app
* store is available.
*
* @param string packageName or url-encoded search string
* @param search false -> show app corresponding to packageName; true -> open search for string
*/
fun openAppStore(string: String, search: Boolean = false, context: Context) {
var suffix = (if (search) "search?q=" else "details?id=") + string
val intent = Intent(Intent.ACTION_VIEW, "market://$suffix".toUri())
try {
context.startActivity(intent)
} catch (activityNotFoundException1: ActivityNotFoundException) {
// all is lost: open google play store web page for app
if (!search) {
suffix = "apps/$suffix"
}
intent.setData("https://play.google.com/store/$suffix".toUri())
context.startActivity(intent)
}
}
}
@@ -14,12 +14,13 @@ import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.createBitmap
import androidx.core.graphics.drawable.IconCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.core.graphics.drawable.toDrawable
import com.nextcloud.client.account.User
import com.owncloud.android.R
import com.owncloud.android.datamodel.OCFile
@@ -97,8 +98,8 @@ class ShortcutUtil @Inject constructor(private val mContext: Context) {
private fun bitmapToAdaptiveBitmap(orig: Bitmap): Bitmap {
val adaptiveIconSize = mContext.resources.getDimensionPixelSize(R.dimen.adaptive_icon_size)
val adaptiveIconOuterSides = mContext.resources.getDimensionPixelSize(R.dimen.adaptive_icon_padding)
val drawable: Drawable = BitmapDrawable(mContext.resources, orig)
val bitmap = Bitmap.createBitmap(adaptiveIconSize, adaptiveIconSize, Bitmap.Config.ARGB_8888)
val drawable: Drawable = orig.toDrawable(mContext.resources)
val bitmap = createBitmap(adaptiveIconSize, adaptiveIconSize)
val canvas = Canvas(bitmap)
drawable.setBounds(
adaptiveIconOuterSides,
@@ -14,24 +14,26 @@ import com.nextcloud.utils.extensions.shouldRemoveNonPrintableUnicodeCharactersA
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.lib.resources.status.NextcloudVersion
import com.owncloud.android.lib.resources.status.OCCapability
import org.apache.commons.io.FilenameUtils
import java.util.regex.Pattern
object AutoRename {
private const val REPLACEMENT = "_"
@Suppress("NestedBlockDepth")
fun rename(filename: String, capability: OCCapability, isFolderPath: Boolean = false): String {
fun rename(filename: String, capability: OCCapability): String {
if (!capability.version.isNewerOrEqual(NextcloudVersion.nextcloud_30)) {
return filename
}
val isFolder = filename.endsWith(OCFile.PATH_SEPARATOR)
val pathSegments = filename.split(OCFile.PATH_SEPARATOR).toMutableList()
capability.run {
if (forbiddenFilenameCharactersJson != null) {
var forbiddenFilenameCharacters = capability.forbiddenFilenameCharacters()
if (isFolderPath) {
if (isFolder) {
forbiddenFilenameCharacters = forbiddenFilenameCharacters.filter { it != OCFile.PATH_SEPARATOR }
}
@@ -70,32 +72,27 @@ object AutoRename {
replaceFileExtensions(forbiddenExtension, segment)
}
}
pathSegments.replaceAll { segment ->
lowercaseFileExtension(segment)
}
}
}
val result = pathSegments.joinToString(OCFile.PATH_SEPARATOR)
val filenameWithExtension = pathSegments.joinToString(OCFile.PATH_SEPARATOR)
val result = if (isFolder) filenameWithExtension else lowercaseFileExtension(filenameWithExtension)
return if (capability.shouldRemoveNonPrintableUnicodeCharactersAndConvertToUTF8()) {
val utf8Result = convertToUTF8(result)
removeNonPrintableUnicodeCharacters(utf8Result)
} else {
result
}
}.trim()
}
private fun lowercaseFileExtension(input: String): String {
val lastDotIndex = input.lastIndexOf('.')
return if (lastDotIndex > 0) {
val base = input.substring(0, lastDotIndex)
val extension = input.substring(lastDotIndex + 1).lowercase() // Convert extension to lowercase
"$base.$extension"
private fun lowercaseFileExtension(filename: String): String {
val extension = FilenameUtils.getExtension(filename).lowercase()
val filenameWithoutExtension = FilenameUtils.removeExtension(filename)
return if (extension.isNotEmpty()) {
filenameWithoutExtension + StringConstants.DOT + extension
} else {
input
filenameWithoutExtension
}
}
@@ -1,39 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2024 Alper Ozturk <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.utils.extensions
import android.view.View
import android.view.Window
import android.view.WindowManager
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
fun Window?.setNoLimitLayout() {
val flag = WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
this?.setFlags(flag, flag)
}
fun Window?.addSystemBarPaddings() {
if (this == null) {
return
}
ViewCompat.setOnApplyWindowInsetsListener(decorView) { v: View, insets: WindowInsetsCompat ->
val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.updatePadding(
left = bars.left,
top = bars.top,
right = bars.right,
bottom = bars.bottom
)
WindowInsetsCompat.CONSUMED
}
}
@@ -0,0 +1,21 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2024 Alper Ozturk <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.utils.numberFormatter
import java.text.NumberFormat
import java.util.Locale
object NumberFormatter {
@Suppress("MagicNumber")
fun getPercentageText(percent: Int): String {
val formatter = NumberFormat.getPercentInstance(Locale.getDefault())
formatter.maximumFractionDigits = 0
return formatter.format(percent / 100.0)
}
}
@@ -66,7 +66,7 @@ class LauncherActivity : BaseActivity() {
private fun scheduleSplashScreen() {
Handler(Looper.getMainLooper()).postDelayed({
if (user != null) {
if (user.isPresent) {
if (MDMConfig.enforceProtection(this) && appPreferences.lockPreference == SettingsActivity.LOCK_NONE) {
startActivity(Intent(this, SettingsActivity::class.java))
} else {
@@ -327,53 +327,54 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
}
initServerPreFragment(savedInstanceState);
ProcessLifecycleOwner.get().getLifecycle().addObserver(lifecycleEventObserver);
}
ProcessLifecycleOwner.get().getLifecycle().addObserver(lifecycleEventObserver);
}
private void showEnforcedServers() {
showAuthStatus();
accountSetupBinding.hostUrlFrame.setVisibility(View.GONE);
accountSetupBinding.hostUrlInputHelperText.setVisibility(View.GONE);
accountSetupBinding.scanQr.setVisibility(View.GONE);
accountSetupBinding.serversSpinner.setVisibility(View.VISIBLE);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.enforced_servers_spinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
private void showEnforcedServers() {
showAuthStatus();
accountSetupBinding.hostUrlFrame.setVisibility(View.GONE);
accountSetupBinding.hostUrlInputHelperText.setVisibility(View.GONE);
accountSetupBinding.scanQr.setVisibility(View.GONE);
accountSetupBinding.serversSpinner.setVisibility(View.VISIBLE);
ArrayList<String> servers = new ArrayList<>();
servers.add("");
adapter.add(getString(R.string.please_select_a_server));
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.enforced_servers_spinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ArrayList<EnforcedServer> t = new Gson().fromJson(getString(R.string.enforce_servers),
new TypeToken<ArrayList<EnforcedServer>>() {
}
.getType());
ArrayList<String> servers = new ArrayList<>();
servers.add("");
adapter.add(getString(R.string.please_select_a_server));
for (EnforcedServer e : t) {
adapter.add(e.getName());
servers.add(e.getUrl());
ArrayList<EnforcedServer> t = new Gson().fromJson(getString(R.string.enforce_servers),
new TypeToken<ArrayList<EnforcedServer>>() {
}
.getType());
for (EnforcedServer e : t) {
adapter.add(e.getName());
servers.add(e.getUrl());
}
accountSetupBinding.serversSpinner.setAdapter(adapter);
accountSetupBinding.serversSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String url = servers.get(position);
if (URLUtil.isValidUrl(url)) {
accountSetupBinding.hostUrlInput.setText(url);
checkOcServer();
}
}
accountSetupBinding.serversSpinner.setAdapter(adapter);
accountSetupBinding.serversSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String url = servers.get(position);
if (URLUtil.isValidUrl(url)) {
accountSetupBinding.hostUrlInput.setText(url);
checkOcServer();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// do nothing
}
});
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// do nothing
}
});
}
private final LifecycleEventObserver lifecycleEventObserver = ((lifecycleOwner, event) -> {
if (event == Lifecycle.Event.ON_START && token != null) {
@@ -1204,12 +1205,12 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
private void getUserCapabilitiesAndFinish() {
final Handler handler = new Handler();
final User user = accountManager.getUser(mAccount.name);
final Optional<User> user = accountManager.getUser(mAccount.name);
if (user != null) {
if (user.isPresent()) {
Executors.newSingleThreadExecutor().execute(() -> {
try {
final FileDataStorageManager storageManager = new FileDataStorageManager(user, getContentResolver());
final FileDataStorageManager storageManager = new FileDataStorageManager(user.get(), getContentResolver());
new GetCapabilitiesOperation(storageManager).execute(MainApp.getAppContext());
handler.post(this::endSuccess);
} catch (Exception e) {
@@ -13,8 +13,8 @@ package com.owncloud.android.authentication
import android.app.Activity
import android.content.Context
import android.net.Uri
import android.os.AsyncTask
import androidx.core.net.toUri
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.lib.common.OwnCloudClientFactory
import com.owncloud.android.lib.common.OwnCloudCredentials
@@ -46,7 +46,7 @@ class AuthenticatorAsyncTask(activity: Activity) : AsyncTask<Any?, Void?, Remote
val context = mWeakContext.get()
// Client
val uri = Uri.parse(url)
val uri = url.toUri()
val nextcloudClient = OwnCloudClientFactory.createNextcloudClient(
uri,
credentials.username,
@@ -13,6 +13,7 @@
*/
package com.owncloud.android.datamodel;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.content.ContentProviderClient;
import android.content.ContentProviderOperation;
@@ -65,6 +66,7 @@ import com.owncloud.android.lib.resources.status.E2EVersion;
import com.owncloud.android.lib.resources.status.OCCapability;
import com.owncloud.android.lib.resources.tags.Tag;
import com.owncloud.android.operations.RemoteOperationFailedException;
import com.owncloud.android.utils.FileSortOrder;
import com.owncloud.android.utils.FileStorageUtils;
import com.owncloud.android.utils.MimeType;
import com.owncloud.android.utils.MimeTypeUtil;
@@ -87,9 +89,12 @@ import java.util.Set;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.sqlite.db.SimpleSQLiteQuery;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import kotlin.Pair;
import static com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID;
@SuppressFBWarnings("CE")
public class FileDataStorageManager {
private static final String TAG = FileDataStorageManager.class.getSimpleName();
@@ -455,6 +460,28 @@ public class FileDataStorageManager {
}
}
public List<OCFile> getFolderContent(OCFile directory,
boolean onlyOnDevice,
boolean showHiddenFiles,
String mimeType,
boolean limitToPersonalFiles,
FileSortOrder sortOrder) {
if (directory != null && directory.isFolder() && directory.fileExists()) {
return getFolderContent(directory.getFileId(),
onlyOnDevice,
showHiddenFiles,
mimeType,
limitToPersonalFiles,
sortOrder);
} else {
return new ArrayList<>();
}
}
public boolean getFolderIsEmpty(OCFile ocFile) {
return fileDao.getFolderIsEmpty(ocFile.getFileId());
}
public OCFile findDuplicatedFile(OCFile parentFolder, ServerFileInterface newFile) {
List<OCFile> folderContent = getFolderContent(parentFolder, false);
if (folderContent == null || folderContent.isEmpty()) {
@@ -1177,6 +1204,72 @@ public class FileDataStorageManager {
return folderContent;
}
private List<OCFile> getFolderContent(long fileId,
boolean onlyOnDevice,
boolean showHiddenFiles,
String mimeType,
boolean limitToPersonalFiles,
FileSortOrder sortOrder) {
Log_OC.d(TAG, "getFolderContent - start");
List<OCFile> folderContent = new ArrayList<>();
String query = "SELECT * FROM filelist WHERE parent = ?";
ArrayList<String> args = new ArrayList<>();
args.add(String.valueOf(fileId));
if (!showHiddenFiles) {
query += " AND filename NOT LIKE '.%'";
}
if (!TextUtils.isEmpty(mimeType)) {
query += " AND content_type LIKE ?";
args.add(mimeType + "%");
}
if (limitToPersonalFiles) {
String userId = AccountManager.get(MainApp.getAppContext()).getUserData(user.toPlatformAccount(), KEY_USER_ID);
query += " AND owner_id LIKE ? AND (permissions IS NULL OR (permissions NOT LIKE '%S%' AND permissions NOT LIKE '%M%'))";
args.add(userId);
}
// sort A-Z
if (sortOrder == FileSortOrder.SORT_A_TO_Z) {
query += " ORDER BY favorite DESC, filename ASC";
}
if (sortOrder == FileSortOrder.SORT_Z_TO_A) {
query += " ORDER BY favorite DESC, filename DESC";
}
if (sortOrder == FileSortOrder.SORT_OLD_TO_NEW) {
query += " ORDER BY favorite DESC, created ASC";
}
if (sortOrder == FileSortOrder.SORT_NEW_TO_OLD) {
query += " ORDER BY favorite DESC, created DESC";
}
if (sortOrder == FileSortOrder.SORT_SMALL_TO_BIG) {
query += " ORDER BY favorite DESC, content_length ASC";
}
if (sortOrder == FileSortOrder.SORT_BIG_TO_SMALL) {
query += " ORDER BY favorite DESC, content_length DESC";
}
List<FileEntity> files = fileDao.getFolderContentByQuery(new SimpleSQLiteQuery(query, args.toArray()));
for (FileEntity fileEntity : files) {
OCFile child = createFileInstance(fileEntity);
if (!onlyOnDevice || child.existsOnDevice()) {
folderContent.add(child);
}
}
Log_OC.d(TAG, "getFolderContent - finished");
return folderContent;
}
private OCFile createRootDir() {
OCFile ocFile = new OCFile(OCFile.ROOT_PATH);
@@ -2315,6 +2408,8 @@ public class FileDataStorageManager {
contentValues.put(ProviderTableMeta.CAPABILITIES_RECOMMENDATION, capability.getRecommendations().getValue());
contentValues.put(ProviderTableMeta.CAPABILITIES_NOTES_FOLDER_PATH, capability.getNotesFolderPath());
return contentValues;
}
@@ -2490,7 +2585,10 @@ public class FileDataStorageManager {
capability.setForbiddenFilenameBaseNamesJson(getString(cursor, ProviderTableMeta.CAPABILITIES_FORBIDDEN_FORBIDDEN_FILENAME_BASE_NAMES));
capability.setFilesDownloadLimit(getBoolean(cursor, ProviderTableMeta.CAPABILITIES_FILES_DOWNLOAD_LIMIT));
capability.setFilesDownloadLimitDefault(getInt(cursor, ProviderTableMeta.CAPABILITIES_FILES_DOWNLOAD_LIMIT_DEFAULT));
capability.setRecommendations(getBoolean(cursor, ProviderTableMeta.CAPABILITIES_RECOMMENDATION));
capability.setNotesFolderPath(getString(cursor, ProviderTableMeta.CAPABILITIES_NOTES_FOLDER_PATH));
}
return capability;
@@ -762,7 +762,7 @@ public class OCFile implements Parcelable, Comparable<OCFile>, ServerFileInterfa
}
public boolean isShared() {
return isSharedViaLink() || isSharedWithSharee() || isSharedWithMe();
return isSharedViaLink() || isSharedWithSharee() || isSharedWithMe() || !sharees.isEmpty();
}
public String getPermissions() {
@@ -0,0 +1,13 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Tobias Kaminsky <tobias.kaminsky@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.datamodel
enum class SharesType {
INTERNAL,
EXTERNAL
}
@@ -670,8 +670,7 @@ public final class ThumbnailsCacheManager {
int pxH;
pxW = pxH = getThumbnailDimension();
if (file instanceof OCFile) {
OCFile ocFile = (OCFile) file;
if (file instanceof OCFile ocFile) {
if (ocFile.isDown()) {
Bitmap bitmap;
if (MimeTypeUtil.isVideo(ocFile)) {
@@ -1151,8 +1150,7 @@ public final class ThumbnailsCacheManager {
public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
if (imageView != null) {
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncThumbnailDrawable) {
final AsyncThumbnailDrawable asyncDrawable = (AsyncThumbnailDrawable) drawable;
if (drawable instanceof AsyncThumbnailDrawable asyncDrawable) {
return asyncDrawable.getBitmapWorkerTask();
}
}
@@ -1162,8 +1160,7 @@ public final class ThumbnailsCacheManager {
private static ResizedImageGenerationTask getResizedImageGenerationWorkerTask(ImageView imageView) {
if (imageView != null) {
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncResizedImageDrawable) {
final AsyncResizedImageDrawable asyncDrawable = (AsyncResizedImageDrawable) drawable;
if (drawable instanceof AsyncResizedImageDrawable asyncDrawable) {
return asyncDrawable.getBitmapWorkerTask();
}
}
@@ -1173,8 +1170,7 @@ public final class ThumbnailsCacheManager {
private static GalleryImageGenerationTask getGalleryImageGenerationTask(ImageView imageView) {
if (imageView != null) {
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncGalleryImageDrawable) {
final AsyncGalleryImageDrawable asyncDrawable = (AsyncGalleryImageDrawable) drawable;
if (drawable instanceof AsyncGalleryImageDrawable asyncDrawable) {
return asyncDrawable.getBitmapWorkerTask();
}
}
@@ -590,7 +590,7 @@ public class UploadsStorageManager extends Observable {
String remotePath = c.getString(c.getColumnIndexOrThrow(ProviderTableMeta.UPLOADS_REMOTE_PATH));
if (capability != null) {
remotePath = AutoRename.INSTANCE.rename(remotePath, capability,true);
remotePath = AutoRename.INSTANCE.rename(remotePath, capability);
}
String accountName = c.getString(c.getColumnIndexOrThrow(ProviderTableMeta.UPLOADS_ACCOUNT_NAME));
@@ -44,7 +44,7 @@ abstract class AbstractCommandLineStoragePoint extends AbstractStoragePointProvi
process.waitFor();
final InputStream is = process.getInputStream();
final byte buffer[] = new byte[1024];
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s.append(new String(buffer, "UTF8"));
}
@@ -49,7 +49,7 @@ public class MountCommandStoragePointProvider extends AbstractCommandLineStorage
for (String line : mounted.split("\n")) {
if (!line.toLowerCase(Locale.US).contains("asec") && sPattern.matcher(line).matches()) {
String parts[] = line.split(" ");
String[] parts = line.split(" ");
for (String path : parts) {
if (path.length() > 0 && path.charAt(0) == '/' && !path.toLowerCase(Locale.US).contains("vold")) {
result.add(path);
@@ -44,7 +44,7 @@ public class VDCStoragePointProvider extends AbstractCommandLineStoragePoint {
List<StoragePoint> result = new Vector<>();
for (String line : vdcResources.split("\n")) {
String vdcLine[] = line.split(" ");
String[] vdcLine = line.split(" ");
try {
int status = Integer.parseInt(vdcLine[0]);
if (status != sVDCVolumeList) {
@@ -292,10 +292,9 @@ public class OCUpload implements Parcelable {
@SuppressFBWarnings("SEO_SUBOPTIMAL_EXPRESSION_ORDER")
public boolean isSame(@Nullable Object obj) {
if (!(obj instanceof OCUpload)) {
if (!(obj instanceof OCUpload other)) {
return false;
}
OCUpload other = (OCUpload) obj;
return this.uploadId == other.uploadId &&
localPath.equals(other.localPath) &&
remotePath.equals(other.remotePath) &&
@@ -25,7 +25,7 @@ import java.util.List;
*/
public class ProviderMeta {
public static final String DB_NAME = "filelist";
public static final int DB_VERSION = 86;
public static final int DB_VERSION = 88;
private ProviderMeta() {
// No instance
@@ -272,6 +272,7 @@ public class ProviderMeta {
public static final String CAPABILITIES_FORBIDDEN_FORBIDDEN_FILENAME_BASE_NAMES = "forbidden_filename_basenames";
public static final String CAPABILITIES_FILES_DOWNLOAD_LIMIT = "files_download_limit";
public static final String CAPABILITIES_FILES_DOWNLOAD_LIMIT_DEFAULT = "files_download_limit_default";
public static final String CAPABILITIES_NOTES_FOLDER_PATH = "notes_folder_path";
//Columns of Uploads table
public static final String UPLOADS_LOCAL_PATH = "local_path";
@@ -413,7 +413,7 @@ public class UploadFileOperation extends SyncOperation {
String remoteParentPath = new File(getRemotePath()).getParent();
remoteParentPath = remoteParentPath.endsWith(OCFile.PATH_SEPARATOR) ? remoteParentPath : remoteParentPath + OCFile.PATH_SEPARATOR;
remoteParentPath = AutoRename.INSTANCE.rename(remoteParentPath, getCapabilities(), true);
remoteParentPath = AutoRename.INSTANCE.rename(remoteParentPath, getCapabilities());
OCFile parent = getStorageManager().getFileByPath(remoteParentPath);
@@ -756,7 +756,8 @@ public class UploadFileOperation extends SyncOperation {
throws InvalidAlgorithmParameterException, UploadException, NoSuchPaddingException, IllegalBlockSizeException, CertificateException,
NoSuchAlgorithmException, BadPaddingException, InvalidKeyException {
mFile.setDecryptedRemotePath(e2eFiles.getParentFile().getDecryptedRemotePath() + e2eFiles.getOriginalFile().getName());
final var filename = new File(mFile.getRemotePath()).getName();
mFile.setDecryptedRemotePath(e2eFiles.getParentFile().getDecryptedRemotePath() + filename);
mFile.setRemotePath(e2eFiles.getParentFile().getRemotePath() + e2eData.getEncryptedFileName());
@@ -773,9 +773,9 @@ public class OperationsService extends Service {
@NonNull
private User toUser(@Nullable Account account) {
String accountName = account != null ? account.name : "";
User optionalUser = accountManager.getUser(accountName);
if (optionalUser != null) {
return optionalUser;
Optional<User> optionalUser = accountManager.getUser(accountName);
if (optionalUser.isPresent()) {
return optionalUser.get();
} else {
return accountManager.getAnonymousUser();
}
@@ -79,11 +79,7 @@ abstract class AbstractOwnCloudSyncAdapter extends
public User getUser() {
Account account = getAccount();
String accountName = account != null ? account.name : null;
User user = userAccountManager.getUser(accountName);
if (user == null) {
user = userAccountManager.getAnonymousUser();
}
return user;
return userAccountManager.getUser(accountName).orElseGet(userAccountManager::getAnonymousUser);
}
public ContentProviderClient getContentProviderClient() {
@@ -54,9 +54,7 @@ public class ThemeableSwitchPreference extends SwitchPreference {
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View child = viewGroup.getChildAt(i);
if (child instanceof Switch) {
Switch switchView = (Switch) child;
if (child instanceof Switch switchView) {
viewThemeUtils.platform.colorSwitch(switchView);
break;
@@ -12,7 +12,6 @@ import android.view.MenuItem;
import android.view.View;
import com.google.android.material.snackbar.Snackbar;
import com.nextcloud.client.account.User;
import com.nextcloud.client.network.ClientFactory;
import com.nextcloud.common.NextcloudClient;
import com.owncloud.android.R;
@@ -196,18 +195,10 @@ public class ActivitiesActivity extends DrawerActivity implements ActivityListIn
} else {
showDetailsIntent = new Intent(getBaseContext(), FileDisplayActivity.class);
}
showDetailsIntent.putExtra(EXTRA_FILE, ocFile);
User user = getUser();
if (user == null) {
throw new RuntimeException("User not found");
}
showDetailsIntent.putExtra(EXTRA_USER, user);
showDetailsIntent.putExtra(EXTRA_USER, getUser().orElseThrow(RuntimeException::new));
startActivity(showDetailsIntent);
}
@Override
@@ -91,16 +91,12 @@ public class FilesServiceApiImpl implements FilesServiceApi {
if (remoteOcFile.isFolder()) {
// perform folder synchronization
User user = baseActivity.getUser();
if (user == null) {
throw new RuntimeException("User not found");
}
RemoteOperation synchFolderOp = new RefreshFolderOperation(remoteOcFile,
System.currentTimeMillis(),
false,
true,
baseActivity.getStorageManager(),
user,
baseActivity.getUser().orElseThrow(RuntimeException::new),
context);
synchFolderOp.execute(ownCloudClient);
}
@@ -9,10 +9,9 @@ package com.owncloud.android.ui.activity;
import android.accounts.Account;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import com.nextcloud.android.common.ui.util.extensions.AppCompatActivityExtensionsKt;
import com.nextcloud.client.account.User;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.di.Injectable;
@@ -20,7 +19,6 @@ import com.nextcloud.client.mixins.MixinRegistry;
import com.nextcloud.client.mixins.SessionMixin;
import com.nextcloud.client.preferences.AppPreferences;
import com.nextcloud.client.preferences.DarkMode;
import com.nextcloud.utils.extensions.WindowExtensionsKt;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.utils.Log_OC;
@@ -30,8 +28,6 @@ import java.util.Optional;
import javax.inject.Inject;
import androidx.activity.EdgeToEdge;
import androidx.activity.SystemBarStyle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
@@ -69,13 +65,7 @@ public abstract class BaseActivity extends AppCompatActivity implements Injectab
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
boolean isApiLevel35OrHigher = (Build.VERSION.SDK_INT >= 35);
if (isApiLevel35OrHigher) {
enableEdgeToEdge();
WindowExtensionsKt.addSystemBarPaddings(getWindow());
}
AppCompatActivityExtensionsKt.adjustUIForAPILevel35(this);
super.onCreate(savedInstanceState);
sessionMixin = new SessionMixin(this, accountManager);
mixinRegistry.add(sessionMixin);
@@ -85,11 +75,6 @@ public abstract class BaseActivity extends AppCompatActivity implements Injectab
}
}
private void enableEdgeToEdge() {
final var style = SystemBarStyle.auto(Color.TRANSPARENT, Color.TRANSPARENT);
EdgeToEdge.enable(this, style, style);
}
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
@@ -188,7 +173,7 @@ public abstract class BaseActivity extends AppCompatActivity implements Injectab
return sessionMixin.getCurrentAccount();
}
public User getUser() {
public Optional<User> getUser() {
return sessionMixin.getUser();
}
@@ -102,7 +102,7 @@ class ConflictsResolveActivity : FileActivity(), OnConflictDecisionMadeListener
val file = newFile
// version
val user = requireNotNull(user) { "User not found" }
val user = user.orElseThrow { RuntimeException() }
val offlineOperation = if (offlineOperationPath != null) {
fileDataStorageManager.offlineOperationDao.getByPath(offlineOperationPath!!)
@@ -120,11 +120,19 @@ class ConflictsResolveActivity : FileActivity(), OnConflictDecisionMadeListener
else -> Unit
}
updateThumbnailIfNeeded(decision, file)
dismissConflictResolveNotification(file)
finish()
}
}
private fun updateThumbnailIfNeeded(decision: Decision?, file: OCFile?) {
if (decision == Decision.KEEP_BOTH || decision == Decision.KEEP_LOCAL) {
file?.isUpdateThumbnailNeeded = true
fileDataStorageManager.saveFile(file)
}
}
private fun dismissConflictResolveNotification(file: OCFile?) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val tag = NotificationUtils.createUploadNotificationTag(file)
@@ -193,7 +201,7 @@ class ConflictsResolveActivity : FileActivity(), OnConflictDecisionMadeListener
// Overwrite local file
file?.let {
FileDownloadHelper.instance().downloadFile(
requireNotNull(user) { "User not found" },
user.orElseThrow { RuntimeException() },
file,
conflictUploadId = conflictUploadId
)
@@ -290,7 +298,7 @@ class ConflictsResolveActivity : FileActivity(), OnConflictDecisionMadeListener
@SuppressLint("CommitTransaction")
private fun prepareDialog(): Pair<FragmentTransaction, User> {
val userOptional = user
if (userOptional == null) {
if (!userOptional.isPresent) {
Log_OC.e(TAG, "User not present")
showErrorAndFinish()
}
@@ -302,7 +310,7 @@ class ConflictsResolveActivity : FileActivity(), OnConflictDecisionMadeListener
fragmentTransaction.remove(prev)
}
return fragmentTransaction to user
return fragmentTransaction to user.get()
}
private fun startDialog(remotePath: String) {
@@ -60,6 +60,7 @@ import com.nextcloud.common.NextcloudClient;
import com.nextcloud.ui.ChooseAccountDialogFragment;
import com.nextcloud.ui.composeActivity.ComposeActivity;
import com.nextcloud.ui.composeActivity.ComposeDestination;
import com.nextcloud.utils.LinkHelper;
import com.nextcloud.utils.extensions.ViewExtensionsKt;
import com.nextcloud.utils.mdm.MDMConfig;
import com.owncloud.android.MainApp;
@@ -120,6 +121,7 @@ import javax.inject.Inject;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.view.GravityCompat;
@@ -405,7 +407,7 @@ public abstract class DrawerActivity extends ToolbarActivity
}
// hide ecosystem apps according to user preference or in branded client
LinearLayout banner = mNavigationViewHeader.findViewById(R.id.drawer_ecosystem_apps);
ConstraintLayout banner = mNavigationViewHeader.findViewById(R.id.drawer_ecosystem_apps);
boolean shouldHideTopBanner = isClientBranded || !preferences.isShowEcosystemApps();
if (shouldHideTopBanner) {
@@ -415,19 +417,19 @@ public abstract class DrawerActivity extends ToolbarActivity
}
}
private void hideTopBanner(LinearLayout banner) {
private void hideTopBanner(ConstraintLayout banner) {
banner.setVisibility(View.GONE);
}
private void showTopBanner(LinearLayout banner, int primaryColor) {
private void showTopBanner(ConstraintLayout banner, int primaryColor) {
LinearLayout notesView = banner.findViewById(R.id.drawer_ecosystem_notes);
LinearLayout talkView = banner.findViewById(R.id.drawer_ecosystem_talk);
LinearLayout moreView = banner.findViewById(R.id.drawer_ecosystem_more);
LinearLayout assistantView = banner.findViewById(R.id.drawer_ecosystem_assistant);
notesView.setOnClickListener(v -> openAppOrStore("it.niedermann.owncloud.notes"));
talkView.setOnClickListener(v -> openAppOrStore("com.nextcloud.talk2"));
moreView.setOnClickListener(v -> openAppStore("Nextcloud", true));
notesView.setOnClickListener(v -> LinkHelper.INSTANCE.openAppOrStore(LinkHelper.APP_NEXTCLOUD_NOTES, getUser(), this));
talkView.setOnClickListener(v -> LinkHelper.INSTANCE.openAppOrStore(LinkHelper.APP_NEXTCLOUD_TALK, getUser(), this));
moreView.setOnClickListener(v -> LinkHelper.INSTANCE.openAppStore("Nextcloud", true, this));
assistantView.setOnClickListener(v -> {
DrawerActivity.menuItemId = Menu.NONE;
startComposeActivity(ComposeDestination.AssistantScreen, R.string.assistant_screen_top_bar_title);
@@ -459,45 +461,6 @@ public abstract class DrawerActivity extends ToolbarActivity
banner.setVisibility(View.VISIBLE);
}
/**
* Open specified app and, if not installed redirect to corresponding download.
*
* @param packageName of app to be opened
*/
private void openAppOrStore(String packageName) {
Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
if (intent != null) {
// app installed - open directly
intent.putExtra(FileDisplayActivity.KEY_ACCOUNT, getUser().hashCode());
startActivity(intent);
} else {
// app not found - open market (Google Play Store, F-Droid, etc.)
openAppStore(packageName, false);
}
}
/**
* Open app store page of specified app or search for specified string. Will attempt to open browser when no app
* store is available.
*
* @param string packageName or url-encoded search string
* @param search false -> show app corresponding to packageName; true -> open search for string
*/
private void openAppStore(String string, boolean search) {
String suffix = (search ? "search?q=" : "details?id=") + string;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://" + suffix));
try {
startActivity(intent);
} catch (android.content.ActivityNotFoundException activityNotFoundException1) {
// all is lost: open google play store web page for app
if (!search) {
suffix = "apps/" + suffix;
}
intent.setData(Uri.parse("https://play.google.com/store/" + suffix));
startActivity(intent);
}
}
private void setDrawerHeaderLogo(Drawable drawable, String serverName) {
ImageView imageHeader = mNavigationViewHeader.findViewById(R.id.drawer_header_logo);
imageHeader.setImageDrawable(drawable);
@@ -604,9 +567,9 @@ public abstract class DrawerActivity extends ToolbarActivity
menuItemId = Menu.NONE;
MenuItem isNewMenuItemChecked = menuItem.setChecked(false);
Log_OC.d(TAG,"onNavigationItemClicked nav_logout setChecked " + isNewMenuItemChecked);
final User optionalUser = getUser();
if (optionalUser != null) {
UserInfoActivity.openAccountRemovalDialog(optionalUser, getSupportFragmentManager());
final Optional<User> optionalUser = getUser();
if (optionalUser.isPresent()) {
UserInfoActivity.openAccountRemovalDialog(optionalUser.get(), getSupportFragmentManager());
}
} else if (itemId == R.id.nav_shared) {
startSharedSearch(menuItem);
@@ -899,7 +862,7 @@ public abstract class DrawerActivity extends ToolbarActivity
});
SimpleTarget target = new SimpleTarget<Drawable>() {
SimpleTarget<Drawable> target = new SimpleTarget<>() {
@Override
public void onResourceReady(Drawable resource, GlideAnimation glideAnimation) {
Drawable test = resource.getCurrent();
@@ -1037,7 +1000,7 @@ public abstract class DrawerActivity extends ToolbarActivity
MENU_ITEM_EXTERNAL_LINK + link.getId(), MENU_ORDER_EXTERNAL_LINKS, link.getName())
.setCheckable(true).getItemId();
MenuSimpleTarget target = new MenuSimpleTarget<Drawable>(id) {
MenuSimpleTarget<Drawable> target = new MenuSimpleTarget<>(id) {
@Override
public void onResourceReady(Drawable resource, GlideAnimation glideAnimation) {
setExternalLinkIcon(getIdMenuItem(), resource, greyColor);
@@ -1357,7 +1320,7 @@ public abstract class DrawerActivity extends ToolbarActivity
findViewById(R.id.fab_main).callOnClick();
break;
case ACTION_APP_UPDATE:
openAppStore(getPackageName(), false);
LinkHelper.INSTANCE.openAppStore(getPackageName(), false, this);
break;
case OPEN_NOTIFICATIONS:
startActivity(NotificationsActivity.class);
@@ -77,7 +77,10 @@ public abstract class EditorWebView extends ExternalSiteWebView {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
this.getWebView().loadUrl(url);
if (!url.equals(this.getWebView().getUrl())) {
this.getWebView().loadUrl(url);
}
new Handler().postDelayed(() -> {
if (this.getWebView().getVisibility() != View.VISIBLE) {
@@ -107,14 +110,14 @@ public abstract class EditorWebView extends ExternalSiteWebView {
return;
}
User user = getUser();
if (user == null) {
Optional<User> user = getUser();
if (!user.isPresent()) {
return;
}
OCFile file = getFile();
if (file != null) {
TextEditorLoadUrlTask task = new TextEditorLoadUrlTask(this, user, file, editorUtils);
TextEditorLoadUrlTask task = new TextEditorLoadUrlTask(this, user.get(), file, editorUtils);
task.execute();
}
}
@@ -168,12 +171,12 @@ public abstract class EditorWebView extends ExternalSiteWebView {
fileName = getFile().getFileName();
}
User user = getUser();
if (user == null) {
Optional<User> user = getUser();
if (!user.isPresent()) {
finish();
return;
}
initLoadingScreen(user);
initLoadingScreen(user.get());
}
@Override
@@ -237,13 +240,9 @@ public abstract class EditorWebView extends ExternalSiteWebView {
}
private void openShareDialog() {
User user = getUser();
if (user == null) {
throw new RuntimeException("User not found");
}
Intent intent = new Intent(this, ShareActivity.class);
intent.putExtra(FileActivity.EXTRA_FILE, getFile());
intent.putExtra(FileActivity.EXTRA_USER, user);
intent.putExtra(FileActivity.EXTRA_USER, getUser().orElseThrow(RuntimeException::new));
startActivity(intent);
}
@@ -503,19 +503,11 @@ public abstract class FileActivity extends DrawerActivity
OCFile syncedFile = operation.getLocalFile();
if (!result.isSuccess()) {
if (result.getCode() == ResultCode.SYNC_CONFLICT) {
User user = getUser();
if (user == null) {
throw new RuntimeException("User not found");
}
Intent intent = ConflictsResolveActivity.createIntent(
syncedFile,
user,
-1,
null,
this
);
Intent intent = ConflictsResolveActivity.createIntent(syncedFile,
getUser().orElseThrow(RuntimeException::new),
-1,
null,
this);
startActivity(intent);
}
@@ -513,9 +513,9 @@ public class FileDisplayActivity extends FileActivity
}
private void checkOutdatedServer() {
User user = getUser();
Optional<User> user = getUser();
// show outdated warning
if (user != null && CapabilityUtils.checkOutdatedWarning(getResources(), user.getServer().getVersion(), getCapabilities().getExtendedSupport().isTrue())) {
if (user.isPresent() && CapabilityUtils.checkOutdatedWarning(getResources(), user.get().getServer().getVersion(), getCapabilities().getExtendedSupport().isTrue())) {
DisplayUtils.showServerOutdatedSnackbar(this, Snackbar.LENGTH_LONG);
}
}
@@ -812,9 +812,8 @@ public class FileDisplayActivity extends FileActivity
protected void refreshDetailsFragmentIfVisible(String downloadEvent, String downloadedRemotePath, boolean success) {
Fragment leftFragment = getLeftFragment();
if (leftFragment instanceof FileDetailFragment) {
if (leftFragment instanceof FileDetailFragment detailsFragment) {
boolean waitedPreview = mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath);
FileDetailFragment detailsFragment = (FileDetailFragment) leftFragment;
OCFile fileInFragment = detailsFragment.getFile();
if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
// the user browsed to other file ; forget the automatic preview
@@ -1065,23 +1064,15 @@ public class FileDisplayActivity extends FileActivity
return;
}
User user = getUser();
if (user == null) {
throw new RuntimeException("User not found");
}
FileUploadHelper.Companion.instance().uploadNewFiles(
user,
filePaths,
decryptedRemotePaths,
behaviour,
true,
UploadFileOperation.CREATED_BY_USER,
false,
false,
NameCollisionPolicy.ASK_USER
);
FileUploadHelper.Companion.instance().uploadNewFiles(getUser().orElseThrow(RuntimeException::new),
filePaths,
decryptedRemotePaths,
behaviour,
true,
UploadFileOperation.CREATED_BY_USER,
false,
false,
NameCollisionPolicy.ASK_USER);
} else {
fileDataStorageManager.addCreateFileOfflineOperation(filePaths, decryptedRemotePaths);
}
@@ -1111,22 +1102,10 @@ public class FileDisplayActivity extends FileActivity
OCFile currentDir = getCurrentDir();
String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;
User user = getUser();
if (user == null) {
throw new RuntimeException("User not found");
}
UriUploader uploader = new UriUploader(
this,
streamsToUpload,
remotePath,
user,
behaviour,
false, // Not show waiting dialog while file is being copied from private storage
null // Not needed copy temp task listener
UriUploader uploader = new UriUploader(this, streamsToUpload, remotePath, getUser().orElseThrow(RuntimeException::new), behaviour, false, // Not show waiting dialog while file is being copied from private storage
null // Not needed copy temp task listener
);
uploader.uploadUris();
}
@@ -1312,7 +1291,7 @@ public class FileDisplayActivity extends FileActivity
}
//show in-app review dialog to user
inAppReviewHelper.showInAppReview(this);
checkNotifications();
Log_OC.v(TAG, "onResume() end");
@@ -1521,7 +1500,7 @@ public class FileDisplayActivity extends FileActivity
private void setBackgroundText() {
final OCFileListFragment ocFileListFragment = getListOfFilesFragment();
if (ocFileListFragment != null) {
if (mSyncInProgress || getFile().getFileLength() > 0 && getStorageManager().getFolderContent(getFile(), false).isEmpty()) {
if (mSyncInProgress || getFile().getFileLength() > 0 && getStorageManager().getFolderIsEmpty(getFile())) {
ocFileListFragment.setEmptyListLoadingMessage();
} else {
if (MainApp.isOnlyOnDevice()) {
@@ -1710,10 +1689,7 @@ public class FileDisplayActivity extends FileActivity
* @param activeTab the active tab in the details view
*/
public void showDetails(OCFile file, int activeTab) {
User currentUser = getUser();
if (currentUser == null) {
throw new RuntimeException("User not found");
}
User currentUser = getUser().orElseThrow(RuntimeException::new);
resetScrolling(true);
@@ -1845,6 +1821,15 @@ public class FileDisplayActivity extends FileActivity
} else if (operation instanceof RestoreFileVersionRemoteOperation) {
onRestoreFileVersionOperationFinish(result);
}
if (operation instanceof RemoveFileOperation || operation instanceof RenameFileOperation) {
OCFileListFragment fileListFragment =
(ActivityExtensionsKt.lastFragment(this) instanceof OCFileListFragment fragment) ? fragment : getListOfFilesFragment();
if (fileListFragment != null) {
fileListFragment.fetchRecommendedFiles();
}
}
}
private void refreshShowDetails() {
@@ -1920,8 +1905,7 @@ public class FileDisplayActivity extends FileActivity
startSyncFolderOperation(parent, true, true);
Fragment leftFragment = getLeftFragment();
if (leftFragment instanceof FileDetailFragment) {
FileDetailFragment fileDetailFragment = (FileDetailFragment) leftFragment;
if (leftFragment instanceof FileDetailFragment fileDetailFragment) {
fileDetailFragment.getFileDetailActivitiesFragment().reload();
}
@@ -1983,13 +1967,12 @@ public class FileDisplayActivity extends FileActivity
* @param result Result of the renaming.
*/
private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
User optionalUser = getUser();
Optional<User> optionalUser = getUser();
OCFile renamedFile = operation.getFile();
if (result.isSuccess() && optionalUser != null) {
final User currentUser = optionalUser;
if (result.isSuccess() && optionalUser.isPresent()) {
final User currentUser = optionalUser.get();
Fragment leftFragment = getLeftFragment();
if (leftFragment instanceof FileFragment) {
final FileFragment fileFragment = (FileFragment) leftFragment;
if (leftFragment instanceof FileFragment fileFragment) {
if (fileFragment instanceof FileDetailFragment && renamedFile.equals(fileFragment.getFile())) {
((FileDetailFragment) fileFragment).updateFileDetails(renamedFile, currentUser);
showDetails(renamedFile);
@@ -2070,9 +2053,9 @@ public class FileDisplayActivity extends FileActivity
public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
updateListOfFilesFragment(false);
Fragment leftFragment = getLeftFragment();
User optionalUser = getUser();
if (leftFragment instanceof FileDetailFragment && file.equals(((FileDetailFragment) leftFragment).getFile()) && optionalUser != null) {
final User currentUser = optionalUser;
Optional<User> optionalUser = getUser();
if (leftFragment instanceof FileDetailFragment && file.equals(((FileDetailFragment) leftFragment).getFile()) && optionalUser.isPresent()) {
final User currentUser = optionalUser.get();
if (downloading || uploading) {
((FileDetailFragment) leftFragment).updateFileDetails(file, currentUser);
} else {
@@ -2088,11 +2071,7 @@ public class FileDisplayActivity extends FileActivity
private void requestForDownload() {
User user = getUser();
if (user == null) {
throw new RuntimeException("User not found");
}
User user = getUser().orElseThrow(RuntimeException::new);
FileDownloadHelper.Companion.instance().downloadFileIfNotStartedBefore(user, mWaitingToPreview);
}
@@ -2134,11 +2113,11 @@ public class FileDisplayActivity extends FileActivity
// the execution is slightly delayed to allow the activity get the window focus if it's being started
// or if the method is called from a dialog that is being dismissed
if (TextUtils.isEmpty(searchQuery) && getUser() != null) {
if (TextUtils.isEmpty(searchQuery) && getUser().isPresent()) {
getHandler().postDelayed(() -> {
User user = getUser();
Optional<User> user = getUser();
if (!ignoreFocus && !hasWindowFocus() || user == null) {
if (!ignoreFocus && !hasWindowFocus() || !user.isPresent()) {
// do not refresh if the user rotates the device while another window has focus
// or if the current user is no longer valid
return;
@@ -2148,7 +2127,7 @@ public class FileDisplayActivity extends FileActivity
mSyncInProgress = true;
// perform folder synchronization
RemoteOperation refreshFolderOperation = new RefreshFolderOperation(folder, currentSyncTime, false, ignoreETag, getStorageManager(), user, getApplicationContext());
RemoteOperation refreshFolderOperation = new RefreshFolderOperation(folder, currentSyncTime, false, ignoreETag, getStorageManager(), user.get(), getApplicationContext());
refreshFolderOperation.execute(getAccount(), MainApp.getAppContext(), FileDisplayActivity.this, null, null);
OCFileListFragment fragment = getListOfFilesFragment();
@@ -2163,11 +2142,7 @@ public class FileDisplayActivity extends FileActivity
}
private void requestForDownload(OCFile file, String downloadBehaviour, String packageName, String activityName) {
final User currentUser = getUser();
if (currentUser == null) {
throw new RuntimeException("User not found");
}
final User currentUser = getUser().orElseThrow(RuntimeException::new);
if (!FileDownloadHelper.Companion.instance().isDownloading(currentUser, file)) {
FileDownloadHelper.Companion.instance().downloadFile(currentUser, file, downloadBehaviour, DownloadType.DOWNLOAD, activityName, packageName, null);
}
@@ -2203,15 +2178,10 @@ public class FileDisplayActivity extends FileActivity
}
public void startImagePreview(OCFile file, boolean showPreview) {
User user = getUser();
if (user == null) {
throw new RuntimeException("User not found");
}
Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
showDetailsIntent.putExtra(EXTRA_FILE, file);
showDetailsIntent.putExtra(EXTRA_LIVE_PHOTO_FILE, file.livePhotoVideo);
showDetailsIntent.putExtra(EXTRA_USER, user);
showDetailsIntent.putExtra(EXTRA_USER, getUser().orElseThrow(RuntimeException::new));
if (showPreview) {
startActivity(showDetailsIntent);
} else {
@@ -2221,14 +2191,10 @@ public class FileDisplayActivity extends FileActivity
}
public void startImagePreview(OCFile file, VirtualFolderType type, boolean showPreview) {
User user = getUser();
if (user == null) {
throw new RuntimeException("User not found");
}
Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
showDetailsIntent.putExtra(PreviewImageActivity.EXTRA_FILE, file);
showDetailsIntent.putExtra(EXTRA_LIVE_PHOTO_FILE, file.livePhotoVideo);
showDetailsIntent.putExtra(EXTRA_USER, user);
showDetailsIntent.putExtra(EXTRA_USER, getUser().orElseThrow(RuntimeException::new));
showDetailsIntent.putExtra(PreviewImageActivity.EXTRA_VIRTUAL_TYPE, type);
if (showPreview) {
@@ -2250,16 +2216,17 @@ public class FileDisplayActivity extends FileActivity
* @param autoplay When 'true', the playback will start without user interactions.
*/
public void startMediaPreview(OCFile file, long startPlaybackPosition, boolean autoplay, boolean showPreview, boolean streamMedia, boolean showInActivity) {
User user = getUser();
if (user == null) {
Optional<User> user = getUser();
if (!user.isPresent()) {
return; // not reachable under normal conditions
}
User actualUser = user.get();
if (showPreview && file.isDown() && !file.isDownloading() || streamMedia) {
if (showInActivity) {
startMediaActivity(file, startPlaybackPosition, autoplay, user);
startMediaActivity(file, startPlaybackPosition, autoplay, actualUser);
} else {
configureToolbarForPreview(file);
Fragment mediaFragment = PreviewMediaFragment.newInstance(file, user, startPlaybackPosition, autoplay, false);
Fragment mediaFragment = PreviewMediaFragment.newInstance(file, user.get(), startPlaybackPosition, autoplay, false);
setLeftFragment(mediaFragment, false);
}
} else {
@@ -2275,7 +2242,12 @@ public class FileDisplayActivity extends FileActivity
private void startMediaActivity(OCFile file, long startPlaybackPosition, boolean autoplay, User user) {
Intent previewMediaIntent = new Intent(this, PreviewMediaActivity.class);
previewMediaIntent.putExtra(PreviewMediaActivity.EXTRA_FILE, file);
previewMediaIntent.putExtra(PreviewMediaActivity.EXTRA_USER, user);
// Safely handle the absence of a user
if (user != null) {
previewMediaIntent.putExtra(PreviewMediaActivity.EXTRA_USER, user);
}
previewMediaIntent.putExtra(PreviewMediaActivity.EXTRA_START_POSITION, startPlaybackPosition);
previewMediaIntent.putExtra(PreviewMediaActivity.EXTRA_AUTOPLAY, autoplay);
startActivity(previewMediaIntent);
@@ -2292,12 +2264,12 @@ public class FileDisplayActivity extends FileActivity
* @param file Text {@link OCFile} to preview.
*/
public void startTextPreview(OCFile file, boolean showPreview) {
User optUser = getUser();
if (optUser == null) {
Optional<User> optUser = getUser();
if (!optUser.isPresent()) {
// remnants of old unsafe system; do not crash, silently stop
return;
}
User user = optUser;
User user = optUser.get();
if (showPreview) {
PreviewTextFileFragment fragment = PreviewTextFileFragment.create(user, file, searchOpen, searchQuery);
setLeftFragment(fragment, false);
@@ -2325,10 +2297,7 @@ public class FileDisplayActivity extends FileActivity
}
public void startContactListFragment(OCFile file) {
final User user = getUser();
if (user == null) {
throw new RuntimeException("User not found");
}
final User user = getUser().orElseThrow(RuntimeException::new);
ContactsPreferenceActivity.startActivityWithContactsFile(this, user, file);
}
@@ -2354,10 +2323,7 @@ public class FileDisplayActivity extends FileActivity
* @param parentFolder {@link OCFile} containing above file
*/
public void startDownloadForPreview(OCFile file, OCFile parentFolder) {
final User currentUser = getUser();
if (currentUser == null) {
throw new RuntimeException("User not found");
}
final User currentUser = getUser().orElseThrow(RuntimeException::new);
Fragment detailFragment = FileDetailFragment.newInstance(file, parentFolder, currentUser);
setLeftFragment(detailFragment, false);
configureToolbarForPreview(file);
@@ -2497,17 +2463,18 @@ public class FileDisplayActivity extends FileActivity
@Override
public void onStart() {
super.onStart();
final User user = getUser();
final Optional<User> optionalUser = getUser();
final FileDataStorageManager storageManager = getStorageManager();
if (user != null && storageManager != null) {
// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
if (optionalUser.isPresent() && storageManager != null) {
/// Check whether the 'main' OCFile handled by the Activity is contained in the
// current Account
OCFile file = getFile();
// get parent from path
String parentPath = "";
if (file != null) {
if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
// upload in progress - right now, files are not inserted in the local cache
// until the upload is successful. Get parent from path
// upload in progress - right now, files are not inserted in the local
// cache until the upload is successful get parent from path
parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
if (storageManager.getFileByPath(parentPath) == null) {
file = null; // not able to know the directory where the file is uploading
@@ -2523,6 +2490,7 @@ public class FileDisplayActivity extends FileActivity
}
setFile(file);
User user = optionalUser.get();
setupDrawer();
mSwitchAccountButton.setTag(user.getAccountName());
@@ -2537,8 +2505,8 @@ public class FileDisplayActivity extends FileActivity
} else {
updateActionBarTitleAndHomeButton(file.isFolder() ? null : file);
}
lastDisplayedUser = user;
}
lastDisplayedUser = optionalUser.orElse(null);
EventBus.getDefault().post(new TokenPushEvent());
checkForNewDevVersionNecessary(getApplicationContext());
@@ -2582,14 +2550,14 @@ public class FileDisplayActivity extends FileActivity
if (userName == null && fileId == null && intent.getData() != null) {
openDeepLink(intent.getData());
} else {
User optionalUser = userName == null ? getUser() : getUserAccountManager().getUser(userName);
if (optionalUser != null) {
Optional<User> optionalUser = userName == null ? getUser() : getUserAccountManager().getUser(userName);
if (optionalUser.isPresent()) {
if (!TextUtils.isEmpty(fileId)) {
openFile(optionalUser, fileId);
openFile(optionalUser.get(), fileId);
} else if (!TextUtils.isEmpty(filePath)) {
openFileByPath(optionalUser, filePath);
openFileByPath(optionalUser.get(), filePath);
} else {
accountClicked(optionalUser.hashCode());
accountClicked(optionalUser.get().hashCode());
}
} else {
DisplayUtils.showSnackMessage(this, getString(R.string.associated_account_not_found));
@@ -265,7 +265,7 @@ open class FolderPickerActivity :
false,
ignoreETag,
storageManager,
requireNotNull(user) { "User not found" },
user.orElseThrow { RuntimeException("User not set") },
applicationContext
).also {
it.execute(account, this, null, null)
@@ -50,7 +50,7 @@ class InternalTwoWaySyncActivity :
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
internalTwoWaySyncAdapter = InternalTwoWaySyncAdapter(fileDataStorageManager, user, this, this)
internalTwoWaySyncAdapter = InternalTwoWaySyncAdapter(fileDataStorageManager, user.get(), this, this)
binding = InternalTwoWaySyncLayoutBinding.inflate(layoutInflater)
setContentView(binding.root)
@@ -114,7 +114,7 @@ class InternalTwoWaySyncActivity :
try {
backgroundJobManager.cancelTwoWaySyncJob()
val currentUser = user
val currentUser = user.get()
val folders = fileDataStorageManager.getInternalTwoWaySyncFolders(currentUser)
folders.forEach { folder ->
@@ -214,7 +214,7 @@ class InternalTwoWaySyncActivity :
private fun checkDisableForAllFoldersMenuButtonVisibility() {
lifecycleScope.launch {
val folderSize = withContext(Dispatchers.IO) {
fileDataStorageManager.getInternalTwoWaySyncFolders(user).size
fileDataStorageManager.getInternalTwoWaySyncFolders(user.get()).size
}
checkDisableForAllFoldersMenuButtonVisibility(preferences.isTwoWaySyncEnabled, folderSize)
@@ -98,8 +98,8 @@ class ManageAccountsActivity :
val users = accountManager.allUsers
originalUsers = toAccountNames(users)
user?.let {
originalCurrentUser = it.accountName
user.ifPresent {
originalCurrentUser = user.get().accountName
}
}
@@ -144,7 +144,7 @@ class ManageAccountsActivity :
}
val account = bundle.getParcelableArgument(UserInfoActivity.KEY_ACCOUNT, Account::class.java) ?: return
val user = checkNotNull(accountManager.getUser(account.name)) { "User not found" }
val user = accountManager.getUser(account.name).orElseThrow { RuntimeException() }
accountName = account.name
performAccountRemoval(user)
}
@@ -301,7 +301,7 @@ class ManageAccountsActivity :
accountName?.let {
val user = accountManager.getUser(it)
if (user == null) {
if (!user.isPresent) {
fileUploadHelper.cancel(it)
FileDownloadHelper.instance().cancelAllDownloadsForAccount(workerAccountName, workerCurrentDownload)
}
@@ -271,14 +271,10 @@ public class ReceiveExternalFilesActivity extends FileActivity
super.onSaveInstanceState(outState);
outState.putString(KEY_PARENTS, generatePath(mParents));
outState.putParcelable(KEY_FILE, mFile);
User user = getUser();
if (user != null) {
outState.putParcelable(FileActivity.EXTRA_USER, user);
} else {
throw new RuntimeException("User not found");
if (getUser().isPresent()) {
outState.putParcelable(FileActivity.EXTRA_USER, getUser().orElseThrow(RuntimeException::new));
}
Log_OC.d(TAG, "onSaveInstanceState() end");
}
@@ -306,18 +302,13 @@ public class ReceiveExternalFilesActivity extends FileActivity
return;
}
User user = getUser();
if (user == null) {
throw new IllegalAccessError("User not found");
}
if (file.isEncrypted() &&
!FileOperationsHelper.isEndToEndEncryptionSetup(this, user)) {
!FileOperationsHelper.isEndToEndEncryptionSetup(this, getUser().orElseThrow(IllegalAccessError::new))) {
DisplayUtils.showSnackMessage(this, R.string.e2e_not_yet_setup);
return;
}
startSyncFolderOperation(file);
String filename = fileDataStorageManager.getFileNameBasedOnEncryptionStatus(file);
@@ -446,7 +437,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
mFileCategory = CATEGORY_URL;
} else if (isIntentFromGoogleMap(subjectText, extraText)) {
String str = getString(R.string.upload_file_dialog_filetype_googlemap_shortcut);
String texts[] = extraText.split("\n");
String[] texts = extraText.split("\n");
mText.add(internetShortcutUrlText(texts[2]));
mFilenameBase.add(texts[0]);
mFilenameSuffix.add(URL_FILE_SUFFIX);
@@ -576,7 +567,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
}
private boolean isIntentFromGoogleMap(String subjectText, String extraText) {
String texts[] = extraText.split("\n");
String[] texts = extraText.split("\n");
if (texts.length != EXTRA_TEXT_LENGTH) {
return false;
}
@@ -806,7 +797,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
private void setupReceiveExternalFilesAdapter(List<OCFile> files) {
receiveExternalFilesAdapter = new ReceiveExternalFilesAdapter(files,
this,
getUser(),
getUser().get(),
getStorageManager(),
viewThemeUtils,
syncedFolderProvider,
@@ -854,21 +845,14 @@ public class ReceiveExternalFilesActivity extends FileActivity
mSyncInProgress = true;
// perform folder synchronization
User user = getUser();
if (user == null) {
throw new RuntimeException("User not found");
}
RemoteOperation syncFolderOp = new RefreshFolderOperation(
folder,
currentSyncTime,
false,
false,
getStorageManager(),
user,
getApplicationContext()
RemoteOperation syncFolderOp = new RefreshFolderOperation(folder,
currentSyncTime,
false,
false,
getStorageManager(),
getUser().orElseThrow(RuntimeException::new),
getApplicationContext()
);
syncFolderOp.execute(getAccount(), this, null, null);
}
@@ -924,12 +908,8 @@ public class ReceiveExternalFilesActivity extends FileActivity
}
public void uploadFile(String tmpName, String filename) {
User user = getUser();
if (user == null) {
throw new RuntimeException("User not found");
}
FileUploadHelper.Companion.instance().uploadNewFiles(
user,
getUser().orElseThrow(RuntimeException::new),
new String[]{ tmpName },
new String[]{ mFile.getRemotePath() + filename},
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
@@ -951,16 +931,12 @@ public class ReceiveExternalFilesActivity extends FileActivity
DisplayUtils.showSnackMessage(this, R.string.max_file_count_warning_message);
return;
}
User user = getUser();
if (user == null) {
throw new RuntimeException("User not found");
}
UriUploader uploader = new UriUploader(
this,
mStreamsToUpload,
mUploadPath,
user,
getUser().orElseThrow(RuntimeException::new),
FileUploadWorker.LOCAL_BEHAVIOUR_DELETE,
true, // Show waiting dialog while file is being copied from private storage
this // Copy temp task listener
@@ -17,6 +17,7 @@ import android.webkit.JavascriptInterface
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.net.toUri
import com.nextcloud.client.account.CurrentAccountProvider
import com.nextcloud.client.network.ClientFactory
import com.nextcloud.utils.extensions.getParcelableArgument
@@ -135,7 +136,7 @@ class RichDocumentsEditorWebView : EditorWebView() {
public override fun loadUrl(url: String?) {
if (TextUtils.isEmpty(url)) {
RichDocumentsLoadUrlTask(this, user, file).execute()
RichDocumentsLoadUrlTask(this, user.get(), file).execute()
} else {
super.loadUrl(url)
}
@@ -165,7 +166,7 @@ class RichDocumentsEditorWebView : EditorWebView() {
try {
json ?: return
val downloadJson = JSONObject(json)
val url = Uri.parse(downloadJson.getString(URL))
val url = downloadJson.getString(URL).toUri()
when (downloadJson.getString(TYPE)) {
PRINT -> printFile(url)
SLIDESHOW -> showSlideShow(url)
@@ -203,7 +204,7 @@ class RichDocumentsEditorWebView : EditorWebView() {
hyperlink ?: return
val url = JSONObject(hyperlink).getString(HYPERLINK)
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(url)
intent.data = url.toUri()
startActivity(intent)
} catch (e: JSONException) {
Log_OC.e(this, "Failed to parse download json message: $e")
@@ -38,9 +38,11 @@ import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.URLUtil;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.nextcloud.android.common.ui.util.extensions.WindowExtensionsKt;
import com.nextcloud.client.account.User;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.di.Injectable;
@@ -52,7 +54,6 @@ import com.nextcloud.client.preferences.AppPreferences;
import com.nextcloud.client.preferences.AppPreferencesImpl;
import com.nextcloud.client.preferences.DarkMode;
import com.nextcloud.utils.extensions.ViewExtensionsKt;
import com.nextcloud.utils.extensions.WindowExtensionsKt;
import com.nextcloud.utils.mdm.MDMConfig;
import com.owncloud.android.MainApp;
import com.owncloud.android.R;
@@ -146,10 +147,15 @@ public class SettingsActivity extends PreferenceActivity
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
boolean isApiLevel35OrHigher = (Build.VERSION.SDK_INT >= 35);
if (isApiLevel35OrHigher) {
WindowExtensionsKt.addSystemBarPaddings(getWindow());
WindowExtensionsKt.setNoLimitLayout(getWindow());
final var window = getWindow();
if (window != null) {
WindowExtensionsKt.addSystemBarPaddings(getWindow());
final var flag = WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
window.setFlags(flag, flag);
}
}
super.onCreate(savedInstanceState);
@@ -62,15 +62,15 @@ public class ShareActivity extends FileActivity {
setContentView(binding.getRoot());
OCFile file = getFile();
User optionalUser = getUser();
if (optionalUser == null) {
Optional<User> optionalUser = getUser();
if (!optionalUser.isPresent()) {
finish();
return;
}
// Icon
if (file.isFolder()) {
boolean isAutoUploadFolder = SyncedFolderProvider.isAutoUploadFolder(syncedFolderProvider, file, optionalUser);
boolean isAutoUploadFolder = SyncedFolderProvider.isAutoUploadFolder(syncedFolderProvider, file, optionalUser.get());
Integer overlayIconId = file.getFileOverlayIconId(isAutoUploadFolder);
LayerDrawable drawable = MimeTypeUtil.getFolderIcon(preferences.isDarkModeEnabled(), overlayIconId, this, viewThemeUtils);
@@ -100,7 +100,7 @@ public class ShareActivity extends FileActivity {
Activity activity = this;
new Thread(() -> {
RemoteOperationResult result = new ReadFileRemoteOperation(getFile().getRemotePath())
.execute(optionalUser,
.execute(optionalUser.get(),
activity);
if (result.isSuccess()) {
@@ -115,7 +115,7 @@ public class ShareActivity extends FileActivity {
if (savedInstanceState == null) {
// Add Share fragment on first creation
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment fragment = FileDetailSharingFragment.newInstance(getFile(), optionalUser);
Fragment fragment = FileDetailSharingFragment.newInstance(getFile(), optionalUser.get());
ft.replace(R.id.share_fragment_container, fragment, TAG_SHARE_FRAGMENT);
ft.commit();
}
@@ -12,8 +12,8 @@ import android.annotation.SuppressLint
import android.app.NotificationManager
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Looper
import android.os.PowerManager
import android.provider.Settings
import android.text.TextUtils
@@ -22,8 +22,10 @@ import android.view.MenuItem
import android.view.View
import androidx.annotation.VisibleForTesting
import androidx.appcompat.app.AlertDialog
import androidx.core.net.toUri
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.nextcloud.client.core.Clock
@@ -56,10 +58,9 @@ import com.owncloud.android.ui.dialog.SyncedFolderPreferencesDialogFragment.OnSy
import com.owncloud.android.ui.dialog.parcel.SyncedFolderParcelable
import com.owncloud.android.utils.PermissionUtil
import com.owncloud.android.utils.SyncedFolderUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.util.Locale
import javax.inject.Inject
@@ -149,7 +150,6 @@ class SyncedFoldersActivity :
private var dialogFragment: SyncedFolderPreferencesDialogFragment? = null
private var path: String? = null
private var type = 0
private var loadJob: Job? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -158,8 +158,8 @@ class SyncedFoldersActivity :
if (intent != null && intent.extras != null) {
val accountName = intent.extras!!.getString(NotificationWork.KEY_NOTIFICATION_ACCOUNT)
val optionalUser = user
if (optionalUser != null && accountName != null) {
val user = optionalUser
if (optionalUser.isPresent && accountName != null) {
val user = optionalUser.get()
if (!accountName.equals(user.accountName, ignoreCase = true)) {
accountManager.setCurrentOwnCloudAccount(accountName)
setUser(userAccountManager.user)
@@ -275,8 +275,7 @@ class SyncedFoldersActivity :
return
}
showLoadingContent()
loadJob = CoroutineScope(Dispatchers.IO).launch {
loadJob?.cancel()
lifecycleScope.launch(Dispatchers.IO) {
val mediaFolders = MediaProvider.getImageFolders(
contentResolver,
perFolderMediaItemLimit,
@@ -310,10 +309,11 @@ class SyncedFoldersActivity :
mergeFolderData(currentAccountSyncedFoldersList, mediaFolders)
).filterNotNull()
CoroutineScope(Dispatchers.Main).launch {
withContext(Dispatchers.Main) {
adapter.setSyncFolderItems(syncFolderItems)
adapter.notifyDataSetChanged()
showList()
if (!TextUtils.isEmpty(path)) {
val section = adapter.getSectionByLocalPathAndType(path, type)
if (section >= 0) {
@@ -322,16 +322,10 @@ class SyncedFoldersActivity :
}
}
}
loadJob = null
}
}
}
override fun onDestroy() {
super.onDestroy()
loadJob?.cancel()
}
/**
* merges two lists of [SyncedFolder] and [MediaFolder] items into one of SyncedFolderItems.
*
@@ -584,18 +578,22 @@ class SyncedFoldersActivity :
}
override fun onSyncFolderSettingsClick(section: Int, syncedFolderDisplayItem: SyncedFolderDisplayItem?) {
val fragmentTransaction = supportFragmentManager.beginTransaction().apply {
addToBackStack(null)
}
check(Looper.getMainLooper().isCurrentThread) { "This must be called on the main thread!" }
dialogFragment = SyncedFolderPreferencesDialogFragment.newInstance(
syncedFolderDisplayItem,
section
)
dialogFragment?.let {
if (isDialogFragmentReady(it)) {
it.show(fragmentTransaction, SYNCED_FOLDER_PREFERENCES_DIALOG_TAG)
dialogFragment?.let { folderPreferencesDialog ->
if (isDialogFragmentReady(folderPreferencesDialog) &&
lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)
) {
val fragmentTransaction = supportFragmentManager
.beginTransaction()
.addToBackStack(null)
folderPreferencesDialog.show(fragmentTransaction, SYNCED_FOLDER_PREFERENCES_DIALOG_TAG)
} else {
Log_OC.d(TAG, "SyncedFolderPreferencesDialogFragment not ready")
}
@@ -825,7 +823,7 @@ class SyncedFoldersActivity :
@SuppressLint("BatteryLife")
val intent = Intent(
Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
Uri.parse("package:" + BuildConfig.APPLICATION_ID)
("package:" + BuildConfig.APPLICATION_ID).toUri()
)
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
@@ -8,8 +8,8 @@
package com.owncloud.android.ui.activity
import android.annotation.SuppressLint
import android.net.Uri
import android.widget.Toast
import androidx.core.net.toUri
import androidx.webkit.WebSettingsCompat
import androidx.webkit.WebViewFeature
import com.nextcloud.android.common.ui.util.PlatformThemeUtil
@@ -38,12 +38,12 @@ class TextEditorWebView : EditorWebView() {
override fun postOnCreate() {
super.postOnCreate()
if (user == null) {
if (!user.isPresent) {
Toast.makeText(this, getString(R.string.failed_to_start_editor), Toast.LENGTH_LONG).show()
finish()
}
val editor = editorUtils.getEditor(user, file.mimeType)
val editor = editorUtils.getEditor(user.get(), file.mimeType)
if (editor != null && editor.id == "onlyoffice") {
webView.settings.userAgentString = generateOnlyOfficeUserAgent()
@@ -61,14 +61,14 @@ class TextEditorWebView : EditorWebView() {
WebSettingsCompat.setForceDark(webView.settings, WebSettingsCompat.FORCE_DARK_ON)
}
webView.setDownloadListener { url, _, _, _, _ -> downloadFile(Uri.parse(url)) }
webView.setDownloadListener { url, _, _, _, _ -> downloadFile(url.toUri()) }
loadUrl(intent.getStringExtra(EXTRA_URL))
}
override fun loadUrl(url: String?) {
if (url.isNullOrEmpty()) {
TextEditorLoadUrlTask(this, user, file, editorUtils).execute()
TextEditorLoadUrlTask(this, user.get(), file, editorUtils).execute()
}
}
@@ -214,11 +214,6 @@ public class UploadListActivity extends FileActivity {
swipeListRefreshLayout.setRefreshing(false);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
Log_OC.v(TAG, "onResume() start");
Loaded 100 of 226 files, more files were not shown because too many files have changed in this diff. Show more