Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a76f6a6a1f |
No files matched your search
@@ -1,179 +0,0 @@
|
||||
---
|
||||
name: android-activity-to-navigator-fragment
|
||||
description: >
|
||||
Use when converting a standalone Activity (usually a DrawerActivity or FileActivity
|
||||
subclass such as a drawer destination) into a Fragment hosted by NavigatorActivity, when
|
||||
the user mentions "navigator", "NavigatorActivity", "NavigatorScreen", "convert activity
|
||||
to fragment", "move screen into the new navigation", or names a drawer screen that still
|
||||
has its own Activity. Covers registering the NavigatorScreen, building the fragment and
|
||||
its layout, decoupling collaborators from the old Activity type, rewiring every entry
|
||||
point (drawer, PendingIntents, broadcast receivers, deep links), DI and manifest cleanup,
|
||||
and migrating the instrumented screenshot test.
|
||||
license: AGPL-3.0-or-later
|
||||
SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
metadata:
|
||||
author: Nextcloud Android
|
||||
version: "1.0.0"
|
||||
---
|
||||
|
||||
# Activity → NavigatorActivity Fragment Conversion
|
||||
|
||||
Historically every drawer destination was its own `DrawerActivity` subclass, each with its
|
||||
own toolbar, `DrawerLayout` and back handling. `NavigatorActivity` replaces them with **one
|
||||
host Activity** that owns the toolbar and drawer, and swaps **fragments** for the
|
||||
destinations. Converted so far: Community (#16652), Activities (#16753), Notifications
|
||||
(#16800), Trashbin (#16879), Upload list.
|
||||
|
||||
Read `references/ARCHITECTURE.md` once before the first conversion. It explains how
|
||||
`Navigator`, `NavigatorScreen`, `NavigatorActivity` and `DrawerActivity.pushFragment` work
|
||||
together.
|
||||
|
||||
## The Prime Directive: Behaviour Must Not Change
|
||||
|
||||
The screen must look and behave exactly as before from every entry point: drawer item,
|
||||
notification tap, notification action, deep link, rotation, back press, drawer toggle and
|
||||
menu actions. This is a structural refactor. If you find a bug, report it instead of
|
||||
fixing it in the same change.
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 0: Inventory (do not edit yet)
|
||||
|
||||
1. Read the whole Activity, its layout and its menu.
|
||||
2. `git grep -n "<ActivityName>"` across `app/src`, including `AndroidManifest.xml`,
|
||||
`ComponentsModule.java`, KDoc links, `androidTest` and screenshot file names. Every hit is
|
||||
either an **entry point** you must rewire or a **reference** you must update.
|
||||
3. List what the Activity takes from its **base class**. This is the step most likely to go
|
||||
wrong. `NavigatorActivity` is a `DrawerActivity`, **not** a `FileActivity`. Anything from
|
||||
`FileActivity` (`fileOperationsHelper`, `OperationsService` binding,
|
||||
`onRemoteOperationFinish`, `requestCredentialsUpdate`, `showLoadingDialog`,
|
||||
`connectivityService` field, `backgroundJobManager` field, `EXTRA_FILE`/`EXTRA_USER`
|
||||
handling in `onCreate`) does not exist in the host. See `references/HOST-CAPABILITIES.md`.
|
||||
4. List the intent extras the Activity, or its base class, reads. Each one must keep working
|
||||
when it arrives on the `NavigatorActivity` intent.
|
||||
5. Note any `onActivityResult`, `BroadcastReceiver`, `OnBackPressedCallback`,
|
||||
`onOptionsItemSelected`, `ActionMode` or drawer listeners. Each one needs a fragment
|
||||
equivalent (see `references/ACTIVITY-TO-FRAGMENT-MAPPING.md`).
|
||||
|
||||
If a collaborator needs a capability the host does not have, **stop and ask the
|
||||
developer** whether to (a) move the flow into the fragment and extract the shared pieces
|
||||
into a helper used by both places, or (b) change the host. Option (a) is the default. It
|
||||
was chosen for the upload list's credential check (`CredentialsUpdateHelper`).
|
||||
|
||||
### Step 1: Register the screen in `NavigatorScreen`
|
||||
|
||||
Add the screen in all **five** places in `ui/navigation/NavigatorScreen.kt`. The `when`
|
||||
expressions are exhaustive, so the compiler catches a missing branch, except in `fromTag`:
|
||||
|
||||
1. `@Parcelize object X : NavigatorScreen(X_TAG[, hasDrawer = false])`
|
||||
2. `private const val X_TAG = "X"` in the companion
|
||||
3. `fromTag`: `X_TAG -> X` (**not compiler-checked**; missing it breaks restoring after rotation)
|
||||
4. `menuItemId()`: the drawer item id, or `-1` for screens outside the drawer
|
||||
5. `actionBarStyle()`: `ActionBarStyle.Plain to R.string.<existing title>`
|
||||
6. `toFragment()`: `X -> XFragment()`
|
||||
|
||||
Use `hasDrawer = false` for screens with a back arrow instead of a hamburger (Notifications).
|
||||
|
||||
### Step 2: Fragment layout
|
||||
|
||||
Copy the Activity layout to `fragment_<name>.xml` and strip the shell. The host already
|
||||
provides it:
|
||||
|
||||
- remove the root `DrawerLayout`, the `<include layout="@layout/toolbar_standard"/>` and the
|
||||
`<include layout="@layout/drawer"/>`;
|
||||
- remove `layout_below="@id/appbar"`. The host's `FragmentContainerView` already sits below
|
||||
the app bar;
|
||||
- keep every view id the code or tests use, so the generated binding properties match;
|
||||
- keep the original SPDX copyright lines and add a line for the current year (derived file).
|
||||
|
||||
Delete the old layout once nothing references it.
|
||||
|
||||
### Step 3: Write the fragment
|
||||
|
||||
Follow `references/ACTIVITY-TO-FRAGMENT-MAPPING.md`. The essentials:
|
||||
|
||||
- `class XFragment : Fragment()`, with `@Inject lateinit var` dependencies. Injection is done
|
||||
by `NavigatorActivity.onAttachFragment`, so `Injectable` is optional.
|
||||
- Nullable binding: `private var binding: FragmentXBinding? = null`. Set it to `null` in
|
||||
`onDestroyView`. Use `val binding = binding ?: return` in every function that touches views
|
||||
(#16783 fixed a crash after a configuration change caused by `_binding!!`).
|
||||
- Host access: `getTypedActivity(NavigatorActivity::class.java)` (or `DrawerActivity` /
|
||||
`BaseActivity` when that is all you need) for `user`, `storageManager`, `clientRepository`,
|
||||
`setUser`, `setDrawerIndicatorEnabled`, `startActionMode`.
|
||||
- Menu: `requireActivity().addMenuProvider(provider, viewLifecycleOwner, Lifecycle.State.RESUMED)`.
|
||||
Do **not** handle `android.R.id.home`. The host does that.
|
||||
- Back press: implement `NavigatorOnBackPressListener` only if the screen has internal
|
||||
navigation (Trashbin folders).
|
||||
- Remove `getMenuItemId()`, `setupDrawer()`, `setupToolbar()`, `highlightNavigationViewItem()`
|
||||
and title setup. `NavigatorScreen` + `NavigatorActivity.setupActionBar` handle all of these.
|
||||
- Keep files under 300 lines. Extract cohesive flows (conflict handling, credential checks,
|
||||
the menu provider) into their own classes in the fragment's package.
|
||||
|
||||
### Step 4: Decouple collaborators from the old Activity
|
||||
|
||||
Adapters, helpers and listeners typed as `XActivity` or `FileActivity` must take the
|
||||
narrowest type that has what they use. Usually that is `DrawerActivity`, `BaseActivity`,
|
||||
`NavigatorActivity` or a plain `Context`. Calls to capabilities the host lacks become
|
||||
callbacks on the click or listener interface, implemented by the fragment
|
||||
(e.g. `UploadListItemOnClick.onCredentialErrorClick(user)`).
|
||||
|
||||
### Step 5: Rewire every entry point
|
||||
|
||||
**Always** build the intent with `NavigatorActivity.intent(context, NavigatorScreen.X)`.
|
||||
`NavigatorActivity.onCreate` calls `requireNotNull` on the screen extra, so a bare
|
||||
`Intent(context, NavigatorActivity::class.java)` crashes (#17193).
|
||||
|
||||
| Old call site | New call site |
|
||||
|---|---|
|
||||
| `DrawerActivity.onNavigationItemClicked`: `startActivity(X.class, FLAG_ACTIVITY_CLEAR_TOP)` | `pushFragment(NavigatorScreen.X.INSTANCE)` |
|
||||
| Buttons in other DrawerActivities: `startActivity(X::class.java)` | `pushFragment(NavigatorScreen.X)` |
|
||||
| `handleDeepLink`: `startActivity(X.class)` | `pushFragment(NavigatorScreen.X.INSTANCE)` |
|
||||
| `PendingIntent` / `BroadcastReceiver` / Worker: `Intent(context, X::class.java)` | `NavigatorActivity.intent(context, NavigatorScreen.X).apply { flags = … }` |
|
||||
| `X.createIntent(...)` factory | inline `NavigatorActivity.intent(...)` + only the extras the fragment reads |
|
||||
|
||||
Keep the original flags (`FLAG_ACTIVITY_NEW_TASK`, `FLAG_ACTIVITY_CLEAR_TOP`, …). Extras the
|
||||
old base class consumed (e.g. `FileActivity.EXTRA_USER` → `setUser`) must now be read by the
|
||||
fragment from `activity?.intent`, once, when `savedInstanceState == null`.
|
||||
|
||||
### Step 6: DI, manifest, cleanup
|
||||
|
||||
- `ComponentsModule.java`: remove `abstract XActivity xActivity();` and add
|
||||
`@ContributesAndroidInjector abstract XFragment xFragment();`. Without this, injection
|
||||
fails at runtime.
|
||||
- `AndroidManifest.xml`: remove the `<activity>` entry.
|
||||
- Delete the Activity, update KDoc/Javadoc `[link]`s that pointed at it, and remove now-unused
|
||||
imports in files you edited.
|
||||
|
||||
### Step 7: Migrate the instrumented test
|
||||
|
||||
Rename `XActivityIT` to `XFragmentIT` and launch through the host:
|
||||
|
||||
```kotlin
|
||||
val intent = NavigatorActivity.intent(targetContext, NavigatorScreen.X)
|
||||
ActivityScenario.launch<NavigatorActivity>(intent).use { scenario -> … }
|
||||
```
|
||||
|
||||
To call into the fragment, find it with `sut.supportFragmentManager.fragments.filterIsInstance<XFragment>()`
|
||||
(see `TrashbinFragmentIT.launchFragment`). **Rename the reference screenshots with `git mv`**
|
||||
(`app/screenshots/generic/debug/<pkg>.XActivityIT_*.png` → `XFragmentIT_*.png`) so the
|
||||
screenshot test compares against the existing images instead of failing.
|
||||
|
||||
### Step 8: Verify
|
||||
|
||||
1. `./gradlew :app:compileGplayDebugKotlin :app:compileGplayDebugJavaWithJavac :app:compileGplayDebugAndroidTestKotlin`
|
||||
2. `./gradlew spotlessKotlinCheck detekt lintGplayDebug spotbugsGplayDebug`, then fix findings
|
||||
in every file you touched.
|
||||
3. `git grep -n "<ActivityName>\|<old_layout_name>"` returns nothing.
|
||||
4. Manual checklist (hand it to the developer if you cannot run the app): open from the
|
||||
drawer, from every notification or PendingIntent, from the deep link; rotate on the
|
||||
screen; switch to another drawer destination and press back; toggle the drawer with the
|
||||
hamburger; use every menu action; check light and dark themes.
|
||||
|
||||
## References
|
||||
|
||||
- `references/ARCHITECTURE.md`: how the navigator works.
|
||||
- `references/ACTIVITY-TO-FRAGMENT-MAPPING.md`: Activity API → fragment equivalent.
|
||||
- `references/HOST-CAPABILITIES.md`: what `NavigatorActivity` provides and what it does not.
|
||||
- `references/PITFALLS.md`: bugs that the earlier conversions ran into.
|
||||
- `assets/worked-example.md`: the upload list conversion, step by step.
|
||||
@@ -1,81 +0,0 @@
|
||||
<!--
|
||||
~ Nextcloud - Android Client
|
||||
~
|
||||
~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
~ SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
-->
|
||||
|
||||
# Worked Example: `UploadListActivity` → `UploadListFragment`
|
||||
|
||||
This conversion was the hardest one so far, because the Activity extended `FileActivity`.
|
||||
|
||||
## Inventory findings
|
||||
|
||||
- Base class `FileActivity`. The adapter called `activity.fileOperationsHelper.checkCurrentCredentials(user)`
|
||||
for uploads that failed with `CREDENTIAL_ERROR`. The result came back through
|
||||
`onRemoteOperationFinish` → `requestCredentialsUpdate` → `CheckRemoteWipeTask` →
|
||||
`performCredentialsUpdate` → `startActivityForResult(AuthenticatorActivity)` →
|
||||
`onActivityResult` → `FilesSyncHelper.restartUploadsIfNeeded`.
|
||||
- Entry points: drawer `nav_uploads`, `FileUploaderIntents.openUploadListIntent` (upload
|
||||
notifications, with `EXTRA_USER`), `AppWideNotificationManager.getUploadListPendingIntent`,
|
||||
`SyncConflictNotificationBroadcastReceiver`.
|
||||
- `EXTRA_USER` was consumed by `FileActivity.onCreate` → `setUser`. `EXTRA_FILE` was
|
||||
ignored (the Activity set `file = null`).
|
||||
- Menu: global pause/resume toggle. A `LocalBroadcastManager` receiver for upload events.
|
||||
`UploadWarningCard` registered in `onCreate` and unregistered in `onDestroy`.
|
||||
|
||||
## Decisions
|
||||
|
||||
- Host stays a `DrawerActivity`. The credential flow moves into the
|
||||
fragment.
|
||||
- To avoid copying `FileActivity` logic, `ui/helpers/CredentialsUpdateHelper.kt` was
|
||||
extracted. `FileActivity.performCredentialsUpdate`, `CheckRemoteWipeTask` and the fragment
|
||||
all use it.
|
||||
|
||||
## Resulting files
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `ui/fragment/uploadList/UploadListFragment.kt` | lifecycle, list setup, receiver, warning card, `EXTRA_USER` |
|
||||
| `ui/fragment/uploadList/UploadListMenuProvider.kt` | global pause toggle |
|
||||
| `ui/fragment/uploadList/UploadListConflictHandler.kt` | sync-conflict check and retry |
|
||||
| `ui/fragment/uploadList/UploadListCredentialsHandler.kt` | check credentials → remote wipe → re-login |
|
||||
| `ui/helpers/CredentialsUpdateHelper.kt` | credential steps shared with `FileActivity` |
|
||||
| `res/layout/fragment_upload_list.xml` | old layout without `DrawerLayout`/toolbar/drawer |
|
||||
|
||||
## Collaborator changes
|
||||
|
||||
- `UploadListAdapter(activity: FileActivity)` → `DrawerActivity`.
|
||||
`fileOperationsHelper.checkCurrentCredentials(user)` → `itemOnClick.onCredentialErrorClick(user)`.
|
||||
- `UploadListAdapterHelper(activity: FileActivity)` → `DrawerActivity`;
|
||||
`activity.accountManager` → `activity.userAccountManager`.
|
||||
- `UploadListItemOnClick` gained `onCredentialErrorClick(user: User)`.
|
||||
|
||||
## Entry point changes
|
||||
|
||||
```kotlin
|
||||
// FileUploaderIntents
|
||||
val intent = NavigatorActivity.intent(context, NavigatorScreen.UploadList).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
putExtra(FileActivity.EXTRA_USER, operation?.user)
|
||||
}
|
||||
|
||||
// AppWideNotificationManager, SyncConflictNotificationBroadcastReceiver
|
||||
val intent = NavigatorActivity.intent(context, NavigatorScreen.UploadList).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
// DrawerActivity.onNavigationItemClicked
|
||||
} else if (itemId == R.id.nav_uploads) {
|
||||
resetOnlyPersonalAndOnDevice();
|
||||
pushFragment(NavigatorScreen.UploadList.INSTANCE);
|
||||
```
|
||||
|
||||
## Cleanup
|
||||
|
||||
- `ComponentsModule`: `uploadListActivity()` removed, `uploadListFragment()` added.
|
||||
- Manifest entry removed. `UploadListActivity.kt` and `upload_list_layout.xml` deleted.
|
||||
- `FileUploadEventBroadcaster` KDoc links updated.
|
||||
- `UploadListActivityActivityIT` → `UploadListFragmentIT`, with screenshots `git mv`'d.
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
<!--
|
||||
~ Nextcloud - Android Client
|
||||
~
|
||||
~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
~ SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
-->
|
||||
|
||||
# Activity API → Navigator Fragment Equivalent
|
||||
|
||||
| In the Activity | In the fragment |
|
||||
|---|---|
|
||||
| `class X : DrawerActivity()` / `FileActivity()` | `class XFragment : Fragment()` |
|
||||
| `onCreate`: `setContentView(binding.root)` | `onCreateView`: `binding = FragmentXBinding.inflate(inflater, container, false)` |
|
||||
| View setup in `onCreate` | `onViewCreated` |
|
||||
| Non-view setup in `onCreate` (intent extras, config) | `onCreate` (guard extras with `savedInstanceState == null`) |
|
||||
| `onDestroy` cleanup tied to views/receivers registered in `onCreate` | `onDestroyView` |
|
||||
| `onStart`/`onStop`/`onResume` | same callbacks on the fragment |
|
||||
| `setupToolbar()`, `updateActionBarTitleAndHomeButtonByString`, `setupDrawer(menuItemId)` | delete; `NavigatorScreen.actionBarStyle()` + host |
|
||||
| `getMenuItemId()`, `highlightNavigationViewItem()` | delete; `NavigatorScreen.menuItemId()` + host |
|
||||
| `onCreateOptionsMenu` / `onOptionsItemSelected` | `MenuProvider` added with `viewLifecycleOwner, Lifecycle.State.RESUMED`; return `false` for ids you do not own |
|
||||
| `android.R.id.home` → toggle drawer | delete; the host handles it |
|
||||
| `OnBackPressedCallback` for internal navigation | `NavigatorOnBackPressListener` |
|
||||
| `mDrawerToggle.isDrawerIndicatorEnabled = x` | `navigatorActivity?.setDrawerIndicatorEnabled(x)` |
|
||||
| `addDrawerListener(l)` | `activity?.findViewById<DrawerLayout>(R.id.drawer_layout)?.addDrawerListener(l)` |
|
||||
| `startActionMode(cb)` | `navigatorActivity?.startActionMode(cb)` |
|
||||
| `findViewById(R.id.sort_button)` (toolbar views) | `activity?.findViewById(...)`; the toolbar belongs to the host |
|
||||
| `supportFragmentManager` for dialogs | `childFragmentManager`, or `requireActivity().supportFragmentManager` when the dialog calls back into the activity |
|
||||
| `this` as `Context` | `requireContext()` (inside callbacks: capture before launching) |
|
||||
| `this` as `Activity` (snackbars, PopupMenu, adapters) | `requireActivity()` / typed host |
|
||||
| `lifecycleScope` | `lifecycleScope` (fragment lifetime; survives while on back stack) or `viewLifecycleOwner.lifecycleScope` (view work only) |
|
||||
| `user`, `storageManager`, `clientRepository`, `capabilities` | `navigatorActivity?.user`, `.storageManager`, `.clientRepository`, `.capabilities` |
|
||||
| `setUser(user)` | `navigatorActivity?.setUser(user)` (`BaseActivity.setUser` is public) |
|
||||
| `startActivityForResult` + `onActivityResult` | `registerForActivityResult(StartActivityForResult())` as a fragment property |
|
||||
| `finish()` | `activity?.finish()` |
|
||||
| `DisplayUtils.showSnackMessage(this, …)` | `DisplayUtils.showSnackMessage(requireView(), …)` / `SnackbarUtil.show(this, …)` |
|
||||
| inner `BroadcastReceiver` class | `private val receiver = object : BroadcastReceiver() { … }`, avoids an extra type in the file |
|
||||
| `@Inject var x: T? = null` with `@JvmField` | `@Inject lateinit var x: T` |
|
||||
| Activity fields inherited from the base (`viewThemeUtils`, `preferences`, `connectivityService`, `accountManager`, `backgroundJobManager`) | `@Inject lateinit var` them in the fragment |
|
||||
|
||||
## Dialog listener lookups
|
||||
|
||||
Dialogs that cast `activity as Listener` break when the listener is now a fragment.
|
||||
Trashbin fixed `SortingOrderDialogFragment` with this fallback chain:
|
||||
|
||||
```kotlin
|
||||
val listener = parentFragment as? OnSortingOrderListener
|
||||
?: activity as? OnSortingOrderListener
|
||||
?: requireActivity().supportFragmentManager.fragments
|
||||
.firstOrNull { it is OnSortingOrderListener } as? OnSortingOrderListener
|
||||
```
|
||||
|
||||
Check every dialog the screen opens for the same pattern.
|
||||
@@ -1,89 +0,0 @@
|
||||
<!--
|
||||
~ Nextcloud - Android Client
|
||||
~
|
||||
~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
~ SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
-->
|
||||
|
||||
# Navigator Architecture
|
||||
|
||||
All classes live in `app/src/main/java/com/owncloud/android/ui/navigation/`.
|
||||
|
||||
```
|
||||
NavigatorActivity (DrawerActivity) activity_navigator.xml
|
||||
├─ toolbar_standard (appbar) DrawerLayout
|
||||
├─ FragmentContainerView ◄── Navigator ──► ├─ CoordinatorLayout
|
||||
└─ drawer │ ├─ appbar
|
||||
│ └─ fragment_container_view
|
||||
└─ drawer
|
||||
```
|
||||
|
||||
## `NavigatorScreen`: the destination registry
|
||||
|
||||
A `sealed class NavigatorScreen(val tag: String, val hasDrawer: Boolean = true) : Parcelable`.
|
||||
Each destination is a `@Parcelize object`, so it can travel in an `Intent` extra and is
|
||||
compared by identity in `when`.
|
||||
|
||||
| Member | Purpose |
|
||||
|---|---|
|
||||
| `tag` | Used as the fragment back-stack entry name. Must be unique |
|
||||
| `hasDrawer` | `true`: hamburger + unlocked drawer. `false`: back arrow + `LOCK_MODE_LOCKED_CLOSED` |
|
||||
| `fromTag(tag)` | Turns a back-stack entry name back into a screen. Used after configuration changes |
|
||||
| `menuItemId()` | Drawer item to highlight (`-1` for none) |
|
||||
| `actionBarStyle()` | `ActionBarStyle.Plain` → `setupToolbar()`, `Search` → `setupHomeSearchToolbarWithSortAndListButtons()`, plus title res |
|
||||
| `toFragment()` | Creates a fresh fragment instance |
|
||||
|
||||
## `Navigator`: the fragment stack
|
||||
|
||||
- `push(screen)`: ignores the call if a fragment with that tag already exists. Otherwise it
|
||||
does `replace(container, screen.toFragment())` + `addToBackStack(screen.tag)`.
|
||||
- `pop()`: `popBackStack()` and returns the new top screen.
|
||||
- `getTopScreen()`: reads the name of the last back-stack entry and maps it with `fromTag`.
|
||||
This keeps working after process death or rotation, because the `FragmentManager`
|
||||
restores the back stack. The in-memory `stack` does not survive that.
|
||||
|
||||
## `NavigatorActivity`: the host
|
||||
|
||||
- `onCreate`: inflates `ActivityNavigatorBinding`, then `requireNotNull`s the
|
||||
`EXTRA_SCREEN` extra. It either `push`es the screen (first launch) or restores the action
|
||||
bar from `getTopScreen()` (re-creation).
|
||||
- `onAttachFragment`: `AndroidSupportInjection.inject(fragment)` for **every** attached
|
||||
fragment. This is why converted fragments need a `@ContributesAndroidInjector` entry in
|
||||
`ComponentsModule`, even when they do not implement `Injectable`.
|
||||
- `setupActionBar(screen)`: toolbar style, title, drawer or back arrow, drawer lock mode.
|
||||
Called on every `push`/`pop`.
|
||||
- Back press (`OnBackPressedCallback`): close the drawer → let the top
|
||||
`NavigatorOnBackPressListener` intercept → `finish()` if only one entry is left → `pop()`.
|
||||
- Home button (`onOptionsItemSelected(android.R.id.home)`): listener intercept → back if
|
||||
`!hasDrawer` → toggle the drawer otherwise.
|
||||
- `getMenuItemId()` / `onResume`: highlight the drawer item of the top screen.
|
||||
- `NavigatorActivity.intent(context, screen)`: the **only** correct way to build a launch
|
||||
intent.
|
||||
|
||||
## `DrawerActivity.pushFragment(screen)`
|
||||
|
||||
```java
|
||||
public void pushFragment(NavigatorScreen screen) {
|
||||
if (this instanceof NavigatorActivity navigatorActivity) {
|
||||
navigatorActivity.push(screen); // already in the navigator: swap fragment
|
||||
} else {
|
||||
startActivity(NavigatorActivity.Companion.intent(this, screen)); // e.g. from FileDisplayActivity
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Drawer item clicks call this, so moving between converted screens swaps fragments
|
||||
inside a single `NavigatorActivity` instead of starting a new Activity each time.
|
||||
|
||||
## `NavigatorOnBackPressListener`
|
||||
|
||||
```kotlin
|
||||
interface NavigatorOnBackPressListener {
|
||||
fun canInterceptBackPress(): Boolean
|
||||
fun interceptBackPress()
|
||||
}
|
||||
```
|
||||
|
||||
Implement it in a fragment that has its own navigation inside the screen. For example,
|
||||
`TrashbinFragment` goes up one folder while `trashbinPresenter.isRoot == false`. The host
|
||||
checks it for both the system back gesture and the toolbar home button.
|
||||
@@ -1,44 +0,0 @@
|
||||
<!--
|
||||
~ Nextcloud - Android Client
|
||||
~
|
||||
~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
~ SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
-->
|
||||
|
||||
# What `NavigatorActivity` Provides
|
||||
|
||||
`NavigatorActivity` extends `DrawerActivity → ToolbarActivity → BaseActivity`. It does
|
||||
**not** extend `FileActivity`. Decided to keep it that way: making every
|
||||
navigator screen a `FileActivity` would bind `OperationsService` for all of them and show
|
||||
`FileActivity`'s offline info box on screens that never had one.
|
||||
|
||||
## Available from the host
|
||||
|
||||
- `BaseActivity`: `user`, `setUser(user)`, `capabilities`, `storageManager`,
|
||||
`clientRepository`, `userAccountManager`, `account`.
|
||||
- `ToolbarActivity`: toolbar setup, `showInfoBox`/`hideInfoBox` (only called by
|
||||
`FileActivity`), sort and grid toolbar buttons (`R.id.sort_button`,
|
||||
`R.id.switch_grid_view_button`).
|
||||
- `DrawerActivity`: `appPreferences`, `openDrawer`/`closeDrawer`/`isDrawerOpen`,
|
||||
`setDrawerIndicatorEnabled`, `pushFragment`, `fetchExternalLinks`.
|
||||
|
||||
## Not available: `FileActivity`-only features
|
||||
|
||||
| `FileActivity` feature | How to replace it in a fragment |
|
||||
|---|---|
|
||||
| `fileOperationsHelper.*` (queues operations on `OperationsService`) | Run the `RemoteOperation`/`SyncOperation` directly in `lifecycleScope` on `Dispatchers.IO` with a client for the right user |
|
||||
| `onRemoteOperationFinish(op, result)` override | Handle the result inline after the coroutine returns |
|
||||
| `requestCredentialsUpdate(account)` → `CheckRemoteWipeTask` → `performCredentialsUpdate` | `CredentialsUpdateHelper` (`isRemoteWipeRequested`, `invalidateCredentials`, `createUpdateCredentialsIntent`) + `registerForActivityResult` |
|
||||
| `onActivityResult(REQUEST_CODE__UPDATE_CREDENTIALS, RESULT_OK)` | the `ActivityResultLauncher` callback |
|
||||
| `showLoadingDialog` / `dismissLoadingDialog` | `LoadingDialog.newInstance(msg).show(childFragmentManager, TAG)` and `dismissAllowingStateLoss()` |
|
||||
| `EXTRA_USER` → `setUser` in `onCreate` | fragment reads `activity?.intent` and calls `navigatorActivity?.setUser` |
|
||||
| `EXTRA_FILE` → `file` | read it in the fragment if it is used, otherwise drop it from the callers |
|
||||
| `connectivityService`, `backgroundJobManager`, `accountManager` fields | `@Inject lateinit var` in the fragment |
|
||||
|
||||
## De-duplication rule
|
||||
|
||||
When a fragment needs logic that a base Activity implements privately, **do not copy it**.
|
||||
Extract the reusable steps into a Kotlin helper (e.g. `ui/helpers/CredentialsUpdateHelper.kt`).
|
||||
Have the original Activity code call the helper too, so there is one implementation.
|
||||
Only the orchestration specific to the fragment (coroutines, result launcher, dialog) should
|
||||
live in the fragment's package.
|
||||
@@ -1,71 +0,0 @@
|
||||
<!--
|
||||
~ Nextcloud - Android Client
|
||||
~
|
||||
~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
~ SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
-->
|
||||
|
||||
# Pitfalls Found in Earlier Conversions
|
||||
|
||||
## Bare intents crash the host (#17193)
|
||||
|
||||
`NotificationWork` was changed to `Intent(context, NavigatorActivity::class.java)` without
|
||||
a screen. `NavigatorActivity.onCreate` calls `requireNotNull` on `EXTRA_SCREEN`, so tapping
|
||||
the notification crashed. Always use `NavigatorActivity.intent(context, NavigatorScreen.X)`.
|
||||
Check **every** `PendingIntent`, `BroadcastReceiver`, Worker and notification manager that
|
||||
referenced the old Activity.
|
||||
|
||||
## `binding!!` after a configuration change (#16783)
|
||||
|
||||
The `_binding!!` / `val binding get() = _binding!!` pattern crashed when a callback
|
||||
(presenter, coroutine, receiver) fired after `onDestroyView`. Use a nullable
|
||||
`private var binding` and `val binding = binding ?: return` in each function.
|
||||
|
||||
## Screen not restored after rotation (#16783)
|
||||
|
||||
`NavigatorActivity` only re-applies the action bar and drawer highlight if
|
||||
`NavigatorScreen.fromTag` knows the tag. `fromTag` is not an exhaustive `when` over the
|
||||
sealed class, so the compiler does not catch a missing entry.
|
||||
|
||||
## Dependency injection
|
||||
|
||||
`NavigatorActivity.onAttachFragment` injects every fragment. That only works if
|
||||
`ComponentsModule` has a `@ContributesAndroidInjector abstract XFragment xFragment();`.
|
||||
Without it you get an `IllegalArgumentException: No injector factory bound` at runtime, not at
|
||||
compile time. `addFragmentOnAttachListener` / lifecycle callbacks did not behave the same,
|
||||
which is why the deprecated `onAttachFragment` is used.
|
||||
|
||||
## Toolbar views belong to the host
|
||||
|
||||
Sort and grid buttons, the info box and the search bar live in the host's `toolbar_standard`.
|
||||
Reach them with `activity?.findViewById`. Set their visibility explicitly, because the
|
||||
previous screen may have changed it.
|
||||
|
||||
## Dialog callbacks
|
||||
|
||||
Dialogs that do `activity as Listener` silently stop working when the listener is now a
|
||||
fragment (see the `SortingOrderDialogFragment` fix in `ACTIVITY-TO-FRAGMENT-MAPPING.md`).
|
||||
|
||||
## Lifecycle scope choice
|
||||
|
||||
Long-running work started by the user (retrying an upload, executing an action) should use
|
||||
the fragment's `lifecycleScope`. That keeps it running while the fragment sits on the back
|
||||
stack with its view destroyed. Only pure view work should use
|
||||
`viewLifecycleOwner.lifecycleScope`. Always null-check the binding when the work returns.
|
||||
|
||||
## Receivers and registrations
|
||||
|
||||
Anything registered in the Activity's `onCreate` and released in `onDestroy` (e.g.
|
||||
`UploadWarningCard.register/unregister`) must move to `onViewCreated`/`onDestroyView`.
|
||||
Otherwise it leaks across back-stack transitions or registers twice.
|
||||
|
||||
## Screenshot tests
|
||||
|
||||
Renaming `XActivityIT` → `XFragmentIT` changes the screenshot names. `git mv` the PNGs in
|
||||
`app/screenshots/generic/debug/` to match, or CI reports missing references.
|
||||
|
||||
## File size and type rules
|
||||
|
||||
`AGENTS.md` caps files at 300 lines and wants one type per file. Activities converted to
|
||||
fragments often exceed 300 lines. Split cohesive flows (menu provider, conflict handler,
|
||||
credentials handler) into separate classes in the fragment's package.
|
||||
@@ -1,135 +0,0 @@
|
||||
---
|
||||
name: android-eventbus-to-workmanager-flow
|
||||
description: >
|
||||
Use when replacing a GreenRobot EventBus event that a WorkManager worker posts (progress,
|
||||
state, completion) with WorkManager's own observation APIs, consumed through a ViewModel
|
||||
Flow; when the user mentions "event bus", "EventBus", "EventBusFactory", "@Subscribe",
|
||||
"worker progress", "setProgress", "observe worker", "getWorkInfosForUniqueWorkFlow" or
|
||||
"listen to the worker through the viewmodel". Covers publishing progress from the worker,
|
||||
building the ViewModel Flow keyed by the work name, DI registration, collecting the Flow
|
||||
from Kotlin or legacy Java fragments/activities, and deleting the event classes.
|
||||
license: AGPL-3.0-or-later
|
||||
SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
metadata:
|
||||
author: Nextcloud Android
|
||||
version: "1.0.0"
|
||||
---
|
||||
|
||||
# EventBus → WorkManager Flow via ViewModel
|
||||
|
||||
Workers used to tell the UI what they were doing by posting GreenRobot EventBus events
|
||||
(`EventBusFactory.downloadProgressEventBus.post(FileDownloadProgressEvent(percent))`). That
|
||||
has three problems: the event is global (every subscriber gets every worker's events,
|
||||
whatever file it is about), it is lost when nobody is registered, and the subscriber has to
|
||||
register and unregister by hand in `onStart`/`onStop`.
|
||||
|
||||
WorkManager already stores each worker's state and progress and exposes them as `Flow`s. The
|
||||
UI asks WorkManager about **one specific piece of work**, through a ViewModel, and collects
|
||||
the Flow with the lifecycle. Official guide:
|
||||
https://developer.android.com/develop/background-work/background-tasks/persistent/how-to/observe
|
||||
|
||||
Converted so far: `FileDownloadProgressEvent` → `FileDetailFragmentViewModel.downloadProgress`
|
||||
(see `assets/worked-example.md`). The earlier `FileDisplayActivityViewModel.observeOfflineWorker`
|
||||
is the simplest form of the same pattern (state only, Kotlin consumer).
|
||||
|
||||
## The Prime Directive: Behaviour Must Not Change
|
||||
|
||||
The screen must show the same thing at the same moments as before. The only intended
|
||||
differences are the ones the global bus got wrong: a screen now only reacts to the work it is
|
||||
about. Write them down for the PR description. If you find an unrelated bug, report it
|
||||
instead of fixing it in the same change.
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 0: Inventory (do not edit yet)
|
||||
|
||||
1. `git grep -n "<EventName>"` across `app/src`. List every **poster** (usually a worker) and
|
||||
every **subscriber** (`@Subscribe fun on…(event: <EventName>)`).
|
||||
2. If the event lives on a dedicated bus (`EventBusFactory.<x>EventBus`), also grep for the
|
||||
bus. When it has no other users, delete it together with the event.
|
||||
3. For each poster, find how its work is enqueued in `BackgroundJobManagerImpl`: the
|
||||
**unique work name** (`enqueueUniqueWork(name, …)`) and the **tags** (`oneTimeRequestBuilder`
|
||||
adds `formatNameTag`, `formatClassTag`, `formatUserTag`, plus any custom tag). The UI
|
||||
must be able to rebuild exactly one of these from what it already knows (user, file id…).
|
||||
4. List what each event field carries and what the subscriber does with it. Decide whether
|
||||
it is **progress** (while running → `setProgress`), a **result** (at the end →
|
||||
`Result.success(outputData)`), or only **state** (`WorkInfo.state`, nothing to publish).
|
||||
5. Look for older parallel mechanisms the subscriber also uses for the same purpose (bound
|
||||
listeners, `LocalBroadcastManager`). If you can prove one is dead (e.g. a field that is
|
||||
only ever set to `null`), remove it with all its plumbing, including test doubles in
|
||||
`app/src/debug` and mocks in `androidTest`. Otherwise leave it and mention it in the summary.
|
||||
|
||||
### Step 1: Make the work addressable
|
||||
|
||||
If the unique work name / tag builder is `private` in `BackgroundJobManagerImpl`, move it
|
||||
into the `companion object` next to `formatNameTag`/`formatClassTag` as a public
|
||||
`format…Tag(...)` function, and have the enqueue and cancel call sites use it. The UI and
|
||||
the scheduler must build the name with the same function, never with a copied string.
|
||||
|
||||
### Step 2: Publish from the worker
|
||||
|
||||
- Add the `Data` key as a `const val` in the worker's `companion object`
|
||||
(`const val PROGRESS_PERCENT = "PROGRESS_PERCENT"`).
|
||||
- From a `suspend` context call `setProgress(workDataOf(KEY to value))`. From a non-suspend
|
||||
callback (e.g. `OnDatatransferProgressListener.onTransferProgress`) call
|
||||
`setProgressAsync(...)`.
|
||||
- **Throttle it.** WorkManager writes progress to its database. Publish only when the value
|
||||
changed, and reuse an existing throttle (the notification update interval) when the
|
||||
worker has one.
|
||||
- Results go in `Result.success(workDataOf(...))` and are read from `WorkInfo.outputData`.
|
||||
- Delete the `post(...)` call and the event imports.
|
||||
|
||||
### Step 3: ViewModel
|
||||
|
||||
One ViewModel per screen, in a package next to the screen
|
||||
(`ui/fragment/<screen>/<Screen>FragmentViewModel.kt`, mirroring
|
||||
`ui/activity/filedisplayactivity/FileDisplayActivityViewModel.kt`). Template:
|
||||
`references/VIEWMODEL-TEMPLATE.md`.
|
||||
|
||||
- Constructor-inject `WorkManager` (`@Inject constructor(private val workManager: WorkManager)`).
|
||||
- Hold the work name the screen is interested in a `MutableStateFlow<String?>`. A setter
|
||||
function (`observeDownloadProgress(user, file)`) builds it with the Step 1 function.
|
||||
- Expose a **cold** `Flow<T>`: `filterNotNull()` → `flatMapLatest { getWorkInfosForUniqueWorkFlow(it) }`
|
||||
→ map the `WorkInfo` list to the UI value → `distinctUntilChanged()`. Use
|
||||
`getWorkInfoByIdFlow(id)` when you have the request id, `getWorkInfosByTagFlow(tag)` when
|
||||
the work is not unique.
|
||||
- Progress is only present while `state == RUNNING`. It is empty after the work finishes, so
|
||||
filter on `RUNNING` and drop missing keys (`progress.keyValueMap[KEY] as? Int`).
|
||||
- Register it in `di/ViewModelModule.kt` with `@Binds @IntoMap @ViewModelKey(X::class)`.
|
||||
Without this, `ViewModelFactory` throws at runtime.
|
||||
|
||||
### Step 4: Consumer
|
||||
|
||||
- Get the ViewModel from `ViewModelFactory`: Kotlin `by viewModels { vmFactory }`, Java
|
||||
`new ViewModelProvider(this, vmFactory).get(X.class)` in `onCreate`. Injection of
|
||||
`Injectable` fragments happens before `onAttach`, so `vmFactory` is ready in `onCreate`.
|
||||
- Tell the ViewModel what to watch where the screen learns its subject (`onViewCreated`,
|
||||
and every public "show this other file" method such as `updateFileDetails(file, user)`).
|
||||
- Collect with the **view** lifecycle in fragments:
|
||||
- Kotlin: `viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(STARTED) { vm.flow.collect { … } } }`
|
||||
- Java: `LifecycleOwnerExtensionsKt.collectWhenStarted(getViewLifecycleOwner(), viewModel.getX(), this::onX);`
|
||||
(`utils/extensions/LifecycleOwnerExtensions.kt`). Do not switch to `LiveData` for Java
|
||||
callers. See `references/PITFALLS.md` for why.
|
||||
- Turn the old `@Subscribe public void onX(Event e)` into `private void onX(T value)`. Keep
|
||||
its body unchanged apart from reading the value directly.
|
||||
- Remove the `register`/`unregister` lines for the bus. Keep `EventBus.getDefault()` registration
|
||||
if the class still has other `@Subscribe` methods.
|
||||
|
||||
### Step 5: Delete and verify
|
||||
|
||||
1. Delete the event class (and the dedicated bus if it has no users left).
|
||||
2. `git grep -n "<EventName>\|<busName>"` returns nothing.
|
||||
3. `./gradlew :app:compileGplayDebugJavaWithJavac spotlessKotlinCheck detekt`, then
|
||||
`lintGplayDebug spotbugsGplayDebug`. Fix findings in every file you touched.
|
||||
4. Manual check (hand it to the developer if you cannot run the app): start the work and
|
||||
open the screen, so the value shows up; open the screen first, then start the work; rotate
|
||||
while it runs; leave the screen for more than 5 s, let the work finish, come back (no stale
|
||||
value); open the screen for a *different* subject while work runs for another one (it must
|
||||
not react).
|
||||
|
||||
## References
|
||||
|
||||
- `references/VIEWMODEL-TEMPLATE.md`: ViewModel, worker and consumer snippets.
|
||||
- `references/PITFALLS.md`: what went wrong or nearly went wrong.
|
||||
- `assets/worked-example.md`: `FileDownloadProgressEvent` → `FileDetailFragmentViewModel`.
|
||||
@@ -1,56 +0,0 @@
|
||||
<!--
|
||||
~ Nextcloud - Android Client
|
||||
~
|
||||
~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
~ SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
-->
|
||||
|
||||
# Worked Example: `FileDownloadProgressEvent` → `FileDetailFragmentViewModel`
|
||||
|
||||
## Inventory findings
|
||||
|
||||
- Event: `ui/events/FileDownloadProgressEvent(percent: Int)` on a dedicated bus,
|
||||
`ui/events/EventBusFactory.downloadProgressEventBus`. Neither had other users.
|
||||
- Poster: `FileDownloadWorker.onTransferProgress`, on every transfer chunk, unthrottled, with
|
||||
no file information.
|
||||
- Subscriber: `FileDetailFragment` (Java). It registered the bus in `onStart`, unregistered
|
||||
it in `onStop`, and `@Subscribe(threadMode = MAIN) onDownloadProgress` showed the progress
|
||||
block with the "downloading" text and the percent.
|
||||
- Enqueue: `BackgroundJobManagerImpl.startFileDownloadJob` →
|
||||
`enqueueUniqueWork(startFileDownloadJobTag(accountName, fileId), KEEP, request)`, and the
|
||||
same string as a tag. The builder was `private`.
|
||||
- Parallel mechanism: `containerActivity.getFileDownloadProgressListener()` /
|
||||
`FileDownloadWorker.FileDownloadProgressListener`. The field in `FileActivity` is never
|
||||
assigned, so it is always `null`, which is why the bus was added (commit `37df0dca9d`).
|
||||
Removed in the same change, since the ViewModel replaces it.
|
||||
- Folders use `FolderDownloadWorker`, which never posted the event.
|
||||
|
||||
## Changes
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `jobs/BackgroundJobManagerImpl.kt` | `startFileDownloadJobTag` → public companion `formatFileDownloadTag`, used by start and cancel |
|
||||
| `jobs/download/FileDownloadWorker.kt` | `PROGRESS_PERCENT` key; `setProgressAsync(workDataOf(PROGRESS_PERCENT to percent))` inside the notification throttle; bus post removed |
|
||||
| `ui/fragment/filedetail/FileDetailFragmentViewModel.kt` | new; `downloadProgress: Flow<Int>` keyed by `formatFileDownloadTag` |
|
||||
| `di/ViewModelModule.kt` | `@Binds @IntoMap @ViewModelKey(FileDetailFragmentViewModel::class)` |
|
||||
| `utils/extensions/LifecycleOwnerExtensions.kt` | new; `collectWhenStarted(flow, Consumer)` for Java consumers |
|
||||
| `ui/fragment/FileDetailFragment.java` | `ViewModelFactory` inject, VM in `onCreate`, `observeDownloadProgress` in `onViewCreated` and `updateFileDetails(file, user)`, `collectWhenStarted` on the view lifecycle, `@Subscribe` → `private void onDownloadProgress(int)`, bus register/unregister removed |
|
||||
| `ui/events/FileDownloadProgressEvent.kt`, `ui/events/EventBusFactory.kt` | deleted |
|
||||
| `FileDownloadWorker.FileDownloadProgressListener` and its plumbing | deleted: inner class, worker field, `ComponentsGetter.getFileDownloadProgressListener()`, `FileActivity` field and getter, the two `= null` assignments in `FileDisplayActivity`, the download branches of `FileDetailFragment.listenForTransferProgress`/`leaveTransferProgress`, the `TestActivity` override and the `FileMenuFilterIT` mock |
|
||||
|
||||
## Intended behaviour differences
|
||||
|
||||
- Progress is shown only for the file the details screen is about, not for whichever file is
|
||||
downloading.
|
||||
- The UI updates at the notification throttle (750 ms) instead of on every chunk.
|
||||
|
||||
## Decisions
|
||||
|
||||
- **Cold `Flow` + `collectWhenStarted`, not `LiveData`.** `LiveData` replayed a stale
|
||||
percent after a finish that happened while the view was stopped (see `PITFALLS.md`).
|
||||
- **The ViewModel is created in `onCreate`, not `onViewCreated`.** The activity can call
|
||||
`updateFileDetails(file, user)` before the view exists, and the ViewModel must survive view
|
||||
re-creation from the back stack.
|
||||
- **The finished state is still handled by the existing broadcast path.**
|
||||
`FileDisplayActivity` calls `updateFileDetails(false, true)` on `ACTION_DOWNLOAD_COMPLETED`.
|
||||
Moving that to `WorkInfo.State.SUCCEEDED` is a possible follow-up, not part of this change.
|
||||
@@ -1,67 +0,0 @@
|
||||
<!--
|
||||
~ Nextcloud - Android Client
|
||||
~
|
||||
~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
~ SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
-->
|
||||
|
||||
# Pitfalls
|
||||
|
||||
## `LiveData` replays a stale value
|
||||
|
||||
The first draft exposed `asLiveData()` so the Java fragment could `observe(...)`. `LiveData`
|
||||
keeps its last value and stops collecting upstream 5 s after the last observer goes away. If
|
||||
the download finishes during those 5 s, the cached value is the last running percent, and
|
||||
the next observer gets it right away. The progress block is shown again for a download that
|
||||
has already finished. A cold `Flow` collected with `repeatOnLifecycle` asks WorkManager again
|
||||
on every start and only gets the current state. Use `collectWhenStarted` from Java instead
|
||||
of `LiveData`.
|
||||
|
||||
## Progress disappears when the work finishes
|
||||
|
||||
`WorkInfo.progress` is empty as soon as the state leaves `RUNNING`. Do not read progress
|
||||
from `SUCCEEDED`/`FAILED` infos, and do not treat the missing key as `0`. Use `mapNotNull`
|
||||
and let the existing "finished" path (broadcast, `updateFileDetails(false, true)`) hide the
|
||||
UI, as it did before. Put final values in `Result.success(outputData)` if the UI needs them.
|
||||
|
||||
## Every `setProgress` is a database write
|
||||
|
||||
WorkManager persists progress. Calling it on every transfer chunk writes to the database
|
||||
hundreds of times per file. Publish only on change and inside the worker's existing
|
||||
throttle (`minProgressUpdateInterval`).
|
||||
|
||||
## Unique work name vs tag
|
||||
|
||||
`getWorkInfosForUniqueWorkFlow(name)` matches the `enqueueUniqueWork` name.
|
||||
`getWorkInfosByTagFlow(tag)` matches `addTag`. In `startFileDownloadJob` the same string
|
||||
is used for both, but that is not true for every job. Check the enqueue call. Never build the
|
||||
string by hand in the ViewModel. Make the builder public in the
|
||||
`BackgroundJobManagerImpl` companion.
|
||||
|
||||
## The bus was global; the Flow is not
|
||||
|
||||
`FileDownloadProgressEvent` reached `FileDetailFragment` for **any** running download, so
|
||||
the details of file A could show the progress of file B. The ViewModel is keyed by
|
||||
account + file id, so it only reacts to its own file. This is the intended change; mention it
|
||||
in the PR. Check which worker really runs for each subject: folders are downloaded by
|
||||
`FolderDownloadWorker`, not `FileDownloadWorker`, and never posted the event.
|
||||
|
||||
## The subject can change without a new view
|
||||
|
||||
`FileDetailFragment.updateFileDetails(OCFile, User)` swaps the file on a live fragment. Call
|
||||
`viewModel.observeX(...)` there too. Thanks to `flatMapLatest`, the old work's Flow is
|
||||
cancelled automatically. Guard with `viewModel != null` because the activity can call it on a
|
||||
fragment that has not reached `onCreate` yet.
|
||||
|
||||
## Missing ViewModel binding
|
||||
|
||||
Forgetting `@Binds @IntoMap @ViewModelKey(X::class)` in `ViewModelModule` compiles, but
|
||||
`ViewModelFactory` throws `IllegalArgumentException` when the screen opens.
|
||||
|
||||
## Keep other `@Subscribe` methods registered
|
||||
|
||||
`FileDetailFragment` still receives `FavoriteEvent` on `EventBus.getDefault()`. Remove only
|
||||
the registration for the bus you are replacing. Removing the default registration silently
|
||||
stops the remaining events. The other way round fails too: if the last `@Subscribe` method
|
||||
goes away but `register(this)` stays, EventBus throws `EventBusException` ("has no public
|
||||
methods with the @Subscribe annotation") when the screen starts.
|
||||
@@ -1,126 +0,0 @@
|
||||
<!--
|
||||
~ Nextcloud - Android Client
|
||||
~
|
||||
~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
~ SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
-->
|
||||
|
||||
# Templates
|
||||
|
||||
## Worker
|
||||
|
||||
```kotlin
|
||||
companion object {
|
||||
const val PROGRESS_PERCENT = "PROGRESS_PERCENT"
|
||||
}
|
||||
|
||||
// suspend context
|
||||
setProgress(workDataOf(PROGRESS_PERCENT to percent))
|
||||
|
||||
// non-suspend callback, inside the existing throttle
|
||||
if (percent != lastPercent && (currentTime - lastUpdateTime) >= minProgressUpdateInterval) {
|
||||
notificationManager.updateDownloadProgress(percent, totalToTransfer)
|
||||
setProgressAsync(workDataOf(PROGRESS_PERCENT to percent))
|
||||
lastUpdateTime = currentTime
|
||||
}
|
||||
```
|
||||
|
||||
## Work name (BackgroundJobManagerImpl companion)
|
||||
|
||||
```kotlin
|
||||
fun formatFileDownloadTag(accountName: String, fileId: Long): String =
|
||||
JOB_FOLDER_DOWNLOAD + accountName + fileId
|
||||
```
|
||||
|
||||
Use it in `startXJob` (`enqueueUniqueWork(tag, …)`), in `cancelXJob`, and in the ViewModel.
|
||||
|
||||
## ViewModel
|
||||
|
||||
```kotlin
|
||||
class FileDetailFragmentViewModel @Inject constructor(private val workManager: WorkManager) : ViewModel() {
|
||||
|
||||
private val downloadWorkName = MutableStateFlow<String?>(null)
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
val downloadProgress: Flow<Int> = downloadWorkName
|
||||
.filterNotNull()
|
||||
.flatMapLatest { workManager.getWorkInfosForUniqueWorkFlow(it) }
|
||||
.mapNotNull { workInfos -> workInfos.firstOrNull { it.state == WorkInfo.State.RUNNING }?.downloadPercent() }
|
||||
.distinctUntilChanged()
|
||||
|
||||
fun observeDownloadProgress(user: User, file: OCFile) {
|
||||
downloadWorkName.value = BackgroundJobManagerImpl.formatFileDownloadTag(user.accountName, file.fileId)
|
||||
}
|
||||
|
||||
private fun WorkInfo.downloadPercent(): Int? = progress.keyValueMap[FileDownloadWorker.PROGRESS_PERCENT] as? Int
|
||||
}
|
||||
```
|
||||
|
||||
State-only variant (no progress published), from `FileDisplayActivityViewModel`:
|
||||
|
||||
```kotlin
|
||||
suspend fun observeOfflineWorker(onComplete: () -> Unit) {
|
||||
workManager
|
||||
.getWorkInfosByTagFlow(BackgroundJobManagerImpl.formatClassTag(OfflineOperationsWorker::class))
|
||||
.collect { workInfos ->
|
||||
if (workInfos.any { it.state == WorkInfo.State.SUCCEEDED }) {
|
||||
onComplete()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Prefer exposing a `Flow` property over a `suspend fun` with a callback: the consumer decides
|
||||
the lifecycle, and Java can collect it through `collectWhenStarted`.
|
||||
|
||||
## DI (`di/ViewModelModule.kt`)
|
||||
|
||||
```kotlin
|
||||
@Binds
|
||||
@IntoMap
|
||||
@ViewModelKey(FileDetailFragmentViewModel::class)
|
||||
abstract fun fileDetailFragmentViewModel(vm: FileDetailFragmentViewModel): ViewModel
|
||||
```
|
||||
|
||||
## Kotlin consumer (fragment)
|
||||
|
||||
```kotlin
|
||||
@Inject lateinit var vmFactory: ViewModelFactory
|
||||
private val viewModel by viewModels<FileDetailFragmentViewModel> { vmFactory }
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
viewModel.observeDownloadProgress(user, file)
|
||||
viewLifecycleOwner.lifecycleScope.launch {
|
||||
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.downloadProgress.collect(::onDownloadProgress)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Java consumer (fragment)
|
||||
|
||||
```java
|
||||
@Inject ViewModelFactory vmFactory;
|
||||
private FileDetailFragmentViewModel viewModel;
|
||||
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
viewModel = new ViewModelProvider(this, vmFactory).get(FileDetailFragmentViewModel.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
viewModel.observeDownloadProgress(user, getFile());
|
||||
LifecycleOwnerExtensionsKt.collectWhenStarted(getViewLifecycleOwner(),
|
||||
viewModel.getDownloadProgress(),
|
||||
this::onDownloadProgress);
|
||||
}
|
||||
|
||||
private void onDownloadProgress(int percent) { … }
|
||||
```
|
||||
|
||||
`collectWhenStarted` (`utils/extensions/LifecycleOwnerExtensions.kt`) wraps
|
||||
`lifecycleScope.launch { repeatOnLifecycle(STARTED) { flow.collect(collector::accept) } }`
|
||||
and takes an `androidx.core.util.Consumer`, so a Java method reference fits.
|
||||
@@ -0,0 +1,5 @@
|
||||
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
exclude_paths:
|
||||
- "app/src/main/cpp/**"
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM ubuntu:resolute@sha256:6a06111c3b0a8600feadb270aec771dc239bf407b25625f93f44ab00e11f4d3c
|
||||
FROM ubuntu:resolute@sha256:513c074113a871b51a8d16ab445c88779d6452d937a164fb5cc479f32668a41d
|
||||
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
ENV ANDROID_HOME=/usr/lib/android-sdk
|
||||
|
||||
@@ -26,7 +26,7 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
analysis:
|
||||
runs-on: ubuntu-latest-max
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Disabled on forks
|
||||
if: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }}
|
||||
@@ -57,10 +57,10 @@ jobs:
|
||||
repository: ${{ steps.get-vars.outputs.repo }}
|
||||
ref: ${{ steps.get-vars.outputs.branch }}
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 25
|
||||
java-version: 21
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
sudo apt install python3-defusedxml
|
||||
@@ -70,7 +70,7 @@ jobs:
|
||||
run: |
|
||||
mkdir -p "$HOME/.gradle"
|
||||
{
|
||||
echo "org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8"
|
||||
echo "org.gradle.jvmargs=-Xmx1g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8"
|
||||
echo "org.gradle.configureondemand=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 }}"
|
||||
@@ -33,13 +33,13 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: set up JDK 21
|
||||
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 21
|
||||
- uses: gradle/actions/wrapper-validation@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1
|
||||
- uses: gradle/actions/wrapper-validation@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1
|
||||
uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
|
||||
- name: Build ${{ matrix.flavor }}
|
||||
run: |
|
||||
{
|
||||
|
||||
@@ -26,11 +26,11 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 21
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1
|
||||
uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
|
||||
- name: Check ${{ matrix.task }}
|
||||
run: ./gradlew ${{ matrix.task }}
|
||||
@@ -1,7 +1,6 @@
|
||||
# synced from @nextcloud/android-config
|
||||
|
||||
# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2023-2024 Andy Scherzinger <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2022 Tobias Kaminsky <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2022 Álvaro Brey <[email protected]>
|
||||
@@ -22,14 +21,13 @@ permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: codeql-${{ github.event.pull_request.number || github.run_id }}
|
||||
group: codeql-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
runs-on: ubuntu-latest-max
|
||||
timeout-minutes: 90
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
@@ -49,18 +47,17 @@ jobs:
|
||||
with:
|
||||
swap-size-gb: 10
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
uses: github/codeql-action/init@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 25
|
||||
- name: Assemble
|
||||
run: |
|
||||
mkdir -p "$HOME/.gradle"
|
||||
echo "org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError" > "$HOME/.gradle/gradle.properties"
|
||||
./gradlew --no-daemon assembleDebug
|
||||
java-version: 21
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
|
||||
- name: Compile sources
|
||||
run: ./gradlew --no-daemon --no-build-cache :app:compileGplayDebugSources
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
uses: github/codeql-action/analyze@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
|
||||
@@ -17,12 +17,12 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
detectWrongSettings:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 21
|
||||
|
||||
@@ -17,7 +17,7 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-24.04
|
||||
services:
|
||||
server:
|
||||
image: ${{ matrix.server == 'stable22' && 'ghcr.io/nextcloud/continuous-integration-shallow-server-php8.0:1' || 'ghcr.io/nextcloud/continuous-integration-shallow-server-php8.3:latest' }}
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
|
||||
- name: configure server
|
||||
run: |
|
||||
sudo apt-get update && sudo apt-get install unzip cpu-checker qemu-system-x86 --yes
|
||||
sudo apt-get update && sudo apt-get install unzip cpu-checker qemu-kvm --yes
|
||||
sudo chmod 666 /dev/kvm
|
||||
docker cp .github/workflows/configServer.sh server:/tmp/
|
||||
docker exec server chmod +x /tmp/configServer.sh
|
||||
@@ -45,11 +45,17 @@ jobs:
|
||||
docker exec server /usr/local/bin/run.sh
|
||||
|
||||
- name: set up JDK 21
|
||||
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 21
|
||||
|
||||
- name: Enable KVM group perms
|
||||
run: |
|
||||
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
|
||||
sudo udevadm control --reload-rules
|
||||
sudo udevadm trigger --name-match=kvm
|
||||
|
||||
- name: Configure gradle daemon
|
||||
run: |
|
||||
mkdir -p $HOME/.gradle
|
||||
@@ -93,7 +99,7 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: scripts/uploadReport.sh "${{ secrets.LOG_USERNAME }}" "${{ secrets.LOG_PASSWORD }}" ${{github.event.number}} ${{ matrix.server }} "IT" ${{github.event.number}}
|
||||
- name: Archive Espresso results
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
if: ${{ always() }}
|
||||
with:
|
||||
name: Report-${{ matrix.server }}-${{ matrix.api-level }}
|
||||
|
||||
@@ -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: nextcloud/pr-feedback-action@4738cf661995d96df3512409ec17c900a4081d33 # main
|
||||
- uses: nextcloud/pr-feedback-action@4709fa5b3e1821559d4c312ef937b61f1567aa44 # main
|
||||
with:
|
||||
feedback-message: |
|
||||
Hello there,
|
||||
|
||||
+13
-13
@@ -1,5 +1,4 @@
|
||||
# SPDX-FileCopyrightText: 2021-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2023 Andy Scherzinger <[email protected]>
|
||||
# SPDX-License-Identifier: MIT
|
||||
name: "QA"
|
||||
@@ -18,7 +17,7 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
qa:
|
||||
runs-on: ubuntu-latest-max
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check if secrets are available
|
||||
run: echo "ok=${{ secrets.KS_PASS != '' }}" >> "$GITHUB_OUTPUT"
|
||||
@@ -31,11 +30,11 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: set up JDK 21
|
||||
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 25
|
||||
java-version: 21
|
||||
|
||||
- name: Build QA
|
||||
id: build-qa
|
||||
@@ -61,21 +60,21 @@ jobs:
|
||||
./gradlew assembleQaDebug
|
||||
$(find /usr/local/lib/android/sdk/build-tools/*/apksigner | sort | tail -n1) sign --ks-pass pass:"$KS_PASS" --key-pass pass:"$KEY_PASS" --ks-key-alias key0 --ks ".github/workflows/QA_keystore.jks" app/build/outputs/apk/qa/debug/*qa-debug*.apk
|
||||
apk=$(find app/build/outputs/apk/qa/debug -name '*qa-debug*.apk' | head -n1)
|
||||
{
|
||||
echo "apk-path=$apk"
|
||||
echo "apk-name=$(basename "$apk")"
|
||||
echo "apk-size=$(du -h "$apk" | cut -f1)"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
echo "apk-path=$apk" >> "$GITHUB_OUTPUT"
|
||||
echo "apk-name=$(basename "$apk")" >> "$GITHUB_OUTPUT"
|
||||
echo "apk-size=$(du -h "$apk" | cut -f1)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Upload APK
|
||||
id: upload-apk
|
||||
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
|
||||
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f
|
||||
with:
|
||||
path: app/build/outputs/apk/qa/debug/*qa-debug*.apk
|
||||
path: ${{ steps.build-qa.outputs.apk-path }}
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
archive: false
|
||||
|
||||
- name: Create QR Code
|
||||
- name: Create QR code
|
||||
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
|
||||
env:
|
||||
ARTIFACT_URL: ${{ steps.upload-apk.outputs.artifact-url }}
|
||||
@@ -83,8 +82,9 @@ jobs:
|
||||
sudo apt-get -y install qrencode
|
||||
qrencode -s 8 -o qr.png "$ARTIFACT_URL"
|
||||
|
||||
- name: Upload QR
|
||||
- name: Upload QR code
|
||||
id: upload-qr
|
||||
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
|
||||
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f
|
||||
with:
|
||||
path: qr.png
|
||||
@@ -113,4 +113,4 @@ jobs:
|
||||
using your existing install while testing.
|
||||
|
||||
Downloading the file requires a GitHub account, so open this link on the
|
||||
device you want to test on, or transfer the APK to it.
|
||||
device you want to test on, or transfer the APK to it.
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: "Run analysis"
|
||||
uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0
|
||||
uses: ossf/scorecard-action@2d1146689b8cda280b9bc96326124645441f03bc # v2.4.4
|
||||
with:
|
||||
results_file: results.sarif
|
||||
results_format: sarif
|
||||
@@ -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@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
uses: github/codeql-action/upload-sarif@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 21
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
run: scripts/deleteOldComments.sh "test" "Unit" ${{github.event.number}}
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1
|
||||
uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
|
||||
|
||||
- name: Run unit tests with coverage
|
||||
run: ./gradlew jacocoTestGplayDebugUnitTest
|
||||
@@ -49,7 +49,7 @@ jobs:
|
||||
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@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
|
||||
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
flags: unit
|
||||
@@ -58,7 +58,7 @@ jobs:
|
||||
|
||||
- name: Upload jacoco artifacts
|
||||
if: ${{ failure() }}
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: test-results
|
||||
path: app/build/reports/jacoco/jacocoTestGplayDebugUnitTestReport/html/
|
||||
@@ -60,7 +60,6 @@ build
|
||||
/gradle.properties
|
||||
.attach_pid*
|
||||
fastlane/Fastfile
|
||||
fastlane/ruby
|
||||
*.hprof
|
||||
|
||||
# NDK / C++
|
||||
|
||||
@@ -37,14 +37,6 @@ Java, Kotlin, XML, Jetpack Compose are the key technologies used for building th
|
||||
Project-specific skills live in `./.claude/skills/<skill-name>/`. Load a skill when the task matches its trigger.
|
||||
|
||||
- **`android-java-to-kotlin`** (`./.claude/skills/android-java-to-kotlin/SKILL.md`) — Completes a Java-to-Kotlin conversion in this Android app. Use it when finishing a conversion, when the user mentions "java to kotlin", "j2k", "convert java", or "make it idiomatic", or when a freshly IDE-converted `.kt` file needs cleanup. The workflow is two-person: the developer first runs the Android Studio converter (`Code > Convert Java File to Kotlin File`), then the agent drives the idiomatic second pass — fail-fast control flow, function decomposition, `lifecycleScope`/coroutines instead of Java threads, modern Android APIs, and project conventions (SPDX headers, no magic numbers, `@JvmStatic`). The conversion must preserve behaviour, and the agent must write a behaviour-locking test before declaring it done.
|
||||
- **`android-activity-to-navigator-fragment`** (`./.claude/skills/android-activity-to-navigator-fragment/SKILL.md`) — Converts a standalone Activity (typically a drawer destination) into a Fragment hosted by `NavigatorActivity`. Use it when the user mentions "navigator", `NavigatorActivity`, `NavigatorScreen`, or "convert activity to fragment". It covers registering the `NavigatorScreen`, the fragment and its layout, decoupling collaborators from `FileActivity`, rewiring every entry point with `NavigatorActivity.intent(...)`, DI and manifest cleanup, and migrating the screenshot test.
|
||||
- **`android-eventbus-to-workmanager-flow`** (`./.claude/skills/android-eventbus-to-workmanager-flow/SKILL.md`) — Replaces an EventBus event posted by a WorkManager worker with WorkManager observation through a ViewModel `Flow`. Use it when the user mentions "event bus", `EventBusFactory`, `@Subscribe`, "worker progress", or "observe worker". It covers publishing with `setProgress`, a ViewModel keyed by the unique work name, `ViewModelModule` registration, collecting from Kotlin or Java (`collectWhenStarted`) and deleting the event. The live example is `FileDetailFragmentViewModel`.
|
||||
|
||||
### Android Skills
|
||||
|
||||
Agent skills for Android development at https://github.com/android/skills (overview: https://developer.android.com/tools/agents/android-skills). Use them when a task matches their trigger and no project-specific skill above covers it. Install one with the Android CLI (`android skills add <skill-name>`) or read its `SKILL.md` directly from the repository. Project-specific skills and the rules in this file take precedence over the official skills.
|
||||
|
||||
- **`r8-analyzer`** (https://github.com/android/skills/tree/main/performance/r8-analyzer) — Analyzes the R8 configuration and keep rules for redundant, overly broad, or library-subsumed rules. Use it when changing the keep rules in `app/src/main/keepRules/` or the `optimization {}` blocks in `app/build.gradle.kts`.
|
||||
|
||||
## General Guidance
|
||||
|
||||
@@ -103,16 +95,6 @@ Use `StateFlow` and `MutableStateFlow` in ViewModels for state management. Colle
|
||||
|
||||
Uses Dagger 2 for major Android components (`Activity`, `Fragment`, `Service`, `BroadcastReceiver`, `ContentProvider`). Manual constructor injection for other components.
|
||||
|
||||
### Network Clients
|
||||
|
||||
Get `OwnCloudClient` and `NextcloudClient` instances from `ClientRepository` (`com.nextcloud.repository`), never from `ClientFactory`.
|
||||
`ClientFactory` is deprecated and being phased out; do not add new usages of it, and replace it with `ClientRepository` when touching code that still uses it.
|
||||
|
||||
- Inject `ClientRepository` with Dagger (`@Inject lateinit var clientRepository: ClientRepository`); it is bound to `RemoteClientRepository`, which resolves the current user via `UserAccountManager` on every call.
|
||||
- Activities extending `BaseActivity` already expose it via `getClientRepository()`.
|
||||
- Prefer the `suspend` functions `getOwncloudClient()` / `getNextcloudClient()` from a lifecycle-aware scope (`lifecycleScope`, `viewModelScope`); they switch to `Dispatchers.IO` and return `null` on failure, so handle `null` instead of catching exceptions.
|
||||
- Do not construct `RemoteClientRepository` manually.
|
||||
|
||||
### Extension Functions
|
||||
|
||||
The `com.nextcloud.utils.extensions` package contains helper extensions organized by type (e.g., `FileExtensions.kt`, `StringExtensions.kt`, `ViewExtensions.kt`). Create focused extension files rather than putting multiple types in one file.
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
# Autogenerated by fastlane
|
||||
#
|
||||
# Ensure this file is checked in to source control!
|
||||
|
||||
source "https://rubygems.org"
|
||||
|
||||
gem "fastlane"
|
||||
gem "abbrev"
|
||||
gem 'fastlane'
|
||||
|
||||
plugins_path = File.join(File.dirname(__FILE__), 'fastlane', 'Pluginfile')
|
||||
eval_gemfile(plugins_path) if File.exist?(plugins_path)
|
||||
+52
-60
@@ -7,10 +7,10 @@ GEM
|
||||
public_suffix (>= 2.0.2, < 8.0)
|
||||
artifactory (3.0.17)
|
||||
atomos (0.1.3)
|
||||
aws-eventstream (1.4.1)
|
||||
aws-partitions (1.1299.1)
|
||||
aws-sdk-core (3.262.0)
|
||||
aws-eventstream (~> 1, >= 1.4.1)
|
||||
aws-eventstream (1.4.0)
|
||||
aws-partitions (1.1287.0)
|
||||
aws-sdk-core (3.257.0)
|
||||
aws-eventstream (~> 1, >= 1.3.0)
|
||||
aws-partitions (~> 1, >= 1.992.0)
|
||||
aws-sigv4 (~> 1.9)
|
||||
base64
|
||||
@@ -18,11 +18,11 @@ GEM
|
||||
jmespath (~> 1, >= 1.6.1)
|
||||
logger
|
||||
rexml (~> 3.4, >= 3.4.2)
|
||||
aws-sdk-kms (1.137.0)
|
||||
aws-sdk-core (~> 3, >= 3.262.0)
|
||||
aws-sdk-kms (1.132.0)
|
||||
aws-sdk-core (~> 3, >= 3.256.0)
|
||||
aws-sigv4 (~> 1.5)
|
||||
aws-sdk-s3 (1.236.0)
|
||||
aws-sdk-core (~> 3, >= 3.262.0)
|
||||
aws-sdk-s3 (1.232.0)
|
||||
aws-sdk-core (~> 3, >= 3.256.0)
|
||||
aws-sdk-kms (~> 1)
|
||||
aws-sigv4 (~> 1.5)
|
||||
aws-sigv4 (1.12.1)
|
||||
@@ -30,24 +30,24 @@ GEM
|
||||
babosa (1.0.4)
|
||||
base64 (0.3.0)
|
||||
benchmark (0.5.0)
|
||||
bigdecimal (4.1.3)
|
||||
cgi (0.5.2)
|
||||
bigdecimal (3.3.1)
|
||||
cgi (0.4.2)
|
||||
claide (1.1.0)
|
||||
colored (1.2)
|
||||
colored2 (3.1.2)
|
||||
commander (4.6.0)
|
||||
highline (~> 2.0.0)
|
||||
csv (3.3.7)
|
||||
csv (3.3.6)
|
||||
declarative (0.0.20)
|
||||
digest-crc (0.7.0)
|
||||
rake (>= 12.0.0, < 14.0.0)
|
||||
domain_name (0.7.20261007)
|
||||
domain_name (0.6.20260907)
|
||||
dotenv (2.8.1)
|
||||
emoji_regex (3.2.3)
|
||||
erb (6.0.7)
|
||||
excon (1.9.0)
|
||||
faraday (2.15.1)
|
||||
faraday-net_http (>= 2.0, < 3.6)
|
||||
excon (0.112.0)
|
||||
faraday (2.14.4)
|
||||
faraday-net_http (>= 2.0, < 3.5)
|
||||
json
|
||||
logger
|
||||
faraday-cookie_jar (0.0.8)
|
||||
@@ -57,12 +57,11 @@ GEM
|
||||
faraday (>= 1, < 3)
|
||||
faraday-multipart (1.2.0)
|
||||
multipart-post (~> 2.0)
|
||||
faraday-net_http (3.5.0)
|
||||
net-http (~> 0.5)
|
||||
faraday-net_http (2.1.0)
|
||||
faraday-retry (2.4.0)
|
||||
faraday (~> 2.0)
|
||||
fastimage (2.4.3)
|
||||
fastlane (2.241.2)
|
||||
fastimage (2.4.1)
|
||||
fastlane (2.240.1)
|
||||
CFPropertyList (>= 2.3, < 5.0.0)
|
||||
abbrev (~> 0.1)
|
||||
addressable (>= 2.9.0, < 3.0.0)
|
||||
@@ -78,8 +77,7 @@ GEM
|
||||
csv (~> 3.3)
|
||||
dotenv (>= 2.1.1, < 3.0.0)
|
||||
emoji_regex (>= 0.1, < 4.0)
|
||||
erb (>= 4.0, < 7.0)
|
||||
excon (>= 1.0.0, < 2.0.0)
|
||||
excon (>= 0.71.0, < 2.0.0)
|
||||
faraday (~> 2.7)
|
||||
faraday-cookie_jar (~> 0.0.8)
|
||||
faraday-follow_redirects (~> 0.3)
|
||||
@@ -90,7 +88,7 @@ GEM
|
||||
gh_inspector (>= 1.1.2, < 2.0.0)
|
||||
google-apis-androidpublisher_v3 (~> 0.99)
|
||||
google-apis-playcustomapp_v1 (~> 0.1)
|
||||
google-cloud-env (>= 1.6.0, < 2.5.0)
|
||||
google-cloud-env (>= 1.6.0, < 2.4.0)
|
||||
google-cloud-storage (~> 1.31)
|
||||
highline (~> 2.0)
|
||||
irb (>= 1.8)
|
||||
@@ -109,7 +107,7 @@ GEM
|
||||
rubyzip (>= 3.4.0, < 4.0.0)
|
||||
security (~> 0.3)
|
||||
simctl (~> 1.6.3)
|
||||
terminal-notifier (>= 3.1.0, < 4.0.0)
|
||||
terminal-notifier (>= 2.0.0, < 3.0.0)
|
||||
terminal-table (~> 4)
|
||||
tty-screen (>= 0.6.3, < 1.0.0)
|
||||
tty-spinner (>= 0.8.0, < 1.0.0)
|
||||
@@ -117,33 +115,34 @@ GEM
|
||||
xcodeproj (>= 1.13.0, < 2.0.0)
|
||||
xcpretty (~> 0.4.1)
|
||||
xcpretty-travis-formatter (>= 0.0.3, < 2.0.0)
|
||||
fastlane-plugin-huawei_appgallery_connect (1.0.31)
|
||||
cgi
|
||||
fastlane-sirp (1.1.0)
|
||||
gh_inspector (1.1.3)
|
||||
google-apis-androidpublisher_v3 (0.110.0)
|
||||
google-apis-androidpublisher_v3 (0.108.0)
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-apis-core (1.4.0)
|
||||
addressable (~> 2.9)
|
||||
faraday (~> 2.13)
|
||||
faraday-follow_redirects (~> 0.3)
|
||||
googleauth (~> 1.14)
|
||||
mini_mime (~> 1.1)
|
||||
multi_json (~> 1.11)
|
||||
google-apis-core (0.18.0)
|
||||
addressable (~> 2.5, >= 2.5.1)
|
||||
googleauth (~> 1.9)
|
||||
httpclient (>= 2.8.3, < 3.a)
|
||||
mini_mime (~> 1.0)
|
||||
mutex_m
|
||||
representable (~> 3.0)
|
||||
retriable (>= 3.1, < 5.0)
|
||||
retriable (>= 2.0, < 4.a)
|
||||
google-apis-iamcredentials_v1 (0.28.0)
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-apis-playcustomapp_v1 (0.18.0)
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-apis-storage_v1 (0.70.0)
|
||||
google-apis-storage_v1 (0.67.0)
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-cloud-core (1.9.0)
|
||||
google-cloud-env (>= 1.0, < 3.a)
|
||||
google-cloud-errors (~> 1.0)
|
||||
google-cloud-env (2.4.1)
|
||||
google-cloud-env (2.3.1)
|
||||
base64 (~> 0.2)
|
||||
faraday (>= 1.0, < 3.a)
|
||||
google-cloud-errors (1.7.0)
|
||||
google-cloud-storage (1.62.1)
|
||||
google-cloud-storage (1.62.0)
|
||||
addressable (~> 2.8)
|
||||
digest-crc (~> 0.4)
|
||||
google-apis-core (>= 0.18, < 2)
|
||||
@@ -152,8 +151,8 @@ GEM
|
||||
google-cloud-core (~> 1.6)
|
||||
googleauth (~> 1.9)
|
||||
mini_mime (~> 1.0)
|
||||
google-logging-utils (0.2.1)
|
||||
googleauth (1.17.6)
|
||||
google-logging-utils (0.2.0)
|
||||
googleauth (1.17.4)
|
||||
faraday (>= 1.0, < 3.a)
|
||||
google-cloud-env (~> 2.2)
|
||||
google-logging-utils (~> 0.1)
|
||||
@@ -164,7 +163,9 @@ GEM
|
||||
highline (2.0.3)
|
||||
http-cookie (1.1.6)
|
||||
domain_name (~> 0.5)
|
||||
io-console (0.9.5)
|
||||
httpclient (2.9.0)
|
||||
mutex_m
|
||||
io-console (0.9.3)
|
||||
irb (1.18.0)
|
||||
pp (>= 0.6.0)
|
||||
prism (>= 1.3.0)
|
||||
@@ -172,7 +173,7 @@ GEM
|
||||
reline (>= 0.4.2)
|
||||
jmespath (1.6.2)
|
||||
json (2.21.2)
|
||||
jwt (3.3.0)
|
||||
jwt (2.10.3)
|
||||
base64
|
||||
logger (1.7.0)
|
||||
mini_magick (4.13.2)
|
||||
@@ -182,11 +183,6 @@ GEM
|
||||
mutex_m (0.3.0)
|
||||
nanaimo (0.4.0)
|
||||
naturally (2.3.0)
|
||||
net-http (0.10.0)
|
||||
net-protocol (>= 0.3.0)
|
||||
uri (>= 0.11.1)
|
||||
net-protocol (0.4.0)
|
||||
timeout
|
||||
nkf (0.3.0)
|
||||
optparse (0.8.1)
|
||||
os (1.1.4)
|
||||
@@ -194,42 +190,41 @@ GEM
|
||||
plist (3.7.2)
|
||||
pp (0.6.4)
|
||||
prettyprint
|
||||
prettyprint (0.2.1)
|
||||
prettyprint (0.2.0)
|
||||
prism (1.9.0)
|
||||
pstore (0.3.0)
|
||||
public_suffix (7.0.5)
|
||||
pstore (0.2.1)
|
||||
public_suffix (6.0.2)
|
||||
rake (13.4.2)
|
||||
rbs (4.2.0)
|
||||
logger
|
||||
prism (>= 1.6.0)
|
||||
tsort
|
||||
rdoc (8.1.0)
|
||||
rdoc (8.0.0)
|
||||
erb
|
||||
prism (>= 1.6.0)
|
||||
rbs (>= 4.0.0)
|
||||
tsort
|
||||
reline (0.7.0)
|
||||
io-console (~> 0.5)
|
||||
representable (3.3.1)
|
||||
representable (3.2.0)
|
||||
declarative (< 0.1.0)
|
||||
trailblazer-option (>= 0.1.1, < 0.2.0)
|
||||
uber (< 0.2.0)
|
||||
retriable (4.2.0)
|
||||
retriable (3.8.0)
|
||||
rexml (3.4.4)
|
||||
rouge (3.28.0)
|
||||
rubyzip (3.7.0)
|
||||
security (0.4.0)
|
||||
signet (0.22.1)
|
||||
rubyzip (3.6.0)
|
||||
security (0.3.0)
|
||||
signet (0.22.0)
|
||||
addressable (~> 2.8)
|
||||
faraday (>= 0.17.5, < 3.a)
|
||||
jwt (>= 1.5, < 4.0)
|
||||
simctl (1.6.10)
|
||||
CFPropertyList
|
||||
naturally
|
||||
terminal-notifier (3.1.0)
|
||||
terminal-notifier (2.0.0)
|
||||
terminal-table (4.0.0)
|
||||
unicode-display_width (>= 1.1.1, < 4)
|
||||
timeout (0.6.1)
|
||||
trailblazer-option (0.1.2)
|
||||
tsort (0.2.0)
|
||||
tty-cursor (0.7.1)
|
||||
@@ -237,10 +232,7 @@ GEM
|
||||
tty-spinner (0.9.3)
|
||||
tty-cursor (~> 0.7)
|
||||
uber (0.1.0)
|
||||
unicode-display_width (3.3.0)
|
||||
unicode-emoji (~> 4.3)
|
||||
unicode-emoji (4.3.0)
|
||||
uri (1.1.2)
|
||||
unicode-display_width (2.6.0)
|
||||
word_wrap (1.0.0)
|
||||
xcodeproj (1.28.1)
|
||||
CFPropertyList (>= 2.3.3, < 4.0)
|
||||
@@ -260,8 +252,8 @@ PLATFORMS
|
||||
x86_64-linux
|
||||
|
||||
DEPENDENCIES
|
||||
abbrev
|
||||
fastlane
|
||||
fastlane-plugin-huawei_appgallery_connect
|
||||
|
||||
BUNDLED WITH
|
||||
2.5.4
|
||||
@@ -4,7 +4,7 @@
|
||||
-->
|
||||
# [Nextcloud](https://nextcloud.com) Android app :iphone:
|
||||
|
||||
[](https://api.reuse.software/info/github.com/nextcloud/android) [](https://drone.nextcloud.com/nextcloud/android) [](https://github.com/nextcloud/android/releases/latest)
|
||||
[](https://api.reuse.software/info/github.com/nextcloud/android) [](https://drone.nextcloud.com/nextcloud/android) [](https://app.codacy.com/gh/nextcloud/android/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade) [](https://github.com/nextcloud/android/releases/latest)
|
||||
|
||||
[<img src="https://play.google.com/intl/en_us/badges/images/generic/en_badge_web_generic.png"
|
||||
alt="Download from Google Play"
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
[](https://api.reuse.software/info/github.com/nextcloud/android)
|
||||
[](https://drone.nextcloud.com/nextcloud/android)
|
||||
[](https://app.codacy.com/gh/nextcloud/android/dashboard)
|
||||
[](https://github.com/nextcloud/android/releases/latest)
|
||||
|
||||
[<img src="https://play.google.com/intl/en_us/badges/images/generic/en_badge_web_generic.png" alt="تحميل من Google Play" height="80">](https://play.google.com/store/apps/details?id=com.nextcloud.client)
|
||||
|
||||
+40
-24
@@ -13,17 +13,13 @@ import com.github.spotbugs.snom.SpotBugsTask
|
||||
import com.karumi.shot.ShotExtension
|
||||
import org.gradle.internal.jvm.Jvm
|
||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||
import java.io.FileInputStream
|
||||
import java.util.Properties
|
||||
|
||||
val shotTest = System.getenv("SHOT_TEST") == "true"
|
||||
val ciBuild = System.getenv("CI") == "true"
|
||||
val perfAnalysis = project.hasProperty("perfAnalysis")
|
||||
|
||||
val allAbis = listOf("armeabi-v7a", "arm64-v8a", "x86", "x86_64")
|
||||
val localDebugAbis = when (System.getProperty("os.arch")) {
|
||||
"aarch64", "arm64" -> listOf("arm64-v8a")
|
||||
else -> listOf("arm64-v8a", "x86_64")
|
||||
}
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
@@ -72,6 +68,12 @@ configurations.configureEach {
|
||||
}
|
||||
}
|
||||
|
||||
// semantic versioning for version code
|
||||
val versionMajor = 35
|
||||
val versionMinor = 1
|
||||
val versionPatch = 0
|
||||
val versionBuild = 50 // 0-50=Alpha / 51-98=RC / 90-99=stable
|
||||
|
||||
val ndkEnv = buildMap {
|
||||
file("${project.rootDir}/ndk.env").readLines().forEach {
|
||||
val (key, value) = it.split("=")
|
||||
@@ -79,9 +81,14 @@ val ndkEnv = buildMap {
|
||||
}
|
||||
}
|
||||
|
||||
val ncTestServerUsername = providers.gradleProperty("NC_TEST_SERVER_USERNAME").get()
|
||||
val ncTestServerPassword = providers.gradleProperty("NC_TEST_SERVER_PASSWORD").get()
|
||||
val ncTestServerBaseUrl = providers.gradleProperty("NC_TEST_SERVER_BASEURL").get()
|
||||
val configProps = Properties().apply {
|
||||
val file = rootProject.file("gradle.properties")
|
||||
if (file.exists()) load(FileInputStream(file))
|
||||
}
|
||||
|
||||
val ncTestServerUsername = configProps["NC_TEST_SERVER_USERNAME"]
|
||||
val ncTestServerPassword = configProps["NC_TEST_SERVER_PASSWORD"]
|
||||
val ncTestServerBaseUrl = configProps["NC_TEST_SERVER_BASEURL"]
|
||||
|
||||
android {
|
||||
// install this NDK version and CMake to produce smaller APKs. Build will still work if not installed
|
||||
@@ -107,12 +114,12 @@ android {
|
||||
)
|
||||
applicationId = "com.nextcloud.client"
|
||||
minSdk = 28
|
||||
compileSdk = 37
|
||||
targetSdk = 36
|
||||
// mayor.minor.hotfix.increment (for increment: 01-50=Alpha / 51-89=RC / 90-99=stable)
|
||||
// xx .xxx .xx .xx
|
||||
versionCode = 350010050
|
||||
versionName = "35.1.0 Alpha 51"
|
||||
compileSdk = 37
|
||||
|
||||
ndk {
|
||||
abiFilters += listOf("armeabi-v7a", "arm64-v8a", "x86", "x86_64")
|
||||
}
|
||||
|
||||
buildConfigField("boolean", "CI", ciBuild.toString())
|
||||
buildConfigField("boolean", "RUNTIME_PERF_ANALYSIS", perfAnalysis.toString())
|
||||
@@ -121,6 +128,13 @@ android {
|
||||
testInstrumentationRunner = if (shotTest) "com.karumi.shot.ShotTestRunner"
|
||||
else "com.nextcloud.client.TestRunner"
|
||||
|
||||
versionCode = versionMajor * 10000000 + versionMinor * 10000 + versionPatch * 100 + versionBuild
|
||||
versionName = when {
|
||||
versionBuild > 89 -> "${versionMajor}.${versionMinor}.${versionPatch}"
|
||||
versionBuild > 50 -> "${versionMajor}.${versionMinor}.${versionPatch} RC" + (versionBuild - 50)
|
||||
else -> "${versionMajor}.${versionMinor}.${versionPatch} Alpha" + (versionBuild + 1)
|
||||
}
|
||||
|
||||
// adapt structure from Eclipse to Gradle/Android Studio expectations;
|
||||
// see http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Configuring-the-Structure
|
||||
|
||||
@@ -128,21 +142,13 @@ android {
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
optimization {
|
||||
enable = true
|
||||
}
|
||||
buildConfigField("String", "NC_TEST_SERVER_DATA_STRING", "\"\"")
|
||||
ndk {
|
||||
abiFilters += allAbis
|
||||
}
|
||||
}
|
||||
|
||||
debug {
|
||||
enableUnitTestCoverage = project.hasProperty("coverage")
|
||||
enableAndroidTestCoverage = project.hasProperty("coverage")
|
||||
resConfigs("xxxhdpi")
|
||||
ndk {
|
||||
abiFilters += if (ciBuild) allAbis else localDebugAbis
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,6 +199,7 @@ android {
|
||||
|
||||
buildFeatures {
|
||||
buildConfig = true
|
||||
dataBinding = true
|
||||
viewBinding = true
|
||||
aidl = true
|
||||
compose = true
|
||||
@@ -317,7 +324,10 @@ tasks.withType<SpotBugsTask>().configureEach {
|
||||
}
|
||||
}
|
||||
|
||||
// Run the compiler as a separate process
|
||||
tasks.withType<JavaCompile>().configureEach {
|
||||
options.isFork = true
|
||||
|
||||
// Enable Incremental Compilation
|
||||
options.isIncremental = true
|
||||
}
|
||||
@@ -399,7 +409,6 @@ dependencies {
|
||||
|
||||
// region Lifecycle
|
||||
implementation(libs.lifecycle.viewmodel.ktx)
|
||||
implementation(libs.lifecycle.process)
|
||||
implementation(libs.lifecycle.service)
|
||||
implementation(libs.lifecycle.runtime.ktx)
|
||||
// endregion
|
||||
@@ -417,6 +426,7 @@ dependencies {
|
||||
testImplementation(libs.kotlinx.coroutines.test)
|
||||
|
||||
// region other libraries
|
||||
compileOnly(libs.org.jbundle.util.osgi.wrapped.org.apache.http.client)
|
||||
implementation(libs.commons.httpclient.commons.httpclient) // remove after entire switch to lib v2
|
||||
implementation(libs.jackrabbit.webdav) // remove after entire switch to lib v2
|
||||
implementation(libs.constraintlayout)
|
||||
@@ -428,12 +438,14 @@ dependencies {
|
||||
implementation(libs.commons.io)
|
||||
implementation(libs.eventbus)
|
||||
implementation(libs.ez.vcard)
|
||||
implementation(libs.nnio)
|
||||
implementation(libs.bcpkix.jdk18on)
|
||||
implementation(libs.gson)
|
||||
implementation(libs.sectioned.recyclerview)
|
||||
implementation(libs.photoview)
|
||||
implementation(libs.android.gif.drawable)
|
||||
implementation(libs.qrcodescanner) // "com.github.blikoon:QRCodeScanner:0.1.2"
|
||||
implementation(libs.flexbox)
|
||||
implementation(libs.androidsvg)
|
||||
implementation(libs.annotation)
|
||||
implementation(libs.emoji.google)
|
||||
@@ -517,6 +529,10 @@ dependencies {
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
// endregion
|
||||
|
||||
// region Stateless
|
||||
implementation(libs.stateless4j)
|
||||
// endregion
|
||||
|
||||
// region Google Play dependencies, upon each update first test: new registration, receive push
|
||||
add(gplayImplementationConfiguration, libs.bundles.gplay)
|
||||
// endregion
|
||||
|
||||
+10
-10
@@ -53,9 +53,9 @@ complexity:
|
||||
active: false
|
||||
threshold: 10
|
||||
includeStaticDeclarations: false
|
||||
CyclomaticComplexMethod:
|
||||
ComplexMethod:
|
||||
active: true
|
||||
threshold: 15
|
||||
threshold: 10
|
||||
ignoreSingleWhenExpression: false
|
||||
ignoreSimpleWhenEntries: false
|
||||
excludes: ['**/androidTest/**']
|
||||
@@ -67,10 +67,10 @@ complexity:
|
||||
threshold: 600
|
||||
LongMethod:
|
||||
active: true
|
||||
threshold: 120
|
||||
threshold: 60
|
||||
excludes: ['**/androidTest/**']
|
||||
LongParameterList:
|
||||
active: false
|
||||
active: true
|
||||
functionThreshold: 7
|
||||
constructorThreshold: 6
|
||||
ignoreDefaultParameters: false
|
||||
@@ -87,7 +87,7 @@ complexity:
|
||||
excludeStringsWithLessThan5Characters: true
|
||||
ignoreStringsRegex: '$^'
|
||||
TooManyFunctions:
|
||||
active: false
|
||||
active: true
|
||||
thresholdInFiles: 15
|
||||
thresholdInClasses: 15
|
||||
thresholdInInterfaces: 15
|
||||
@@ -158,7 +158,7 @@ exceptions:
|
||||
ThrowingNewInstanceOfSameException:
|
||||
active: false
|
||||
TooGenericExceptionCaught:
|
||||
active: false
|
||||
active: true
|
||||
exceptionNames:
|
||||
- ArrayIndexOutOfBoundsException
|
||||
- Error
|
||||
@@ -170,7 +170,7 @@ exceptions:
|
||||
- Throwable
|
||||
allowedExceptionNameRegex: "^(_|(ignore|expected).*)"
|
||||
TooGenericExceptionThrown:
|
||||
active: false
|
||||
active: true
|
||||
exceptionNames:
|
||||
- Error
|
||||
- Exception
|
||||
@@ -226,7 +226,7 @@ naming:
|
||||
active: true
|
||||
packagePattern: '^[a-z]+(\.[a-z][A-Za-z0-9]*)*$'
|
||||
TopLevelPropertyNaming:
|
||||
active: false
|
||||
active: true
|
||||
constantPattern: '[A-Z][_A-Z0-9]*'
|
||||
propertyPattern: '[A-Za-z][_A-Za-z0-9]*'
|
||||
privatePropertyPattern: '(_)?[A-Za-z][A-Za-z0-9]*'
|
||||
@@ -346,7 +346,7 @@ style:
|
||||
NestedClassesVisibility:
|
||||
active: false
|
||||
NewLineAtEndOfFile:
|
||||
active: false
|
||||
active: true
|
||||
NoTabs:
|
||||
active: false
|
||||
OptionalAbstractKeyword:
|
||||
@@ -362,7 +362,7 @@ style:
|
||||
RedundantVisibilityModifierRule:
|
||||
active: false
|
||||
ReturnCount:
|
||||
active: false
|
||||
active: true
|
||||
max: 2
|
||||
excludedFunctions: [equals]
|
||||
excludeLabeled: false
|
||||
|
||||
+1
-5
@@ -15,6 +15,7 @@
|
||||
</issue>
|
||||
<issue id="InvalidPackage">
|
||||
<ignore path="**/freemarker-2.*.*.jar" />
|
||||
<ignore path="**/nnio-0.2.jar"/>
|
||||
<ignore path="**/bcpkix-jdk15on-1.69.jar" />
|
||||
</issue>
|
||||
|
||||
@@ -90,11 +91,6 @@
|
||||
<ignore path="**/appcompat-1.**/**/lint.jar" />
|
||||
</issue>
|
||||
|
||||
<!-- Lint reads abiFilters as source text and cannot resolve allAbis; local debug builds skip x86 on purpose. -->
|
||||
<issue id="ChromeOsAbiSupport">
|
||||
<ignore path="build.gradle.kts" />
|
||||
</issue>
|
||||
|
||||
<issue id="Aligned16KB">
|
||||
<ignore path="**/arm64-v8a/libmockkjvmtiagent.so" />
|
||||
</issue>
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -37,7 +37,7 @@ import com.owncloud.android.lib.resources.shares.OCShare
|
||||
import com.owncloud.android.lib.resources.shares.ShareType
|
||||
import com.owncloud.android.operations.CreateFolderOperation
|
||||
import com.owncloud.android.ui.activity.FileDisplayActivity
|
||||
import com.owncloud.android.ui.adapter.filelist.item.OCFileListItemViewHolder
|
||||
import com.owncloud.android.ui.adapter.OCFileListItemViewHolder
|
||||
import com.owncloud.android.utils.EspressoIdlingResource
|
||||
import org.hamcrest.Matchers.allOf
|
||||
import org.junit.After
|
||||
|
||||
+19
-32
@@ -8,51 +8,37 @@
|
||||
*/
|
||||
package com.nextcloud.client
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Looper
|
||||
import android.view.View
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import androidx.test.core.app.ActivityScenario
|
||||
import androidx.test.core.app.launchActivity
|
||||
import androidx.test.espresso.Espresso.onView
|
||||
import androidx.test.espresso.assertion.ViewAssertions.matches
|
||||
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
|
||||
import androidx.test.espresso.matcher.ViewMatchers.isRoot
|
||||
import com.nextcloud.client.preferences.SubFolderRule
|
||||
import com.owncloud.android.AbstractIT
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.MediaFolderType
|
||||
import com.owncloud.android.datamodel.SyncedFolder
|
||||
import com.owncloud.android.datamodel.SyncedFolderDisplayItem
|
||||
import com.owncloud.android.ui.activity.SyncedFoldersActivity
|
||||
import com.owncloud.android.ui.dialog.SyncedFolderPreferencesDialogFragment.Companion.newInstance
|
||||
import com.owncloud.android.ui.fragment.autoUpload.AutoUploadFragment
|
||||
import com.owncloud.android.ui.navigation.NavigatorActivity
|
||||
import com.owncloud.android.ui.navigation.NavigatorScreen
|
||||
import com.owncloud.android.utils.ScreenshotTest
|
||||
import org.junit.Test
|
||||
|
||||
class AutoUploadFragmentIT : AbstractIT() {
|
||||
private val testClassName = "com.nextcloud.client.AutoUploadFragmentIT"
|
||||
|
||||
private fun findFragment(sut: NavigatorActivity): AutoUploadFragment =
|
||||
sut.supportFragmentManager.fragments.filterIsInstance<AutoUploadFragment>().firstOrNull()
|
||||
?: throw IllegalStateException("AutoUploadFragment not found in NavigatorActivity!")
|
||||
|
||||
private fun launch(block: (ActivityScenario<NavigatorActivity>) -> Unit) {
|
||||
val intent = NavigatorActivity.intent(targetContext, NavigatorScreen.AutoUpload)
|
||||
ActivityScenario.launch<NavigatorActivity>(intent).use(block)
|
||||
}
|
||||
class SyncedFoldersActivityIT : AbstractIT() {
|
||||
private val testClassName = "com.nextcloud.client.SyncedFoldersActivityIT"
|
||||
|
||||
@Test
|
||||
@ScreenshotTest
|
||||
fun open() {
|
||||
launch { scenario ->
|
||||
launchActivity<SyncedFoldersActivity>().use { scenario ->
|
||||
val screenShotName = createName(testClassName + "_" + "open", "")
|
||||
onView(isRoot()).check(matches(isDisplayed()))
|
||||
|
||||
scenario.onActivity { sut ->
|
||||
val fragment = findFragment(sut)
|
||||
fragment.adapter.clear()
|
||||
val emptyListView = fragment.requireView().findViewById<View>(R.id.empty_list_view)
|
||||
screenshotViaName(emptyListView, screenShotName)
|
||||
sut.adapter.clear()
|
||||
screenshotViaName(sut.binding.emptyList.emptyListView, screenShotName)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,15 +67,15 @@ class AutoUploadFragmentIT : AbstractIT() {
|
||||
SyncedFolder.NOT_SCANNED_YET
|
||||
)
|
||||
|
||||
launch { scenario ->
|
||||
val intent = Intent(targetContext, SyncedFoldersActivity::class.java)
|
||||
launchActivity<SyncedFoldersActivity>(intent).use { scenario ->
|
||||
val screenShotName = createName(testClassName + "_" + "testSyncedFolderDialog", "")
|
||||
onView(isRoot()).check(matches(isDisplayed()))
|
||||
|
||||
scenario.onActivity { sut ->
|
||||
val dialog = newInstance(item, 0) ?: throw IllegalStateException("Dialog could not be created")
|
||||
dialog.show(findFragment(sut).childFragmentManager, "")
|
||||
findFragment(sut).childFragmentManager.executePendingTransactions()
|
||||
screenshot(dialog.requireDialog().window?.decorView, screenShotName)
|
||||
val fragment = newInstance(item, 0)
|
||||
fragment!!.show(sut.supportFragmentManager, "")
|
||||
screenshot(fragment.requireDialog().window?.decorView, screenShotName)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -101,17 +87,18 @@ class AutoUploadFragmentIT : AbstractIT() {
|
||||
Looper.prepare()
|
||||
}
|
||||
|
||||
launch { scenario ->
|
||||
val intent = Intent(targetContext, SyncedFoldersActivity::class.java)
|
||||
|
||||
launchActivity<SyncedFoldersActivity>(intent).use { scenario ->
|
||||
var dialog: AlertDialog? = null
|
||||
scenario.onActivity { sut ->
|
||||
val fragment = findFragment(sut)
|
||||
dialog = fragment.buildPowerCheckDialog()
|
||||
fragment.showPowerCheckDialog()
|
||||
dialog = sut.buildPowerCheckDialog()
|
||||
sut.showPowerCheckDialog()
|
||||
}
|
||||
|
||||
val screenShotName = createName(testClassName + "_" + "showPowerCheckDialog", "")
|
||||
onView(isRoot()).check(matches(isDisplayed()))
|
||||
screenshot(dialog?.window?.decorView, screenShotName)
|
||||
screenshot(dialog!!.window?.decorView, screenShotName)
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-7
@@ -8,7 +8,7 @@
|
||||
*/
|
||||
package com.nextcloud.client
|
||||
|
||||
import androidx.test.core.app.ActivityScenario
|
||||
import androidx.test.core.app.launchActivity
|
||||
import androidx.test.espresso.Espresso.onView
|
||||
import androidx.test.espresso.assertion.ViewAssertions.matches
|
||||
import androidx.test.espresso.contrib.DrawerActions
|
||||
@@ -17,19 +17,17 @@ import androidx.test.espresso.matcher.ViewMatchers.isRoot
|
||||
import androidx.test.espresso.matcher.ViewMatchers.withId
|
||||
import com.owncloud.android.AbstractIT
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.ui.navigation.NavigatorActivity
|
||||
import com.owncloud.android.ui.navigation.NavigatorScreen
|
||||
import com.owncloud.android.ui.activity.UploadListActivity
|
||||
import com.owncloud.android.utils.ScreenshotTest
|
||||
import org.junit.Test
|
||||
|
||||
class UploadListFragmentIT : AbstractIT() {
|
||||
private val testClassName = "com.nextcloud.client.UploadListFragmentIT"
|
||||
class UploadListActivityActivityIT : AbstractIT() {
|
||||
private val testClassName = "com.nextcloud.client.UploadListActivityActivityIT"
|
||||
|
||||
@Test
|
||||
@ScreenshotTest
|
||||
fun openDrawer() {
|
||||
val intent = NavigatorActivity.intent(targetContext, NavigatorScreen.UploadList)
|
||||
ActivityScenario.launch<NavigatorActivity>(intent).use { scenario ->
|
||||
launchActivity<UploadListActivity>().use { scenario ->
|
||||
onView(isRoot()).check(matches(isDisplayed()))
|
||||
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open())
|
||||
|
||||
@@ -16,6 +16,7 @@ import java.util.TreeMap
|
||||
*
|
||||
* The implementation is not thread-safe.
|
||||
*/
|
||||
@Suppress("TooManyFunctions")
|
||||
class MockSharedPreferences : SharedPreferences {
|
||||
|
||||
class MockEditor(val store: MutableMap<String?, Any?>) : SharedPreferences.Editor {
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Daniele Verducci <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.nextcloud.extensions
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import com.nextcloud.utils.extensions.areImageDimensionsSame
|
||||
import com.owncloud.android.lib.resources.files.model.ImageDimension
|
||||
import com.owncloud.android.lib.resources.files.model.RemoteFile
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.io.OutputStream
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import kotlin.io.path.exists
|
||||
|
||||
class RemoteFileExtensionsImageTest {
|
||||
|
||||
private lateinit var tempDir: Path
|
||||
private val remoteFileWithDimensions = RemoteFile().apply {
|
||||
mimeType = "image/jpeg"
|
||||
imageDimension = ImageDimension(IMAGE_WIDTH.toFloat(), IMAGE_HEIGHT.toFloat())
|
||||
}
|
||||
private val remoteFileWithoutDimensions = RemoteFile().apply {
|
||||
mimeType = "image/jpeg"
|
||||
imageDimension = null
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testAreImageDimensionsSameWhenLocalFileIsNotImage_ShouldReturnTrue() {
|
||||
// local not an image
|
||||
assertTrue(
|
||||
"comparing with non-image",
|
||||
remoteFileWithDimensions.areImageDimensionsSame(getPath(TEXT_FILENAME).toString())
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testAreImageDimensionsSame_ShouldReturnTrue() {
|
||||
// same dimensions
|
||||
assertTrue(
|
||||
"comparing with same-size image",
|
||||
remoteFileWithDimensions.areImageDimensionsSame(getPath(IMAGE_FILENAME).toString())
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testAreImageDimensionsSame_ShouldReturnFalse() {
|
||||
// different dimensions
|
||||
val biggerRemoteImage = RemoteFile().apply {
|
||||
mimeType = "image/jpeg"
|
||||
imageDimension = ImageDimension((IMAGE_WIDTH * 2).toFloat(), IMAGE_HEIGHT.toFloat())
|
||||
}
|
||||
assertFalse(
|
||||
"comparing with different-size image",
|
||||
biggerRemoteImage.areImageDimensionsSame(getPath(IMAGE_FILENAME).toString())
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testAreImageDimensionsSameWhenLocalFileHasNoDimensions_ShouldReturnTrue() {
|
||||
// local file with null dimensions
|
||||
assertTrue(
|
||||
"comparing null-dimensions local file with valid remote file",
|
||||
remoteFileWithoutDimensions.areImageDimensionsSame(getPath(TEXT_FILENAME).toString())
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testAreImageDimensionsSameWhenRemoteFileHasNoDimensions_ShouldReturnTrue() {
|
||||
// remote file with null dimensions
|
||||
assertTrue(
|
||||
"comparing with null-dimensions remote file",
|
||||
remoteFileWithoutDimensions.areImageDimensionsSame(getPath(IMAGE_FILENAME).toString())
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testAreImageDimensionsSameWhenBothFilesHaveNoDimensions_ShouldReturnTrue() {
|
||||
// both files with null dimensions
|
||||
assertTrue(
|
||||
"comparing null-dimensions local file with null-dimensions remote file",
|
||||
remoteFileWithoutDimensions.areImageDimensionsSame(getPath(TEXT_FILENAME).toString())
|
||||
)
|
||||
}
|
||||
|
||||
@After
|
||||
fun cleanup() {
|
||||
val tf = File(getPath(TEXT_FILENAME).toUri())
|
||||
val imgf = File(getPath(IMAGE_FILENAME).toUri())
|
||||
tf.delete()
|
||||
imgf.delete()
|
||||
}
|
||||
|
||||
@Before
|
||||
fun setup() {
|
||||
tempDir = Files.createTempDirectory(TMP_DIR)
|
||||
assertTrue("Temp directory should exist", tempDir.exists())
|
||||
|
||||
createImageFile()
|
||||
createTextFile()
|
||||
}
|
||||
|
||||
private fun getPath(filename: String): Path = tempDir.resolve("test_$filename")
|
||||
|
||||
private fun createImageFile() {
|
||||
val bitmap = Bitmap.createBitmap(IMAGE_WIDTH, IMAGE_HEIGHT, Bitmap.Config.ARGB_8888)
|
||||
val imagePath = getPath(IMAGE_FILENAME)
|
||||
|
||||
Files.newOutputStream(imagePath).use { out: OutputStream ->
|
||||
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)
|
||||
}
|
||||
|
||||
assertTrue(imagePath.exists())
|
||||
}
|
||||
|
||||
private fun createTextFile() {
|
||||
val f = File(getPath(TEXT_FILENAME).toUri())
|
||||
f.writeText("Lorem ipsum")
|
||||
}
|
||||
|
||||
companion object {
|
||||
val TMP_DIR = "remoteFileExtensionsTest"
|
||||
val TEXT_FILENAME = "text.txt"
|
||||
val IMAGE_FILENAME = "image.jpg"
|
||||
|
||||
val IMAGE_WIDTH = 123
|
||||
val IMAGE_HEIGHT = 45
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import junit.framework.TestCase.assertFalse
|
||||
import junit.framework.TestCase.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
@Suppress("TooManyFunctions")
|
||||
class StringExtensionTests {
|
||||
@Test
|
||||
fun testIsNotBlankAndEqualsWhenGivenBothStringsAreNull() {
|
||||
|
||||
@@ -22,7 +22,7 @@ import org.junit.Test
|
||||
import java.io.File
|
||||
import kotlin.random.Random
|
||||
|
||||
@Suppress("MagicNumber")
|
||||
@Suppress("TooManyFunctions", "MagicNumber")
|
||||
class FileDeletionTests : AbstractIT() {
|
||||
|
||||
private val createdFilePaths = mutableListOf<String>()
|
||||
|
||||
@@ -18,6 +18,7 @@ fun withSelectedText(expected: String): Matcher<View> = object : TypeSafeMatcher
|
||||
description.appendText("with selected text \"$expected\"")
|
||||
}
|
||||
|
||||
@Suppress("ReturnCount")
|
||||
override fun matchesSafely(view: View): Boolean {
|
||||
if (view !is TextView) return false
|
||||
val text = view.text?.toString() ?: ""
|
||||
|
||||
@@ -27,6 +27,7 @@ class RetryTestRule(val retryCount: Int = defaultRetryValue) : TestRule {
|
||||
|
||||
override fun apply(base: Statement, description: Description): Statement = statement(base, description)
|
||||
|
||||
@Suppress("TooGenericExceptionCaught") // and this exactly what we want here
|
||||
private fun statement(base: Statement, description: Description): Statement {
|
||||
return object : Statement() {
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@ import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
|
||||
import androidx.test.espresso.matcher.ViewMatchers.isRoot
|
||||
import androidx.test.espresso.matcher.ViewMatchers.withId
|
||||
import androidx.test.rule.GrantPermissionRule
|
||||
import com.nextcloud.ui.dialog.account.onlineStatus.SetOnlineStatusBottomSheet
|
||||
import com.owncloud.android.AbstractIT
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.lib.resources.users.Status
|
||||
|
||||
@@ -17,7 +17,6 @@ import androidx.test.espresso.matcher.ViewMatchers.withId
|
||||
import androidx.test.rule.GrantPermissionRule
|
||||
import com.nextcloud.test.Flaky
|
||||
import com.nextcloud.test.GrantTestPermissionRule
|
||||
import com.nextcloud.ui.dialog.account.statusMessage.SetStatusMessageBottomSheet
|
||||
import com.owncloud.android.AbstractIT
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.lib.resources.users.ClearAt
|
||||
|
||||
@@ -18,6 +18,7 @@ import com.owncloud.android.lib.resources.status.OCCapability
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
@Suppress("TooManyFunctions")
|
||||
@SinceServer(majorVersion = 30)
|
||||
class AutoRenameTests : AbstractOnServerIT() {
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import junit.framework.TestCase.assertFalse
|
||||
import junit.framework.TestCase.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
@Suppress("TooManyFunctions")
|
||||
class FileExtensionTest {
|
||||
|
||||
@Test
|
||||
|
||||
@@ -15,6 +15,7 @@ import org.junit.Test
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
|
||||
@Suppress("TooManyFunctions")
|
||||
class FileHelperTest {
|
||||
|
||||
private lateinit var testDirectory: File
|
||||
|
||||
@@ -21,10 +21,8 @@ import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
@Suppress("TooManyFunctions")
|
||||
class FileNameValidatorTests : AbstractOnServerIT() {
|
||||
companion object {
|
||||
private const val MAX_FILENAME_SIZE = 250
|
||||
}
|
||||
|
||||
private var capability: OCCapability = fileDataStorageManager.getCapability(account.name)
|
||||
|
||||
@@ -111,20 +109,6 @@ class FileNameValidatorTests : AbstractOnServerIT() {
|
||||
assertEquals(targetContext.getString(R.string.filename_empty), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testLongFileName() {
|
||||
val filename = "a".repeat(MAX_FILENAME_SIZE)
|
||||
val result = FileNameValidator.checkFileName(filename, capability, targetContext)
|
||||
assertNull(result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testTooLongFileName() {
|
||||
val filename = "a".repeat(MAX_FILENAME_SIZE + 1)
|
||||
val result = FileNameValidator.checkFileName(filename, capability, targetContext)
|
||||
assertEquals(targetContext.getString(R.string.filename_too_long), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testFileAlreadyExists() {
|
||||
val existingFiles = setOf("existingFile")
|
||||
|
||||
@@ -17,7 +17,7 @@ import junit.framework.TestCase.assertEquals
|
||||
import junit.framework.TestCase.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
@Suppress("MagicNumber")
|
||||
@Suppress("MagicNumber", "TooManyFunctions")
|
||||
class OCCapabilityJsonToListTests : AbstractIT() {
|
||||
private var capability: OCCapability = fileDataStorageManager.getCapability(account.name)
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import junit.framework.TestCase.assertFalse
|
||||
import junit.framework.TestCase.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
@Suppress("TooManyFunctions")
|
||||
class SharePermissionManagerTest {
|
||||
|
||||
private fun createShare(sharePermission: Int, isFolder: Boolean = false, attributesJson: String? = null): OCShare =
|
||||
|
||||
@@ -15,8 +15,8 @@ import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.nextcloud.client.database.entity.UploadEntity
|
||||
import com.nextcloud.client.database.entity.toOCUpload
|
||||
import com.nextcloud.client.database.entity.toUploadEntity
|
||||
import com.nextcloud.utils.text.DisplayTextFormatter
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.utils.DisplayUtils
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
@@ -188,7 +188,7 @@ class UploadDateTests {
|
||||
minResolution: Long = DateUtils.MINUTE_IN_MILLIS,
|
||||
showFuture: Boolean = false
|
||||
) {
|
||||
val result = DisplayTextFormatter.formatRelativeDateTime(
|
||||
val result = DisplayUtils.getRelativeDateTimeString(
|
||||
context,
|
||||
time,
|
||||
minResolution,
|
||||
|
||||
@@ -11,6 +11,7 @@ import com.nextcloud.utils.extensions.webDavParentPath
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
@Suppress("TooManyFunctions")
|
||||
class WebDavParentPathTests {
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2023 TSI-mc
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.nmc.android.ui
|
||||
|
||||
import android.view.View
|
||||
import androidx.test.core.app.launchActivity
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.owncloud.android.AbstractIT
|
||||
import com.owncloud.android.R
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class LauncherActivityIT : AbstractIT() {
|
||||
|
||||
@Test
|
||||
fun testSplashScreenWithEmptyTitlesShouldHideTitles() {
|
||||
launchActivity<LauncherActivity>().onActivity { activity ->
|
||||
assertEquals(View.VISIBLE, activity.findViewById<View>(R.id.ivSplash).visibility)
|
||||
assertEquals(View.GONE, activity.findViewById<View>(R.id.splashScreenBold).visibility)
|
||||
assertEquals(View.GONE, activity.findViewById<View>(R.id.splashScreenNormal).visibility)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSplashScreenWithTitlesShouldShowTitles() {
|
||||
launchActivity<LauncherActivity>().onActivity { activity ->
|
||||
activity.setSplashTitles("Example", "Cloud")
|
||||
|
||||
assertEquals(View.VISIBLE, activity.findViewById<View>(R.id.ivSplash).visibility)
|
||||
assertEquals(View.VISIBLE, activity.findViewById<View>(R.id.splashScreenBold).visibility)
|
||||
assertEquals(View.VISIBLE, activity.findViewById<View>(R.id.splashScreenNormal).visibility)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,251 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Daniele Verducci <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
|
||||
package com.owncloud.android
|
||||
|
||||
import com.nextcloud.client.account.UserAccountManager
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl
|
||||
import com.nextcloud.client.database.entity.FileEntity
|
||||
import com.nextcloud.client.network.NetworkModule
|
||||
import com.nextcloud.test.SinceServer
|
||||
import com.nextcloud.utils.e2ee.E2EEActionResolver
|
||||
import com.nextcloud.utils.e2ee.E2EEKeyInspector
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.lib.resources.e2ee.ToggleEncryptionRemoteOperation
|
||||
import com.owncloud.android.lib.resources.status.GetCapabilitiesRemoteOperation
|
||||
import com.owncloud.android.lib.resources.status.NextcloudVersion
|
||||
import com.owncloud.android.operations.CreateFolderOperation
|
||||
import com.owncloud.android.operations.RefreshFolderOperation
|
||||
import com.owncloud.android.operations.common.SyncOperation
|
||||
import com.owncloud.android.operations.e2e.E2EDeletionService
|
||||
import com.owncloud.android.ui.dialog.setupEncryption.CertificateValidator
|
||||
import com.owncloud.android.ui.dialog.setupEncryption.EncryptionKeyGenerator
|
||||
import com.owncloud.android.utils.EncryptionUtils
|
||||
import junit.framework.TestCase.assertEquals
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
@SinceServer(majorVersion = 30)
|
||||
open class EncryptedFoldersIT : AbstractOnServerIT() {
|
||||
companion object {
|
||||
val FOLDER = "/encryptedFolder/"
|
||||
val SUBFOLDER = "encryptedSubfolder/"
|
||||
val KEYWORDS = arrayListOf(
|
||||
"ability",
|
||||
"able",
|
||||
"about",
|
||||
"above",
|
||||
"absent",
|
||||
"absorb",
|
||||
"abstract",
|
||||
"absurd",
|
||||
"abuse",
|
||||
"access",
|
||||
"accident",
|
||||
"account",
|
||||
"accuse"
|
||||
)
|
||||
}
|
||||
|
||||
private var e2eeActionResolver: E2EEActionResolver
|
||||
private var encryptionKeyGenerator: EncryptionKeyGenerator
|
||||
|
||||
init {
|
||||
val accountManager: UserAccountManager = UserAccountManagerImpl.fromContext(targetContext)
|
||||
val inspector = E2EEKeyInspector(
|
||||
targetContext,
|
||||
storageManager,
|
||||
CertificateValidator(),
|
||||
arbitraryDataProvider,
|
||||
accountManager
|
||||
)
|
||||
e2eeActionResolver = E2EEActionResolver(
|
||||
storageManager,
|
||||
arbitraryDataProvider,
|
||||
accountManager,
|
||||
connectivityServiceMock,
|
||||
inspector
|
||||
)
|
||||
encryptionKeyGenerator = EncryptionKeyGenerator(targetContext, user)
|
||||
}
|
||||
|
||||
/**
|
||||
* This test covers both encrypted folder creation and encryption of an existing (empty) folder,
|
||||
* as they are basically the same action (folder creation + encryption), the only difference being
|
||||
* the latter is executed manually by the user later.
|
||||
*/
|
||||
|
||||
@Test
|
||||
fun testCreateEncryptedFolder() {
|
||||
createEncryptedFolder(FOLDER)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testCreateEncryptedSubfolder() {
|
||||
val parent = createEncryptedFolder(FOLDER)
|
||||
createEncryptedSubfolder(SUBFOLDER, parent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testReadEncryptedFolder() {
|
||||
val remotePath = FOLDER
|
||||
val ocFile = createEncryptedFolder(remotePath)
|
||||
val files = listEncryptedFolder(ocFile)
|
||||
assertEquals(files.size, 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testReadEncryptedSubfolder() {
|
||||
val parent = createEncryptedFolder(FOLDER)
|
||||
val subOCFile = createEncryptedSubfolder(SUBFOLDER, parent)
|
||||
val files = listEncryptedFolder(subOCFile)
|
||||
assertEquals(files.size, 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUnencryptFolder() {
|
||||
// Create encrypted folder
|
||||
val ocFile = createEncryptedFolder(FOLDER)
|
||||
assertTrue(ocFile.isFolder && ocFile.isEncrypted)
|
||||
|
||||
// Unencrypt it
|
||||
encryptFolder(ocFile, false)
|
||||
assertFalse(ocFile.isEncrypted)
|
||||
}
|
||||
|
||||
@Before
|
||||
fun encryptionSetup() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_30)
|
||||
|
||||
// Fetch capability
|
||||
val capability = GetCapabilitiesRemoteOperation(null).execute(client).getResultData()
|
||||
storageManager.saveCapabilities(capability)
|
||||
|
||||
// Check if server supports end2end capability
|
||||
assertTrue(capability.endToEndEncryption.isTrue)
|
||||
|
||||
// Delete existing encryption key, if any
|
||||
assertTrue(
|
||||
E2EDeletionService(NetworkModule().clientFactory(targetContext)).deleteKeysAndFiles(user)
|
||||
)
|
||||
|
||||
// Create new encryption key
|
||||
val privateKey: EncryptionKeyGenerator.PrivateKeyResult = runBlocking {
|
||||
encryptionKeyGenerator.generatePrivateKey(KEYWORDS)
|
||||
}
|
||||
|
||||
// Check the key was generated
|
||||
assertTrue(privateKey is EncryptionKeyGenerator.PrivateKeyResult.Success)
|
||||
}
|
||||
|
||||
@After
|
||||
fun encryptionCleanup() {
|
||||
// Delete existing encryption key, if any
|
||||
assertTrue(
|
||||
E2EDeletionService(NetworkModule().clientFactory(targetContext)).deleteKeysAndFiles(user)
|
||||
)
|
||||
}
|
||||
|
||||
private fun createEncryptedFolder(remotePath: String): OCFile {
|
||||
val created = CreateFolderOperation(remotePath, user, targetContext, storageManager).apply {
|
||||
setEncrypt(true)
|
||||
}.execute(client)
|
||||
assertTrue(created.toString(), created.isSuccess)
|
||||
|
||||
val ocFile = storageManager.getFileByRemotePath(remotePath)
|
||||
assertNotNull(ocFile)
|
||||
|
||||
encryptFolder(ocFile!!, true)
|
||||
|
||||
return ocFile
|
||||
}
|
||||
|
||||
fun encryptFolder(ocFile: OCFile, encrypt: Boolean) {
|
||||
val encrypted = ToggleEncryptionRemoteOperation(ocFile.localId, ocFile.remotePath, encrypt)
|
||||
.execute(client)
|
||||
assertTrue(encrypted.toString(), encrypted.isSuccess)
|
||||
|
||||
// The server forbids locking a folder that is no longer encrypted, so metadata is only uploaded when encrypting
|
||||
if (encrypt) {
|
||||
uploadFolderMetadata(ocFile)
|
||||
}
|
||||
|
||||
// Set file encryption state locally
|
||||
ocFile.isEncrypted = encrypt
|
||||
assertTrue(storageManager.saveFile(ocFile))
|
||||
}
|
||||
|
||||
private fun uploadFolderMetadata(ocFile: OCFile) {
|
||||
val publicKey = arbitraryDataProvider.getValue(user, EncryptionUtils.PUBLIC_KEY)
|
||||
val privateKey = arbitraryDataProvider.getValue(user, EncryptionUtils.PRIVATE_KEY)
|
||||
val uploadedMetadata = encryptionKeyGenerator.uploadEncryptedFolderMetadata(
|
||||
ocFile,
|
||||
client,
|
||||
publicKey,
|
||||
privateKey,
|
||||
storageManager,
|
||||
arbitraryDataProvider
|
||||
)
|
||||
assertTrue(uploadedMetadata)
|
||||
}
|
||||
|
||||
fun createEncryptedSubfolder(folderName: String, parent: OCFile): OCFile {
|
||||
// An encrypted subfolder is a normal folder inside an encrypted one
|
||||
assertTrue(parent.isFolder && parent.isEncrypted)
|
||||
|
||||
// Create folder
|
||||
val path = parent.decryptedRemotePath + folderName
|
||||
val syncOp: SyncOperation = CreateFolderOperation(
|
||||
path,
|
||||
user,
|
||||
targetContext,
|
||||
storageManager
|
||||
)
|
||||
val result = syncOp.execute(client)
|
||||
assertTrue(result.toString(), result.isSuccess)
|
||||
|
||||
// Check folder exists
|
||||
val ocFile = storageManager.getFileByRemotePath(path)
|
||||
assertNotNull(ocFile)
|
||||
assertTrue(ocFile!!.isFolder && ocFile.isEncrypted)
|
||||
|
||||
return ocFile
|
||||
}
|
||||
|
||||
private fun listEncryptedFolder(ocFile: OCFile): List<FileEntity> {
|
||||
assertNotNull(ocFile)
|
||||
val parent = storageManager.getFileById(ocFile.parentId)
|
||||
assertNotNull(parent)
|
||||
|
||||
// Refresh folder
|
||||
val refreshResult = RefreshFolderOperation(
|
||||
parent,
|
||||
System.currentTimeMillis(),
|
||||
false,
|
||||
false,
|
||||
storageManager,
|
||||
user,
|
||||
targetContext
|
||||
).execute(client)
|
||||
assertTrue(refreshResult.toString(), refreshResult.isSuccess)
|
||||
|
||||
// Check folder metadata
|
||||
runBlocking {
|
||||
assertTrue(e2eeActionResolver.checkFolderMetadataKey(ocFile))
|
||||
}
|
||||
|
||||
// Open folder
|
||||
return runBlocking {
|
||||
storageManager.fileDao.getFolderContentSuspended(ocFile.fileId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2018 Tobias Kaminsky <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.owncloud.android;
|
||||
|
||||
import com.owncloud.android.datamodel.OCFile;
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
|
||||
import com.owncloud.android.operations.CreateFolderOperation;
|
||||
import com.owncloud.android.operations.RemoveFileOperation;
|
||||
import com.owncloud.android.operations.RenameFileOperation;
|
||||
import com.owncloud.android.operations.SynchronizeFolderOperation;
|
||||
import com.owncloud.android.operations.common.SyncOperation;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
/**
|
||||
* Tests related to file operations.
|
||||
*/
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
public class FileIT extends AbstractOnServerIT {
|
||||
|
||||
@Test
|
||||
public void testCreateFolder() {
|
||||
String path = "/testFolder/";
|
||||
|
||||
// folder does not exist yet
|
||||
assertNull(getStorageManager().getFileByPath(path));
|
||||
|
||||
SyncOperation syncOp = new CreateFolderOperation(path, user, targetContext, getStorageManager());
|
||||
RemoteOperationResult result = syncOp.execute(client);
|
||||
|
||||
assertTrue(result.toString(), result.isSuccess());
|
||||
|
||||
// folder exists
|
||||
OCFile file = getStorageManager().getFileByPath(path);
|
||||
assertTrue(file.isFolder());
|
||||
|
||||
// cleanup
|
||||
assertTrue(new RemoveFileOperation(file, false, user, false, targetContext, getStorageManager())
|
||||
.execute(client)
|
||||
.isSuccess());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateNonExistingSubFolder() {
|
||||
String path = "/subFolder/1/2/3/4/5/";
|
||||
// folder does not exist yet
|
||||
assertNull(getStorageManager().getFileByPath(path));
|
||||
|
||||
SyncOperation syncOp = new CreateFolderOperation(path, user, targetContext, getStorageManager());
|
||||
RemoteOperationResult result = syncOp.execute(client);
|
||||
assertTrue(result.toString(), result.isSuccess());
|
||||
|
||||
// folder exists
|
||||
OCFile file = getStorageManager().getFileByPath(path);
|
||||
assertTrue(file.isFolder());
|
||||
|
||||
// cleanup
|
||||
new RemoveFileOperation(file,
|
||||
false,
|
||||
user,
|
||||
false,
|
||||
targetContext,
|
||||
getStorageManager())
|
||||
.execute(client);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemoteIdNull() {
|
||||
getStorageManager().deleteAllFiles();
|
||||
assertEquals(0, getStorageManager().getAllFiles().size());
|
||||
|
||||
OCFile test = new OCFile("/123.txt");
|
||||
getStorageManager().saveFile(test);
|
||||
assertEquals(1, getStorageManager().getAllFiles().size());
|
||||
|
||||
getStorageManager().deleteAllFiles();
|
||||
assertEquals(0, getStorageManager().getAllFiles().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRenameFolder() throws IOException {
|
||||
String folderPath = "/testRenameFolder/";
|
||||
|
||||
// create folder
|
||||
createFolder(folderPath);
|
||||
|
||||
// upload file inside it
|
||||
uploadFile(getDummyFile("nonEmpty.txt"), folderPath + "text.txt");
|
||||
|
||||
// sync folder
|
||||
assertTrue(new SynchronizeFolderOperation(targetContext,
|
||||
folderPath,
|
||||
user,
|
||||
fileDataStorageManager,
|
||||
false,
|
||||
false)
|
||||
.execute(targetContext)
|
||||
.isSuccess());
|
||||
|
||||
// check if file exists
|
||||
String storagePath1 = fileDataStorageManager.getFileByDecryptedRemotePath(folderPath).getStoragePath();
|
||||
assertTrue(new File(storagePath1).exists());
|
||||
|
||||
String storagePath2 = fileDataStorageManager
|
||||
.getFileByDecryptedRemotePath(folderPath + "text.txt")
|
||||
.getStoragePath();
|
||||
assertTrue(new File(storagePath2).exists());
|
||||
|
||||
shortSleep();
|
||||
|
||||
// Rename
|
||||
assertTrue(
|
||||
new RenameFileOperation(folderPath, "test123", fileDataStorageManager)
|
||||
.execute(targetContext)
|
||||
.isSuccess()
|
||||
);
|
||||
|
||||
// after rename check new location
|
||||
assertTrue(
|
||||
new File(fileDataStorageManager.getFileByDecryptedRemotePath("/test123/").getStoragePath())
|
||||
.exists()
|
||||
);
|
||||
assertTrue(
|
||||
new File(fileDataStorageManager.getFileByDecryptedRemotePath("/test123/text.txt").getStoragePath())
|
||||
.exists()
|
||||
);
|
||||
|
||||
// old files do no exist
|
||||
assertNull(fileDataStorageManager.getFileByDecryptedRemotePath(folderPath));
|
||||
assertNull(fileDataStorageManager.getFileByDecryptedRemotePath(folderPath + "text.txt"));
|
||||
|
||||
// local files also do not exist
|
||||
assertFalse(new File(storagePath1).exists());
|
||||
assertFalse(new File(storagePath2).exists());
|
||||
}
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2018 Tobias Kaminsky <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.owncloud.android
|
||||
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.operations.CreateFolderOperation
|
||||
import com.owncloud.android.operations.RenameFileOperation
|
||||
import com.owncloud.android.operations.SynchronizeFolderOperation
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Tests related to file operations.
|
||||
*
|
||||
* Every test starts with an empty server and an empty local database, and [AbstractOnServerIT.after] wipes both again
|
||||
* afterwards, so no test needs to clean up after itself.
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class FileIT : AbstractOnServerIT() {
|
||||
|
||||
@Test
|
||||
fun testCreateFolder() {
|
||||
val path = "/testFolder/"
|
||||
assertNull(storageManager.getFileByDecryptedRemotePath(path))
|
||||
createFolderOrFail(path)
|
||||
assertTrue(localFile(path).isFolder)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testCreateNonExistingSubFolder() {
|
||||
val path = "/subFolder/1/2/3/4/5/"
|
||||
assertNull(storageManager.getFileByDecryptedRemotePath(path))
|
||||
createFolderOrFail(path)
|
||||
assertTrue(localFile(path).isFolder)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testRemoteIdNull() {
|
||||
storageManager.deleteAllFiles()
|
||||
assertEquals(0, storageManager.allFiles.size)
|
||||
|
||||
storageManager.saveFile(OCFile("/123.txt"))
|
||||
assertEquals(1, storageManager.allFiles.size)
|
||||
|
||||
storageManager.deleteAllFiles()
|
||||
assertEquals(0, storageManager.allFiles.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testRenameFolder() {
|
||||
val folderPath = "/testRenameFolder/"
|
||||
val filePath = folderPath + UPLOADED_FILE_NAME
|
||||
val renamedFolderPath = "/$NEW_FOLDER_NAME/"
|
||||
val renamedFilePath = renamedFolderPath + UPLOADED_FILE_NAME
|
||||
|
||||
// the upload creates the parent folder on the server and in the local database
|
||||
uploadFile(getDummyFile(DUMMY_FILE_NAME), filePath)
|
||||
synchronizeFolder(folderPath)
|
||||
|
||||
val folderCopy = localCopyOf(folderPath)
|
||||
val fileCopy = localCopyOf(filePath)
|
||||
assertTrue("$folderPath was not downloaded", folderCopy.exists())
|
||||
assertTrue("$filePath was not downloaded", fileCopy.exists())
|
||||
|
||||
val result = RenameFileOperation(folderPath, NEW_FOLDER_NAME, storageManager).execute(client)
|
||||
assertTrue("Rename of $folderPath failed: ${result.logMessage}", result.isSuccess)
|
||||
|
||||
assertTrue("$renamedFolderPath has no local copy", localCopyOf(renamedFolderPath).exists())
|
||||
assertTrue("$renamedFilePath has no local copy", localCopyOf(renamedFilePath).exists())
|
||||
|
||||
assertNull(storageManager.getFileByDecryptedRemotePath(folderPath))
|
||||
assertNull(storageManager.getFileByDecryptedRemotePath(filePath))
|
||||
|
||||
assertFalse("$folderPath was not moved locally", folderCopy.exists())
|
||||
assertFalse("$filePath was not moved locally", fileCopy.exists())
|
||||
}
|
||||
|
||||
private fun createFolderOrFail(remotePath: String) {
|
||||
val result = CreateFolderOperation(remotePath, user, targetContext, storageManager).execute(client)
|
||||
assertTrue("Creation of $remotePath failed: ${result.logMessage}", result.isSuccess)
|
||||
}
|
||||
|
||||
private fun synchronizeFolder(remotePath: String) {
|
||||
val result = SynchronizeFolderOperation(
|
||||
targetContext,
|
||||
remotePath,
|
||||
user,
|
||||
storageManager,
|
||||
false,
|
||||
false
|
||||
).execute(client)
|
||||
|
||||
assertTrue("Sync of $remotePath failed: ${result.logMessage}", result.isSuccess)
|
||||
}
|
||||
|
||||
private fun localFile(remotePath: String): OCFile {
|
||||
val file = storageManager.getFileByDecryptedRemotePath(remotePath)
|
||||
assertNotNull("$remotePath is missing from the local database", file)
|
||||
return file!!
|
||||
}
|
||||
|
||||
private fun localCopyOf(remotePath: String): File {
|
||||
val storagePath = localFile(remotePath).storagePath
|
||||
assertFalse("$remotePath has no storage path", storagePath.isNullOrEmpty())
|
||||
return File(storagePath)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val DUMMY_FILE_NAME = "nonEmpty.txt"
|
||||
private const val UPLOADED_FILE_NAME = "text.txt"
|
||||
private const val NEW_FOLDER_NAME = "test123"
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@
|
||||
package com.owncloud.android
|
||||
|
||||
import android.Manifest
|
||||
import androidx.test.core.app.ActivityScenario
|
||||
import androidx.test.core.app.launchActivity
|
||||
import androidx.test.espresso.Espresso
|
||||
import androidx.test.espresso.Espresso.onView
|
||||
@@ -23,8 +22,7 @@ import androidx.test.rule.GrantPermissionRule
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.ui.activity.FileDisplayActivity
|
||||
import com.owncloud.android.ui.activity.SettingsActivity
|
||||
import com.owncloud.android.ui.navigation.NavigatorActivity
|
||||
import com.owncloud.android.ui.navigation.NavigatorScreen
|
||||
import com.owncloud.android.ui.activity.SyncedFoldersActivity
|
||||
import com.owncloud.android.utils.ScreenshotTest
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.BeforeClass
|
||||
@@ -105,8 +103,7 @@ class ScreenshotsIT : AbstractIT() {
|
||||
@Test
|
||||
@ScreenshotTest
|
||||
fun autoUploadScreenshot() {
|
||||
val intent = NavigatorActivity.intent(targetContext, NavigatorScreen.AutoUpload)
|
||||
ActivityScenario.launch<NavigatorActivity>(intent).use {
|
||||
launchActivity<SyncedFoldersActivity>().use {
|
||||
onView(isRoot()).check(matches(isDisplayed()))
|
||||
Screengrab.screenshot("05_autoUpload")
|
||||
assertTrue(true)
|
||||
|
||||
@@ -0,0 +1,438 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2020 Tobias Kaminsky <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2020 Chris Narkiewicz <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.owncloud.android;
|
||||
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl;
|
||||
import com.nextcloud.utils.PowerManagementFactory;
|
||||
import com.nextcloud.client.device.PowerManagementService;
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker;
|
||||
import com.nextcloud.client.network.ConnectivityManagerFactory;
|
||||
import com.nextcloud.client.network.ConnectivityService;
|
||||
import com.nextcloud.test.SinceServer;
|
||||
import com.owncloud.android.datamodel.OCFile;
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager;
|
||||
import com.owncloud.android.db.OCUpload;
|
||||
import com.owncloud.android.files.services.NameCollisionPolicy;
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils;
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
|
||||
import com.owncloud.android.lib.resources.files.model.GeoLocation;
|
||||
import com.owncloud.android.lib.resources.files.model.ImageDimension;
|
||||
import com.owncloud.android.lib.resources.status.NextcloudVersion;
|
||||
import com.owncloud.android.operations.RefreshFolderOperation;
|
||||
import com.owncloud.android.operations.RemoveFileOperation;
|
||||
import com.owncloud.android.operations.UploadFileOperation;
|
||||
import com.owncloud.android.utils.FileStorageUtils;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static junit.framework.TestCase.assertFalse;
|
||||
import static junit.framework.TestCase.assertNotNull;
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
|
||||
/**
|
||||
* Tests related to file uploads.
|
||||
*/
|
||||
public class UploadIT extends AbstractOnServerIT {
|
||||
private static final String FOLDER = "/testUpload/";
|
||||
|
||||
private UploadsStorageManager uploadsStorageManager =
|
||||
new UploadsStorageManager(UserAccountManagerImpl.fromContext(targetContext),
|
||||
targetContext.getContentResolver());
|
||||
|
||||
private final PowerManagementService powerManagementServiceMock = PowerManagementFactory.getMock();
|
||||
|
||||
@Before
|
||||
public void before() throws IOException {
|
||||
// make sure that every file is available, even after tests that remove source file
|
||||
createDummyFiles();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEmptyUpload() {
|
||||
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
|
||||
FOLDER + "empty.txt",
|
||||
account.name);
|
||||
|
||||
uploadOCUpload(ocUpload);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNonEmptyUpload() {
|
||||
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
|
||||
FOLDER + "nonEmpty.txt",
|
||||
account.name);
|
||||
|
||||
uploadOCUpload(ocUpload);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUploadWithCopy() {
|
||||
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
|
||||
FOLDER + "nonEmpty.txt",
|
||||
account.name);
|
||||
|
||||
uploadOCUpload(ocUpload, FileUploadWorker.LOCAL_BEHAVIOUR_COPY);
|
||||
|
||||
File originalFile = new File(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt");
|
||||
OCFile uploadedFile = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt");
|
||||
|
||||
assertTrue(originalFile.exists());
|
||||
assertTrue(new File(uploadedFile.getStoragePath()).exists());
|
||||
verifyStoragePath(uploadedFile);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUploadWithMove() {
|
||||
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
|
||||
FOLDER + "nonEmpty.txt",
|
||||
account.name);
|
||||
|
||||
uploadOCUpload(ocUpload, FileUploadWorker.LOCAL_BEHAVIOUR_MOVE);
|
||||
|
||||
File originalFile = new File(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt");
|
||||
OCFile uploadedFile = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt");
|
||||
|
||||
assertFalse(originalFile.exists());
|
||||
assertTrue(new File(uploadedFile.getStoragePath()).exists());
|
||||
verifyStoragePath(uploadedFile);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUploadWithForget() {
|
||||
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
|
||||
FOLDER + "nonEmpty.txt",
|
||||
account.name);
|
||||
|
||||
uploadOCUpload(ocUpload, FileUploadWorker.LOCAL_BEHAVIOUR_FORGET);
|
||||
|
||||
File originalFile = new File(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt");
|
||||
OCFile uploadedFile = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt");
|
||||
|
||||
assertTrue(originalFile.exists());
|
||||
assertFalse(new File(uploadedFile.getStoragePath()).exists());
|
||||
assertTrue(uploadedFile.getStoragePath().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUploadWithDelete() {
|
||||
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
|
||||
FOLDER + "nonEmpty.txt",
|
||||
account.name);
|
||||
|
||||
uploadOCUpload(ocUpload, FileUploadWorker.LOCAL_BEHAVIOUR_DELETE);
|
||||
|
||||
File originalFile = new File(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt");
|
||||
OCFile uploadedFile = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt");
|
||||
|
||||
assertFalse(originalFile.exists());
|
||||
assertFalse(new File(uploadedFile.getStoragePath()).exists());
|
||||
assertTrue(uploadedFile.getStoragePath().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testChunkedUpload() {
|
||||
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/chunkedFile.txt",
|
||||
FOLDER + "chunkedFile.txt", account.name);
|
||||
|
||||
uploadOCUpload(ocUpload);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUploadInNonExistingFolder() {
|
||||
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
|
||||
FOLDER + "2/3/4/1.txt", account.name);
|
||||
|
||||
uploadOCUpload(ocUpload);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUploadOnChargingOnlyButNotCharging() {
|
||||
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
|
||||
FOLDER + "notCharging.txt", account.name);
|
||||
ocUpload.setWhileChargingOnly(true);
|
||||
|
||||
UploadFileOperation newUpload = new UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
user,
|
||||
null,
|
||||
ocUpload,
|
||||
NameCollisionPolicy.DEFAULT,
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
true,
|
||||
getStorageManager()
|
||||
);
|
||||
newUpload.setRemoteFolderToBeCreated();
|
||||
newUpload.addRenameUploadListener(() -> {
|
||||
// dummy
|
||||
});
|
||||
|
||||
RemoteOperationResult result = newUpload.execute(client);
|
||||
assertFalse(result.toString(), result.isSuccess());
|
||||
assertEquals(RemoteOperationResult.ResultCode.DELAYED_FOR_CHARGING, result.getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUploadOnChargingOnlyAndCharging() {
|
||||
final var powerManagementServiceMock = PowerManagementFactory.getMockCharging();
|
||||
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
|
||||
FOLDER + "charging.txt", account.name);
|
||||
ocUpload.setWhileChargingOnly(true);
|
||||
|
||||
UploadFileOperation newUpload = new UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
user,
|
||||
null,
|
||||
ocUpload,
|
||||
NameCollisionPolicy.DEFAULT,
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
true,
|
||||
getStorageManager()
|
||||
);
|
||||
newUpload.setRemoteFolderToBeCreated();
|
||||
newUpload.addRenameUploadListener(() -> {
|
||||
// dummy
|
||||
});
|
||||
|
||||
RemoteOperationResult result = newUpload.execute(client);
|
||||
assertTrue(result.toString(), result.isSuccess());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUploadOnWifiOnlyButNoWifi() {
|
||||
ConnectivityService connectivityServiceMock = ConnectivityManagerFactory.INSTANCE.getWifi();
|
||||
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
|
||||
FOLDER + "noWifi.txt", account.name);
|
||||
ocUpload.setUseWifiOnly(true);
|
||||
|
||||
UploadFileOperation newUpload = new UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
user,
|
||||
null,
|
||||
ocUpload,
|
||||
NameCollisionPolicy.DEFAULT,
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
true,
|
||||
false,
|
||||
getStorageManager()
|
||||
);
|
||||
newUpload.setRemoteFolderToBeCreated();
|
||||
newUpload.addRenameUploadListener(() -> {
|
||||
// dummy
|
||||
});
|
||||
|
||||
RemoteOperationResult result = newUpload.execute(client);
|
||||
assertFalse(result.toString(), result.isSuccess());
|
||||
assertEquals(RemoteOperationResult.ResultCode.DELAYED_FOR_WIFI, result.getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUploadOnWifiOnlyAndWifi() {
|
||||
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
|
||||
FOLDER + "wifi.txt", account.name);
|
||||
ocUpload.setWhileChargingOnly(true);
|
||||
|
||||
UploadFileOperation newUpload = new UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
user,
|
||||
null,
|
||||
ocUpload,
|
||||
NameCollisionPolicy.DEFAULT,
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
true,
|
||||
false,
|
||||
getStorageManager()
|
||||
);
|
||||
newUpload.setRemoteFolderToBeCreated();
|
||||
newUpload.addRenameUploadListener(() -> {
|
||||
// dummy
|
||||
});
|
||||
|
||||
RemoteOperationResult result = newUpload.execute(client);
|
||||
assertTrue(result.toString(), result.isSuccess());
|
||||
|
||||
// cleanup
|
||||
new RemoveFileOperation(getStorageManager().getFileByDecryptedRemotePath(FOLDER),
|
||||
false,
|
||||
user,
|
||||
false,
|
||||
targetContext,
|
||||
getStorageManager())
|
||||
.execute(client);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUploadOnWifiOnlyButMeteredWifi() {
|
||||
ConnectivityService connectivityServiceMock = ConnectivityManagerFactory.INSTANCE.getMetered();
|
||||
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
|
||||
FOLDER + "noWifi.txt",
|
||||
account.name);
|
||||
ocUpload.setUseWifiOnly(true);
|
||||
|
||||
UploadFileOperation newUpload = new UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
user,
|
||||
null,
|
||||
ocUpload,
|
||||
NameCollisionPolicy.DEFAULT,
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
true,
|
||||
false,
|
||||
getStorageManager()
|
||||
);
|
||||
newUpload.setRemoteFolderToBeCreated();
|
||||
newUpload.addRenameUploadListener(() -> {
|
||||
// dummy
|
||||
});
|
||||
|
||||
RemoteOperationResult result = newUpload.execute(client);
|
||||
assertFalse(result.toString(), result.isSuccess());
|
||||
assertEquals(RemoteOperationResult.ResultCode.DELAYED_FOR_WIFI, result.getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SinceServer(majorVersion = 27)
|
||||
public void testCreationAndUploadTimestamp() throws IOException, AccountUtils.AccountNotFoundException {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_27);
|
||||
|
||||
File file = getDummyFile("empty.txt");
|
||||
String remotePath = "/testFile.txt";
|
||||
OCUpload ocUpload = new OCUpload(file.getAbsolutePath(), remotePath, account.name);
|
||||
|
||||
assertTrue(
|
||||
new UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
user,
|
||||
null,
|
||||
ocUpload,
|
||||
NameCollisionPolicy.DEFAULT,
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
false,
|
||||
getStorageManager()
|
||||
)
|
||||
.setRemoteFolderToBeCreated()
|
||||
.execute(client)
|
||||
.isSuccess()
|
||||
);
|
||||
|
||||
long creationTimestamp = Files.readAttributes(file.toPath(), BasicFileAttributes.class)
|
||||
.creationTime()
|
||||
.to(TimeUnit.SECONDS);
|
||||
|
||||
long uploadTimestamp = System.currentTimeMillis() / 1000;
|
||||
|
||||
// RefreshFolderOperation
|
||||
assertTrue(new RefreshFolderOperation(getStorageManager().getFileByDecryptedRemotePath("/"),
|
||||
System.currentTimeMillis() / 1000,
|
||||
false,
|
||||
false,
|
||||
getStorageManager(),
|
||||
user,
|
||||
targetContext).execute(client).isSuccess());
|
||||
|
||||
List<OCFile> files = getStorageManager().getFolderContent(getStorageManager().getFileByDecryptedRemotePath("/"),
|
||||
false);
|
||||
|
||||
OCFile ocFile = files.get(0);
|
||||
|
||||
assertEquals(remotePath, ocFile.getRemotePath());
|
||||
assertEquals(creationTimestamp, ocFile.getCreationTimestamp());
|
||||
assertTrue(uploadTimestamp - 10 < ocFile.getUploadTimestamp() &&
|
||||
uploadTimestamp + 10 > ocFile.getUploadTimestamp());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SinceServer(majorVersion = 27)
|
||||
public void testMetadata() throws IOException, AccountUtils.AccountNotFoundException {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_27);
|
||||
|
||||
File file = getFile("gps.jpg");
|
||||
String remotePath = "/metadata.jpg";
|
||||
OCUpload ocUpload = new OCUpload(file.getAbsolutePath(), remotePath, account.name);
|
||||
|
||||
assertTrue(
|
||||
new UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
user,
|
||||
null,
|
||||
ocUpload,
|
||||
NameCollisionPolicy.DEFAULT,
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
false,
|
||||
false,
|
||||
getStorageManager()
|
||||
)
|
||||
.setRemoteFolderToBeCreated()
|
||||
.execute(client)
|
||||
.isSuccess()
|
||||
);
|
||||
|
||||
// RefreshFolderOperation
|
||||
assertTrue(new RefreshFolderOperation(getStorageManager().getFileByDecryptedRemotePath("/"),
|
||||
System.currentTimeMillis() / 1000,
|
||||
false,
|
||||
false,
|
||||
getStorageManager(),
|
||||
user,
|
||||
targetContext).execute(client).isSuccess());
|
||||
|
||||
List<OCFile> files = getStorageManager().getFolderContent(getStorageManager().getFileByDecryptedRemotePath("/"),
|
||||
false);
|
||||
|
||||
OCFile ocFile = null;
|
||||
for (OCFile f : files) {
|
||||
if ("metadata.jpg".equals(f.getFileName())) {
|
||||
ocFile = f;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
assertNotNull(ocFile);
|
||||
assertEquals(remotePath, ocFile.getRemotePath());
|
||||
assertEquals(new GeoLocation(64, -46), ocFile.getGeoLocation());
|
||||
assertEquals(new ImageDimension(300f, 200f), ocFile.getImageDimension());
|
||||
}
|
||||
|
||||
private void verifyStoragePath(OCFile file) {
|
||||
assertEquals(FileStorageUtils.getSavePath(account.name) + FOLDER + file.getDecryptedFileName(),
|
||||
file.getStoragePath());
|
||||
}
|
||||
}
|
||||
@@ -1,298 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2020 Tobias Kaminsky <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2020 Chris Narkiewicz <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
|
||||
package com.owncloud.android
|
||||
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl
|
||||
import com.nextcloud.client.device.PowerManagementService
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker
|
||||
import com.nextcloud.client.network.ConnectivityManagerFactory
|
||||
import com.nextcloud.client.network.ConnectivityService
|
||||
import com.nextcloud.test.SinceServer
|
||||
import com.nextcloud.utils.PowerManagementFactory
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager
|
||||
import com.owncloud.android.db.OCUpload
|
||||
import com.owncloud.android.files.services.NameCollisionPolicy
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode
|
||||
import com.owncloud.android.lib.resources.files.model.GeoLocation
|
||||
import com.owncloud.android.lib.resources.files.model.ImageDimension
|
||||
import com.owncloud.android.lib.resources.status.NextcloudVersion
|
||||
import com.owncloud.android.operations.RefreshFolderOperation
|
||||
import com.owncloud.android.operations.RemoveFileOperation
|
||||
import com.owncloud.android.operations.UploadFileOperation
|
||||
import com.owncloud.android.utils.FileStorageUtils
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.attribute.BasicFileAttributes
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.math.abs
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
class UploadIT : AbstractOnServerIT() {
|
||||
private val uploadsStorageManager = UploadsStorageManager(
|
||||
UserAccountManagerImpl.fromContext(targetContext),
|
||||
targetContext.contentResolver
|
||||
)
|
||||
|
||||
private val powerManagementServiceMock = PowerManagementFactory.mock
|
||||
|
||||
@Before
|
||||
fun before() {
|
||||
createDummyFiles()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testEmptyUpload() {
|
||||
uploadOCUpload(ocUpload(EMPTY_FILE, "$FOLDER$EMPTY_FILE"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testNonEmptyUpload() {
|
||||
uploadOCUpload(ocUpload(NON_EMPTY_FILE, "$FOLDER$NON_EMPTY_FILE"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUploadWithCopy() {
|
||||
uploadOCUpload(nonEmptyUpload(), FileUploadWorker.LOCAL_BEHAVIOUR_COPY)
|
||||
|
||||
val uploadedFile = uploadedNonEmptyFile()
|
||||
assertTrue(temporalFile(NON_EMPTY_FILE).exists())
|
||||
assertTrue(File(uploadedFile.storagePath).exists())
|
||||
verifyStoragePath(uploadedFile)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUploadWithMove() {
|
||||
uploadOCUpload(nonEmptyUpload(), FileUploadWorker.LOCAL_BEHAVIOUR_MOVE)
|
||||
|
||||
val uploadedFile = uploadedNonEmptyFile()
|
||||
assertFalse(temporalFile(NON_EMPTY_FILE).exists())
|
||||
assertTrue(File(uploadedFile.storagePath).exists())
|
||||
verifyStoragePath(uploadedFile)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUploadWithForget() {
|
||||
uploadOCUpload(nonEmptyUpload(), FileUploadWorker.LOCAL_BEHAVIOUR_FORGET)
|
||||
|
||||
val uploadedFile = uploadedNonEmptyFile()
|
||||
assertTrue(temporalFile(NON_EMPTY_FILE).exists())
|
||||
assertFalse(File(uploadedFile.storagePath).exists())
|
||||
assertTrue(uploadedFile.storagePath.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUploadWithDelete() {
|
||||
uploadOCUpload(nonEmptyUpload(), FileUploadWorker.LOCAL_BEHAVIOUR_DELETE)
|
||||
|
||||
val uploadedFile = uploadedNonEmptyFile()
|
||||
assertFalse(temporalFile(NON_EMPTY_FILE).exists())
|
||||
assertFalse(File(uploadedFile.storagePath).exists())
|
||||
assertTrue(uploadedFile.storagePath.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testChunkedUpload() {
|
||||
uploadOCUpload(ocUpload(CHUNKED_FILE, "$FOLDER$CHUNKED_FILE"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUploadInNonExistingFolder() {
|
||||
uploadOCUpload(ocUpload(EMPTY_FILE, "${FOLDER}2/3/4/1.txt"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUploadOnChargingOnlyButNotCharging() {
|
||||
val upload = ocUpload(EMPTY_FILE, "${FOLDER}notCharging.txt").apply { isWhileChargingOnly = true }
|
||||
|
||||
val result = uploadOperation(upload, whileChargingOnly = true).execute(client)
|
||||
|
||||
assertFalse(result.toString(), result.isSuccess)
|
||||
assertEquals(ResultCode.DELAYED_FOR_CHARGING, result.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUploadOnChargingOnlyAndCharging() {
|
||||
val upload = ocUpload(EMPTY_FILE, "${FOLDER}charging.txt").apply { isWhileChargingOnly = true }
|
||||
|
||||
val result = uploadOperation(
|
||||
upload,
|
||||
powerManagementService = PowerManagementFactory.mockCharging,
|
||||
whileChargingOnly = true
|
||||
).execute(client)
|
||||
|
||||
assertTrue(result.toString(), result.isSuccess)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUploadOnWifiOnlyButNoWifi() {
|
||||
val upload = ocUpload(EMPTY_FILE, "${FOLDER}noWifi.txt").apply { isUseWifiOnly = true }
|
||||
|
||||
val result = uploadOperation(
|
||||
upload,
|
||||
connectivityService = ConnectivityManagerFactory.wifi,
|
||||
onWifiOnly = true
|
||||
).execute(client)
|
||||
|
||||
assertFalse(result.toString(), result.isSuccess)
|
||||
assertEquals(ResultCode.DELAYED_FOR_WIFI, result.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUploadOnWifiOnlyAndWifi() {
|
||||
val upload = ocUpload(EMPTY_FILE, "${FOLDER}wifi.txt").apply { isWhileChargingOnly = true }
|
||||
|
||||
val result = uploadOperation(upload, onWifiOnly = true).execute(client)
|
||||
|
||||
assertTrue(result.toString(), result.isSuccess)
|
||||
removeTestFolder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUploadOnWifiOnlyButMeteredWifi() {
|
||||
val upload = ocUpload(EMPTY_FILE, "${FOLDER}noWifi.txt").apply { isUseWifiOnly = true }
|
||||
|
||||
val result = uploadOperation(
|
||||
upload,
|
||||
connectivityService = ConnectivityManagerFactory.metered,
|
||||
onWifiOnly = true
|
||||
).execute(client)
|
||||
|
||||
assertFalse(result.toString(), result.isSuccess)
|
||||
assertEquals(ResultCode.DELAYED_FOR_WIFI, result.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
@SinceServer(majorVersion = 27)
|
||||
fun testCreationAndUploadTimestamp() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_27)
|
||||
|
||||
val file = getDummyFile(EMPTY_FILE)
|
||||
val remotePath = "/testFile.txt"
|
||||
|
||||
assertTrue(uploadOperation(OCUpload(file.absolutePath, remotePath, account.name)).execute(client).isSuccess)
|
||||
|
||||
val creationTimestamp = Files.readAttributes(file.toPath(), BasicFileAttributes::class.java)
|
||||
.creationTime()
|
||||
.to(TimeUnit.SECONDS)
|
||||
val uploadTimestamp = nowInSeconds()
|
||||
|
||||
val ocFile = refreshRootAndGetContent().first()
|
||||
|
||||
assertEquals(remotePath, ocFile.remotePath)
|
||||
assertEquals(creationTimestamp, ocFile.creationTimestamp)
|
||||
assertTrue(abs(ocFile.uploadTimestamp - uploadTimestamp) < UPLOAD_TIMESTAMP_TOLERANCE_SECONDS)
|
||||
}
|
||||
|
||||
@Test
|
||||
@SinceServer(majorVersion = 27)
|
||||
fun testMetadata() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_27)
|
||||
|
||||
val file = getFile("gps.jpg")
|
||||
val remotePath = "/$METADATA_FILE"
|
||||
|
||||
assertTrue(uploadOperation(OCUpload(file.absolutePath, remotePath, account.name)).execute(client).isSuccess)
|
||||
|
||||
val ocFile = checkNotNull(refreshRootAndGetContent().find { it.fileName == METADATA_FILE }) {
|
||||
"$METADATA_FILE not found in root folder"
|
||||
}
|
||||
|
||||
assertEquals(remotePath, ocFile.remotePath)
|
||||
assertEquals(GeoLocation(EXPECTED_LATITUDE, EXPECTED_LONGITUDE), ocFile.geoLocation)
|
||||
assertEquals(ImageDimension(EXPECTED_WIDTH, EXPECTED_HEIGHT), ocFile.imageDimension)
|
||||
}
|
||||
|
||||
private fun uploadOperation(
|
||||
upload: OCUpload,
|
||||
connectivityService: ConnectivityService = connectivityServiceMock,
|
||||
powerManagementService: PowerManagementService = powerManagementServiceMock,
|
||||
onWifiOnly: Boolean = false,
|
||||
whileChargingOnly: Boolean = false
|
||||
): UploadFileOperation = UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityService,
|
||||
powerManagementService,
|
||||
user,
|
||||
null,
|
||||
upload,
|
||||
NameCollisionPolicy.DEFAULT,
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
onWifiOnly,
|
||||
whileChargingOnly,
|
||||
storageManager
|
||||
).apply {
|
||||
setRemoteFolderToBeCreated()
|
||||
addRenameUploadListener {}
|
||||
}
|
||||
|
||||
private fun refreshRootAndGetContent(): List<OCFile> {
|
||||
val refreshResult = RefreshFolderOperation(
|
||||
storageManager.getFileByDecryptedRemotePath(OCFile.ROOT_PATH),
|
||||
nowInSeconds(),
|
||||
false,
|
||||
false,
|
||||
storageManager,
|
||||
user,
|
||||
targetContext
|
||||
).execute(client)
|
||||
assertTrue(refreshResult.isSuccess)
|
||||
|
||||
return storageManager.getFolderContent(storageManager.getFileByDecryptedRemotePath(OCFile.ROOT_PATH), false)
|
||||
}
|
||||
|
||||
private fun removeTestFolder() {
|
||||
val folder = checkNotNull(storageManager.getFileByDecryptedRemotePath(FOLDER)) { "$FOLDER not found" }
|
||||
RemoveFileOperation(folder, false, user, false, targetContext, storageManager).execute(client)
|
||||
}
|
||||
|
||||
private fun temporalPath(name: String) = "${FileStorageUtils.getTemporalPath(account.name)}/$name"
|
||||
|
||||
private fun temporalFile(name: String) = File(temporalPath(name))
|
||||
|
||||
private fun ocUpload(localName: String, remotePath: String) =
|
||||
OCUpload(temporalPath(localName), remotePath, account.name)
|
||||
|
||||
private fun nonEmptyUpload() = ocUpload(NON_EMPTY_FILE, "$FOLDER$NON_EMPTY_FILE")
|
||||
|
||||
private fun uploadedNonEmptyFile(): OCFile =
|
||||
checkNotNull(storageManager.getFileByDecryptedRemotePath("$FOLDER$NON_EMPTY_FILE")) {
|
||||
"$FOLDER$NON_EMPTY_FILE not found"
|
||||
}
|
||||
|
||||
private fun nowInSeconds() = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())
|
||||
|
||||
private fun verifyStoragePath(file: OCFile) {
|
||||
assertEquals(
|
||||
FileStorageUtils.getSavePath(account.name) + FOLDER + file.decryptedFileName,
|
||||
file.storagePath
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val FOLDER = "/testUpload/"
|
||||
private const val EMPTY_FILE = "empty.txt"
|
||||
private const val NON_EMPTY_FILE = "nonEmpty.txt"
|
||||
private const val CHUNKED_FILE = "chunkedFile.txt"
|
||||
private const val METADATA_FILE = "metadata.jpg"
|
||||
private const val UPLOAD_TIMESTAMP_TOLERANCE_SECONDS = 10
|
||||
private const val EXPECTED_LATITUDE = 64.0
|
||||
private const val EXPECTED_LONGITUDE = -46.0
|
||||
private const val EXPECTED_WIDTH = 300f
|
||||
private const val EXPECTED_HEIGHT = 200f
|
||||
}
|
||||
}
|
||||
+4
@@ -18,6 +18,7 @@ class AuthenticatorActivityIT {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Suppress("TooGenericExceptionCaught")
|
||||
fun tryCatch() {
|
||||
val color = try {
|
||||
Color.parseColor("1")
|
||||
@@ -29,6 +30,7 @@ class AuthenticatorActivityIT {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Suppress("TooGenericExceptionCaught")
|
||||
fun tryCatch2() {
|
||||
val color = try {
|
||||
Color.parseColor("")
|
||||
@@ -40,6 +42,7 @@ class AuthenticatorActivityIT {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Suppress("TooGenericExceptionCaught")
|
||||
fun tryCatch3() {
|
||||
val color = try {
|
||||
Color.parseColor(null)
|
||||
@@ -51,6 +54,7 @@ class AuthenticatorActivityIT {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Suppress("TooGenericExceptionCaught")
|
||||
fun tryCatch4() {
|
||||
val color = try {
|
||||
Color.parseColor("abc")
|
||||
|
||||
-31
@@ -7,15 +7,10 @@
|
||||
*/
|
||||
package com.owncloud.android.datamodel;
|
||||
|
||||
import android.util.Pair;
|
||||
|
||||
import com.nextcloud.utils.extensions.FileDataStorageManagerExtensionsKt;
|
||||
import com.owncloud.android.db.ProviderMeta;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
@@ -49,30 +44,4 @@ public class FileDataStorageManagerContentProviderClientIT extends FileDataStora
|
||||
|
||||
assertEquals(file.getRemotePath(), read.getRemotePath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenerateFileNameForConflictResolution() {
|
||||
final var names = Arrays.asList(
|
||||
// Files
|
||||
new Pair<>("hello", "hello (1)"),
|
||||
new Pair<>("hello.txt", "hello (1).txt"),
|
||||
new Pair<>("hello (1).txt", "hello (2).txt"),
|
||||
new Pair<>("hello (18y5).txt", "hello (18y5) (1).txt"),
|
||||
new Pair<>("hello (hey)", "hello (hey) (1)"),
|
||||
new Pair<>("hello (hey).txt", "hello (hey) (1).txt"),
|
||||
new Pair<>(".hello", ".hello (1)"),
|
||||
|
||||
// Folders
|
||||
new Pair<>("hello/", "hello (1)/"),
|
||||
new Pair<>("hello (1)/", "hello (2)/"),
|
||||
new Pair<>("hello.hello/", "hello.hello (1)/"),
|
||||
new Pair<>("hello.hello (y)/", "hello.hello (y) (1)/"),
|
||||
new Pair<>(".hello/", ".hello (1)/")
|
||||
);
|
||||
|
||||
for (final var name: names) {
|
||||
String gen = FileDataStorageManagerExtensionsKt.generateFileNameForConflictResolution(name.first);
|
||||
assertEquals(gen, name.second);
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -50,11 +50,10 @@ abstract public class FileDataStorageManagerIT extends AbstractOnServerIT {
|
||||
// make sure everything is removed
|
||||
sut.deleteAllFiles();
|
||||
sut.deleteVirtuals(VirtualFolderType.GALLERY);
|
||||
|
||||
assertEquals(0, sut.getAllFiles().size());
|
||||
final var result = new GetCapabilitiesRemoteOperation(null)
|
||||
.execute(client);
|
||||
assertTrue(result.isSuccess());
|
||||
capability = result.getResultData();
|
||||
|
||||
capability = new GetCapabilitiesRemoteOperation(null).execute(client).getResultData();
|
||||
}
|
||||
|
||||
@After
|
||||
@@ -353,4 +352,5 @@ abstract public class FileDataStorageManagerIT extends AbstractOnServerIT {
|
||||
|
||||
assertEquals(capability.getUserStatus(), newCapability.getUserStatus());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -10,6 +10,7 @@ package com.owncloud.android.files
|
||||
import androidx.test.core.app.launchActivity
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.nextcloud.client.account.User
|
||||
import com.nextcloud.client.jobs.download.FileDownloadWorker
|
||||
import com.nextcloud.client.jobs.upload.FileUploadHelper
|
||||
import com.nextcloud.test.TestActivity
|
||||
import com.nextcloud.utils.EditorUtils
|
||||
@@ -47,6 +48,9 @@ class FileMenuFilterIT : AbstractIT() {
|
||||
@MockK
|
||||
private lateinit var mockFileUploaderBinder: FileUploadHelper
|
||||
|
||||
@MockK
|
||||
private lateinit var mockFileDownloadProgressListener: FileDownloadWorker.FileDownloadProgressListener
|
||||
|
||||
@MockK
|
||||
private lateinit var mockOperationsServiceBinder: OperationsService.OperationsServiceBinder
|
||||
|
||||
@@ -60,6 +64,7 @@ class FileMenuFilterIT : AbstractIT() {
|
||||
MockKAnnotations.init(this)
|
||||
every { mockFileUploaderBinder.isUploading(any(), any()) } returns false
|
||||
every { mockComponentsGetter.fileUploaderHelper } returns mockFileUploaderBinder
|
||||
every { mockComponentsGetter.fileDownloadProgressListener } returns mockFileDownloadProgressListener
|
||||
every { mockOperationsServiceBinder.isSynchronizing(any(), any()) } returns false
|
||||
every { mockComponentsGetter.operationsServiceBinder } returns mockOperationsServiceBinder
|
||||
every { mockStorageManager.getFileById(any()) } returns OCFile("/")
|
||||
|
||||
@@ -10,12 +10,9 @@
|
||||
package com.owncloud.android.files.services
|
||||
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker
|
||||
import com.nextcloud.utils.PowerManagementFactory
|
||||
import com.nextcloud.utils.extensions.getRemotePathForConflictResolution
|
||||
import com.nextcloud.utils.extensions.isTheSameAs
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker
|
||||
import com.owncloud.android.AbstractOnServerIT
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager
|
||||
import com.owncloud.android.db.OCUpload
|
||||
import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation
|
||||
@@ -109,71 +106,19 @@ class FileUploaderIT : AbstractOnServerIT() {
|
||||
assertRemoteFileLength(REMOTE_PATH, originalFile.length())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun uploadAndCheckFileIsTheSame() {
|
||||
val filename = NON_EMPTY_FILE
|
||||
val remotePath = OCFile.PATH_SEPARATOR + filename
|
||||
|
||||
// Upload file
|
||||
val originalFile = getDummyFile(filename)
|
||||
val operation = uploadOperation(
|
||||
originalFile,
|
||||
NameCollisionPolicy.DEFAULT,
|
||||
remotePath
|
||||
).setRemoteFolderToBeCreated()
|
||||
assertTrue(operation.execute(client).isSuccess)
|
||||
|
||||
// Check file metadata against remote one
|
||||
val ocFile = storageManager.getFileByRemotePath(remotePath)
|
||||
assertTrue(ocFile.isTheSameAs(originalFile))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun uploadAndCheckFileIsNotTheSame() {
|
||||
val filename = NON_EMPTY_FILE
|
||||
|
||||
// Upload file
|
||||
val originalFile = getDummyFile(filename)
|
||||
val operation = uploadOperation(
|
||||
originalFile,
|
||||
NameCollisionPolicy.DEFAULT
|
||||
).setRemoteFolderToBeCreated()
|
||||
assertTrue(operation.execute(client).isSuccess)
|
||||
|
||||
// Check file metadata against remote one
|
||||
val ocFile = storageManager.getFileByRemotePath(REMOTE_PATH)
|
||||
assertFalse(ocFile.isTheSameAs(originalFile))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun uploadAndCheckConflictingName() {
|
||||
val originalFile = getDummyFile(EMPTY_FILE)
|
||||
uploadOriginalFile(originalFile)
|
||||
val newPath = getRemotePathForConflictResolution(
|
||||
client,
|
||||
OCFile.PATH_SEPARATOR,
|
||||
REMOTE_FILE
|
||||
)
|
||||
assertEquals(newPath, "${OCFile.PATH_SEPARATOR}$REMOTE_FILE_NAME (1).$REMOTE_FILE_EXTENSION")
|
||||
}
|
||||
|
||||
private fun uploadOriginalFile(originalFile: File) {
|
||||
val operation = uploadOperation(originalFile, NameCollisionPolicy.DEFAULT).setRemoteFolderToBeCreated()
|
||||
assertTrue(operation.execute(client).isSuccess)
|
||||
assertRemoteFileLength(REMOTE_PATH, originalFile.length())
|
||||
}
|
||||
|
||||
private fun uploadOperation(
|
||||
localFile: File,
|
||||
nameCollisionPolicy: NameCollisionPolicy,
|
||||
remotePath: String = REMOTE_PATH
|
||||
) = UploadFileOperation(
|
||||
private fun uploadOperation(localFile: File, nameCollisionPolicy: NameCollisionPolicy) = UploadFileOperation(
|
||||
uploadsStorageManager,
|
||||
connectivityServiceMock,
|
||||
powerManagementServiceMock,
|
||||
user,
|
||||
null,
|
||||
OCUpload(localFile.absolutePath, remotePath, account.name),
|
||||
OCUpload(localFile.absolutePath, REMOTE_PATH, account.name),
|
||||
nameCollisionPolicy,
|
||||
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
|
||||
targetContext,
|
||||
@@ -189,10 +134,7 @@ class FileUploaderIT : AbstractOnServerIT() {
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val REMOTE_FILE_NAME = "testFile"
|
||||
private const val REMOTE_FILE_EXTENSION = "txt"
|
||||
private const val REMOTE_FILE = "$REMOTE_FILE_NAME.$REMOTE_FILE_EXTENSION"
|
||||
private const val REMOTE_PATH = "${OCFile.PATH_SEPARATOR}$REMOTE_FILE"
|
||||
private const val REMOTE_PATH = "/testFile.txt"
|
||||
private const val REMOTE_PATH_RENAMED = "/testFile (2).txt"
|
||||
private const val CHUNKED_FILE = "chunkedFile.txt"
|
||||
private const val NON_EMPTY_FILE = "nonEmpty.txt"
|
||||
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.owncloud.android.operations
|
||||
|
||||
import com.owncloud.android.AbstractOnServerIT
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult
|
||||
import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation
|
||||
import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation
|
||||
import com.owncloud.android.lib.resources.files.UploadFileRemoteOperation
|
||||
import com.owncloud.android.lib.resources.files.model.RemoteFile
|
||||
import org.junit.Assert.assertTrue
|
||||
import java.io.File
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
abstract class AbstractInternalTwoWaySyncIT : AbstractOnServerIT() {
|
||||
|
||||
companion object {
|
||||
const val TWO_WAY_SYNC_ENABLED = 0L
|
||||
const val BINARY_MIME_TYPE = "application/octet-stream"
|
||||
const val MILLIS_IN_SECOND = 1000
|
||||
const val POLL_ATTEMPTS = 10
|
||||
const val SMALL_DUMMY_FILE = "nonEmpty.txt"
|
||||
const val LARGE_DUMMY_FILE = "chunkedFile.txt"
|
||||
const val FILE_NAME = "file.bin"
|
||||
}
|
||||
|
||||
protected fun sync(remotePath: String): RemoteOperationResult<*> =
|
||||
SynchronizeFolderOperation(targetContext, remotePath, user, storageManager, false, true)
|
||||
.execute(targetContext)
|
||||
|
||||
protected fun syncAndAssertSuccess(remotePath: String) = assertTrue(sync(remotePath).isSuccess)
|
||||
|
||||
protected fun setUpTwoWaySyncFolder(remotePath: String): OCFile {
|
||||
createFolder(remotePath)
|
||||
syncAndAssertSuccess(remotePath)
|
||||
|
||||
return storageManager.getFileByPath(remotePath).apply {
|
||||
internalFolderSyncTimestamp = TWO_WAY_SYNC_ENABLED
|
||||
storageManager.saveFile(this)
|
||||
}
|
||||
}
|
||||
|
||||
protected fun setUpTwoWaySyncFolderWithFile(remotePath: String): OCFile = setUpTwoWaySyncFolder(remotePath).also {
|
||||
uploadFile(getDummyFile(SMALL_DUMMY_FILE), it.childPath(FILE_NAME))
|
||||
syncAndAssertSuccess(it.remotePath)
|
||||
}
|
||||
|
||||
protected fun uploadDirectlyToServer(localFile: File, remotePath: String) {
|
||||
val modificationTimestamp = System.currentTimeMillis() / MILLIS_IN_SECOND
|
||||
val result = UploadFileRemoteOperation(
|
||||
localFile.absolutePath,
|
||||
remotePath,
|
||||
BINARY_MIME_TYPE,
|
||||
modificationTimestamp
|
||||
).execute(client)
|
||||
assertTrue(result.isSuccess)
|
||||
}
|
||||
|
||||
protected fun existsOnServer(remotePath: String): Boolean =
|
||||
ExistenceCheckRemoteOperation(remotePath, false).execute(client).isSuccess
|
||||
|
||||
protected fun serverEtagOf(remotePath: String): String? = ReadFileRemoteOperation(remotePath)
|
||||
.execute(client)
|
||||
.takeIf { it.isSuccess }
|
||||
?.let { (it.data.first() as RemoteFile).etag }
|
||||
|
||||
protected fun waitUntil(condition: () -> Boolean): Boolean = (1..POLL_ATTEMPTS).any {
|
||||
val fulfilled = condition()
|
||||
if (!fulfilled) {
|
||||
shortSleep()
|
||||
}
|
||||
fulfilled
|
||||
}
|
||||
|
||||
protected fun waitUntilServerEtagChanges(remotePath: String, previousEtag: String): Boolean = waitUntil {
|
||||
serverEtagOf(remotePath)?.let { etag -> etag != previousEtag } == true
|
||||
}
|
||||
|
||||
protected fun OCFile.childPath(name: String): String = remotePath + name
|
||||
|
||||
protected fun OCFile.childFolderPath(name: String): String = remotePath + name + OCFile.PATH_SEPARATOR
|
||||
}
|
||||
+3
-4
@@ -12,9 +12,8 @@ import com.owncloud.android.lib.resources.e2ee.DeleteEncryptedFilesRemoteOperati
|
||||
import com.owncloud.android.lib.resources.users.DeletePrivateKeyRemoteOperation
|
||||
import com.owncloud.android.lib.resources.users.DeletePublicKeyRemoteOperation
|
||||
import com.owncloud.android.lib.resources.users.GetPrivateKeyRemoteOperation
|
||||
import com.owncloud.android.lib.resources.users.GetCertificateRemoteOperation
|
||||
import com.owncloud.android.lib.resources.users.GetPublicKeyRemoteOperation
|
||||
import com.owncloud.android.lib.resources.users.StorePrivateKeyRemoteOperation
|
||||
import com.owncloud.android.ui.dialog.setupEncryption.EncryptionKeyGenerator
|
||||
import com.owncloud.android.utils.EncryptionUtils
|
||||
import com.owncloud.android.utils.crypto.CryptoHelper
|
||||
import org.junit.Assert.assertFalse
|
||||
@@ -32,7 +31,7 @@ class DeleteE2ERemoteOperationIT : AbstractOnServerIT() {
|
||||
|
||||
@Test
|
||||
fun testDeletePrivateKey() {
|
||||
val keyPair = EncryptionKeyGenerator.generateKeyPair()
|
||||
val keyPair = EncryptionUtils.generateKeyPair()
|
||||
val privateKey = keyPair.private
|
||||
val keyPhrase = "moreovertelevisionfactorytendencyindependenceinternationalintellectualimpress" +
|
||||
"interestvolunteer"
|
||||
@@ -58,7 +57,7 @@ class DeleteE2ERemoteOperationIT : AbstractOnServerIT() {
|
||||
val result = sut.execute(nextcloudClient)
|
||||
assertTrue(result.isSuccess)
|
||||
|
||||
val getResult = GetCertificateRemoteOperation().execute(nextcloudClient)
|
||||
val getResult = GetPublicKeyRemoteOperation().execute(nextcloudClient)
|
||||
assertFalse(getResult.isSuccess)
|
||||
}
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.owncloud.android.operations
|
||||
|
||||
import com.owncloud.android.lib.resources.files.CreateFolderRemoteOperation
|
||||
import com.owncloud.android.lib.resources.files.RemoveFileRemoteOperation
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
class InternalTwoWaySyncIT : AbstractInternalTwoWaySyncIT() {
|
||||
|
||||
companion object {
|
||||
private const val NESTED_FILE_NAME = "nested.bin"
|
||||
private const val SUB_FOLDER_NAME = "sub"
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testWhenLocalFileCreatedGivenShouldUploadToServer() {
|
||||
val folder = setUpTwoWaySyncFolder("/twoWaySyncLocalCreateFile/")
|
||||
File(folder.storagePath, FILE_NAME).writeText("hello")
|
||||
|
||||
syncAndAssertSuccess(folder.remotePath)
|
||||
|
||||
val uploaded = storageManager.getFileByPath(folder.childPath(FILE_NAME))
|
||||
assertNotNull(uploaded)
|
||||
assertTrue(File(uploaded.storagePath).exists())
|
||||
assertTrue(existsOnServer(folder.childPath(FILE_NAME)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testWhenLocalFolderWithContentsCreatedGivenShouldCreateFolderAndUploadContents() {
|
||||
val folder = setUpTwoWaySyncFolder("/twoWaySyncLocalCreateFolder/")
|
||||
val subFolder = File(folder.storagePath, SUB_FOLDER_NAME).apply { mkdir() }
|
||||
File(subFolder, NESTED_FILE_NAME).writeText("nested")
|
||||
|
||||
syncAndAssertSuccess(folder.remotePath)
|
||||
|
||||
val remoteSubFolder = storageManager.getFileByPath(folder.childFolderPath(SUB_FOLDER_NAME))
|
||||
assertNotNull(remoteSubFolder)
|
||||
assertTrue(remoteSubFolder.isFolder)
|
||||
|
||||
val nested = storageManager.getFileByPath(remoteSubFolder.childPath(NESTED_FILE_NAME))
|
||||
assertNotNull(nested)
|
||||
assertTrue(File(nested.storagePath).exists())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testWhenLocalFileUpdatedGivenShouldUploadNewVersion() {
|
||||
val folder = setUpTwoWaySyncFolderWithFile("/twoWaySyncLocalUpdate/")
|
||||
val before = storageManager.getFileByPath(folder.childPath(FILE_NAME))
|
||||
|
||||
shortSleep()
|
||||
File(before.storagePath).writeText("updated by test")
|
||||
|
||||
syncAndAssertSuccess(folder.remotePath)
|
||||
|
||||
assertTrue(
|
||||
"Locally modified file was not uploaded within timeout",
|
||||
waitUntilServerEtagChanges(folder.childPath(FILE_NAME), before.etag)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testWhenLocalFileDeletedGivenShouldRemoveFromServer() {
|
||||
val folder = setUpTwoWaySyncFolderWithFile("/twoWaySyncLocalDelete/")
|
||||
val file = storageManager.getFileByPath(folder.childPath(FILE_NAME))
|
||||
assertTrue(File(file.storagePath).delete())
|
||||
|
||||
syncAndAssertSuccess(folder.remotePath)
|
||||
|
||||
assertNull(storageManager.getFileByPath(folder.childPath(FILE_NAME)))
|
||||
assertFalse(existsOnServer(folder.childPath(FILE_NAME)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testWhenRemoteFileCreatedGivenShouldDownload() {
|
||||
val folder = setUpTwoWaySyncFolder("/twoWaySyncRemoteCreateFile/")
|
||||
uploadDirectlyToServer(getDummyFile(SMALL_DUMMY_FILE), folder.childPath(FILE_NAME))
|
||||
|
||||
syncAndAssertSuccess(folder.remotePath)
|
||||
|
||||
val downloaded = storageManager.getFileByPath(folder.childPath(FILE_NAME))
|
||||
assertNotNull(downloaded)
|
||||
assertTrue(File(downloaded.storagePath).exists())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testWhenRemoteFolderWithContentsCreatedGivenShouldDownloadFolderAndContents() {
|
||||
val folder = setUpTwoWaySyncFolder("/twoWaySyncRemoteCreateFolder/")
|
||||
val subFolderPath = folder.childFolderPath(SUB_FOLDER_NAME)
|
||||
assertTrue(CreateFolderRemoteOperation(subFolderPath, true).execute(client).isSuccess)
|
||||
uploadDirectlyToServer(getDummyFile(SMALL_DUMMY_FILE), subFolderPath + NESTED_FILE_NAME)
|
||||
|
||||
syncAndAssertSuccess(folder.remotePath)
|
||||
|
||||
val remoteSubFolder = storageManager.getFileByPath(subFolderPath)
|
||||
assertNotNull(remoteSubFolder)
|
||||
assertTrue(remoteSubFolder.isFolder)
|
||||
|
||||
syncAndAssertSuccess(subFolderPath)
|
||||
|
||||
val nested = storageManager.getFileByPath(subFolderPath + NESTED_FILE_NAME)
|
||||
assertNotNull(nested)
|
||||
assertTrue(File(nested.storagePath).exists())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testWhenRemoteFileUpdatedGivenShouldDownloadNewVersion() {
|
||||
val folder = setUpTwoWaySyncFolderWithFile("/twoWaySyncRemoteUpdate/")
|
||||
val before = storageManager.getFileByPath(folder.childPath(FILE_NAME))
|
||||
val newVersion = getDummyFile(LARGE_DUMMY_FILE)
|
||||
uploadDirectlyToServer(newVersion, folder.childPath(FILE_NAME))
|
||||
|
||||
syncAndAssertSuccess(folder.remotePath)
|
||||
|
||||
val after = storageManager.getFileByPath(folder.childPath(FILE_NAME))
|
||||
assertNotEquals(before.etag, after.etag)
|
||||
assertEquals(newVersion.length(), File(after.storagePath).length())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testWhenRemoteFileDeletedGivenShouldRemoveLocally() {
|
||||
val folder = setUpTwoWaySyncFolderWithFile("/twoWaySyncRemoteDeleteFile/")
|
||||
val localFile = File(storageManager.getFileByPath(folder.childPath(FILE_NAME)).storagePath)
|
||||
assertTrue(localFile.exists())
|
||||
assertTrue(RemoveFileRemoteOperation(folder.childPath(FILE_NAME)).execute(client).isSuccess)
|
||||
|
||||
syncAndAssertSuccess(folder.remotePath)
|
||||
|
||||
assertNull(storageManager.getFileByPath(folder.childPath(FILE_NAME)))
|
||||
assertFalse(localFile.exists())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testWhenRemoteFolderWithContentsDeletedGivenShouldRemoveLocally() {
|
||||
val folder = setUpTwoWaySyncFolder("/twoWaySyncRemoteDeleteFolder/")
|
||||
val subFolderPath = folder.childFolderPath(SUB_FOLDER_NAME)
|
||||
val subFolder = File(folder.storagePath, SUB_FOLDER_NAME).apply { mkdir() }
|
||||
File(subFolder, NESTED_FILE_NAME).writeText("nested")
|
||||
syncAndAssertSuccess(folder.remotePath)
|
||||
assertNotNull(storageManager.getFileByPath(subFolderPath))
|
||||
assertTrue(RemoveFileRemoteOperation(subFolderPath).execute(client).isSuccess)
|
||||
|
||||
syncAndAssertSuccess(folder.remotePath)
|
||||
|
||||
assertNull(storageManager.getFileByPath(subFolderPath))
|
||||
assertFalse(subFolder.exists())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testWhenBothSidesChangedGivenShouldMarkConflict() {
|
||||
val folder = setUpTwoWaySyncFolderWithFile("/twoWaySyncConflict/")
|
||||
val before = storageManager.getFileByPath(folder.childPath(FILE_NAME))
|
||||
|
||||
shortSleep()
|
||||
File(before.storagePath).writeText("local edit")
|
||||
uploadDirectlyToServer(getDummyFile(LARGE_DUMMY_FILE), folder.childPath(FILE_NAME))
|
||||
|
||||
sync(folder.remotePath)
|
||||
|
||||
val after = storageManager.getFileByPath(folder.childPath(FILE_NAME))
|
||||
assertNotNull("Concurrently changed file should have been flagged as conflicting", after.etagInConflict)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testWhenNoChangesGivenShouldSecondSyncNotWork() {
|
||||
val folder = setUpTwoWaySyncFolderWithFile("/twoWaySyncNoop/")
|
||||
val before = storageManager.getFileByPath(folder.childPath(FILE_NAME))
|
||||
|
||||
syncAndAssertSuccess(folder.remotePath)
|
||||
|
||||
val after = storageManager.getFileByPath(folder.childPath(FILE_NAME))
|
||||
assertEquals(before.etag, after.etag)
|
||||
assertEquals(before.fileId, after.fileId)
|
||||
}
|
||||
}
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.owncloud.android.operations
|
||||
|
||||
import android.media.MediaScannerConnection
|
||||
import android.net.Uri
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
class InternalTwoWaySyncLocalEditIT : AbstractInternalTwoWaySyncIT() {
|
||||
|
||||
companion object {
|
||||
private const val IMAGE_ASSET = "image.jpg"
|
||||
private const val IMAGE_NAME = "edited.jpg"
|
||||
private const val MEDIA_SCAN_TIMEOUT_SECONDS = 10L
|
||||
private val EDITED_BYTES = byteArrayOf(0, 1, 2, 3)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testWhenLocalImageEditedGivenShouldKeepLocalAndServerCopyAcrossSyncs() {
|
||||
val folder = setUpTwoWaySyncFolder("/twoWaySyncEditedImage/")
|
||||
val localImage = File(folder.storagePath, IMAGE_NAME)
|
||||
getFile(IMAGE_ASSET).copyTo(localImage)
|
||||
syncAndAssertSuccess(folder.remotePath)
|
||||
|
||||
val before = storageManager.getFileByPath(folder.childPath(IMAGE_NAME))
|
||||
assertNotNull(before)
|
||||
assertEquals(localImage, File(before.storagePath))
|
||||
scanIntoMediaStore(localImage)
|
||||
|
||||
shortSleep()
|
||||
localImage.appendBytes(EDITED_BYTES)
|
||||
syncAndAssertSuccess(folder.remotePath)
|
||||
|
||||
assertTrue(
|
||||
"Edited image was not uploaded within timeout",
|
||||
waitUntil { storageManager.getFileByPath(folder.childPath(IMAGE_NAME))?.etag != before.etag }
|
||||
)
|
||||
assertTrue("Edited image was removed locally after upload", localImage.exists())
|
||||
|
||||
syncAndAssertSuccess(folder.remotePath)
|
||||
|
||||
assertTrue("Edited image was removed locally after next sync", localImage.exists())
|
||||
assertTrue("Edited image was removed from server after next sync", existsOnServer(before.remotePath))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testWhenLocalFileMissingAndServerChangedGivenShouldDownloadInsteadOfDeletingOnServer() {
|
||||
val folder = setUpTwoWaySyncFolderWithFile("/twoWaySyncMissingLocallyChangedOnServer/")
|
||||
val localFile = File(storageManager.getFileByPath(folder.childPath(FILE_NAME)).storagePath)
|
||||
assertTrue(localFile.delete())
|
||||
val newVersion = getDummyFile(LARGE_DUMMY_FILE)
|
||||
uploadDirectlyToServer(newVersion, folder.childPath(FILE_NAME))
|
||||
|
||||
syncAndAssertSuccess(folder.remotePath)
|
||||
|
||||
assertTrue(existsOnServer(folder.childPath(FILE_NAME)))
|
||||
assertTrue(localFile.exists())
|
||||
assertEquals(newVersion.length(), localFile.length())
|
||||
}
|
||||
|
||||
private fun scanIntoMediaStore(file: File) {
|
||||
val latch = CountDownLatch(1)
|
||||
val scannedUri = AtomicReference<Uri?>()
|
||||
MediaScannerConnection.scanFile(targetContext, arrayOf(file.absolutePath), null) { _, uri ->
|
||||
scannedUri.set(uri)
|
||||
latch.countDown()
|
||||
}
|
||||
|
||||
assertTrue("Media scan did not finish", latch.await(MEDIA_SCAN_TIMEOUT_SECONDS, TimeUnit.SECONDS))
|
||||
assertNotNull("Image is not indexed by MediaStore", scannedUri.get())
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -4,7 +4,7 @@
|
||||
* SPDX-FileCopyrightText: 2020 Torsten Grote <t@grobox.de>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.owncloud.android.providers.documentstorage
|
||||
package com.owncloud.android.providers
|
||||
|
||||
import android.content.Context
|
||||
import android.database.ContentObserver
|
||||
@@ -25,7 +25,7 @@ import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.lib.common.OwnCloudClient
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation
|
||||
import com.owncloud.android.providers.documentstorage.DocumentsStorageProvider.Companion.DOCUMENTID_SEPARATOR
|
||||
import com.owncloud.android.providers.DocumentsStorageProvider.DOCUMENTID_SEPARATOR
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.TimeoutCancellationException
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
+22
-30
@@ -4,13 +4,12 @@
|
||||
* SPDX-FileCopyrightText: 2020 Torsten Grote <t@grobox.de>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.owncloud.android.providers.documentstorage
|
||||
package com.owncloud.android.providers
|
||||
|
||||
import android.provider.DocumentsContract
|
||||
import androidx.documentfile.provider.DocumentFile
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl
|
||||
import com.nextcloud.client.jobs.upload.FileUploadHelper
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker
|
||||
import com.nextcloud.test.RandomStringGenerator
|
||||
import com.owncloud.android.AbstractOnServerIT
|
||||
import com.owncloud.android.R
|
||||
@@ -18,18 +17,17 @@ import com.owncloud.android.datamodel.OCFile.ROOT_PATH
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager.UploadStatus
|
||||
import com.owncloud.android.db.OCUpload
|
||||
import com.owncloud.android.db.UploadResult
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.providers.documentstorage.DocumentsProviderUtils.assertExistsOnServer
|
||||
import com.owncloud.android.providers.documentstorage.DocumentsProviderUtils.assertListFilesEquals
|
||||
import com.owncloud.android.providers.documentstorage.DocumentsProviderUtils.assertReadEquals
|
||||
import com.owncloud.android.providers.documentstorage.DocumentsProviderUtils.assertRecentlyModified
|
||||
import com.owncloud.android.providers.documentstorage.DocumentsProviderUtils.assertRegularFile
|
||||
import com.owncloud.android.providers.documentstorage.DocumentsProviderUtils.assertRegularFolder
|
||||
import com.owncloud.android.providers.documentstorage.DocumentsProviderUtils.findFileBlocking
|
||||
import com.owncloud.android.providers.documentstorage.DocumentsProviderUtils.getOCFile
|
||||
import com.owncloud.android.providers.documentstorage.DocumentsProviderUtils.listFilesBlocking
|
||||
import com.owncloud.android.providers.documentstorage.DocumentsStorageProvider.Companion.DOCUMENTID_SEPARATOR
|
||||
import com.owncloud.android.providers.DocumentsProviderUtils.assertExistsOnServer
|
||||
import com.owncloud.android.providers.DocumentsProviderUtils.assertListFilesEquals
|
||||
import com.owncloud.android.providers.DocumentsProviderUtils.assertReadEquals
|
||||
import com.owncloud.android.providers.DocumentsProviderUtils.assertRecentlyModified
|
||||
import com.owncloud.android.providers.DocumentsProviderUtils.assertRegularFile
|
||||
import com.owncloud.android.providers.DocumentsProviderUtils.assertRegularFolder
|
||||
import com.owncloud.android.providers.DocumentsProviderUtils.findFileBlocking
|
||||
import com.owncloud.android.providers.DocumentsProviderUtils.getOCFile
|
||||
import com.owncloud.android.providers.DocumentsProviderUtils.listFilesBlocking
|
||||
import com.owncloud.android.providers.DocumentsStorageProvider.DOCUMENTID_SEPARATOR
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.apache.commons.httpclient.HttpStatus
|
||||
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity
|
||||
@@ -231,7 +229,7 @@ class DocumentsStorageProviderIT : AbstractOnServerIT() {
|
||||
it!!.write(content1)
|
||||
}
|
||||
|
||||
awaitUploadedToServer(file1)
|
||||
awaitUploadedToServer(file1, createdETag)
|
||||
|
||||
val remotePath = file1.getOCFile(storageManager)!!.remotePath
|
||||
|
||||
@@ -266,7 +264,7 @@ class DocumentsStorageProviderIT : AbstractOnServerIT() {
|
||||
it!!.write(content1)
|
||||
}
|
||||
|
||||
awaitUploadedToServer(file1)
|
||||
awaitUploadedToServer(file1, createdETag)
|
||||
|
||||
val content2 = "new content".toByteArray()
|
||||
|
||||
@@ -279,34 +277,28 @@ class DocumentsStorageProviderIT : AbstractOnServerIT() {
|
||||
assertEquals(String(content2), String(bytes))
|
||||
}
|
||||
|
||||
private fun awaitUploadedToServer(file: DocumentFile) {
|
||||
private fun awaitUploadedToServer(file: DocumentFile, etagBeforeUpload: String) {
|
||||
val remotePath = file.getOCFile(storageManager)!!.remotePath
|
||||
|
||||
repeat(UPLOAD_POLL_ATTEMPTS) {
|
||||
val upload = upload(remotePath)
|
||||
if (upload?.uploadStatus == UploadStatus.UPLOAD_FAILED ||
|
||||
(upload?.uploadStatus == UploadStatus.UPLOAD_SUCCEEDED && upload.lastResult != UploadResult.UPLOADED)
|
||||
) {
|
||||
fail("upload of $remotePath failed with ${upload.lastResult}")
|
||||
}
|
||||
|
||||
// the status is stored before the worker deletes the local copy and saves the file,
|
||||
// so the upload only counts as finished once the worker has released it
|
||||
if (upload?.uploadStatus == UploadStatus.UPLOAD_SUCCEEDED &&
|
||||
!FileUploadWorker.isUploading(remotePath, user.accountName)
|
||||
) {
|
||||
if (file.getOCFile(storageManager)!!.etagOnServer != etagBeforeUpload) {
|
||||
return
|
||||
}
|
||||
|
||||
failedUpload(remotePath)?.let {
|
||||
fail("upload of $remotePath failed with ${it.lastResult}")
|
||||
}
|
||||
|
||||
shortSleep()
|
||||
rootDir.listFiles()
|
||||
}
|
||||
|
||||
fail("upload of $remotePath did not finish, stored uploads: ${describeUploads()}")
|
||||
}
|
||||
|
||||
private fun upload(remotePath: String): OCUpload? = uploadsStorageManager
|
||||
private fun failedUpload(remotePath: String): OCUpload? = uploadsStorageManager
|
||||
.getUploadsForAccount(user.accountName)
|
||||
.firstOrNull { it.remotePath == remotePath }
|
||||
.firstOrNull { it.remotePath == remotePath && it.uploadStatus == UploadStatus.UPLOAD_FAILED }
|
||||
|
||||
private fun describeUploads(): String = uploadsStorageManager
|
||||
.getUploadsForAccount(user.accountName)
|
||||
@@ -52,7 +52,7 @@ class LoginIT : AbstractIT() {
|
||||
*/
|
||||
@Test
|
||||
@Throws(InterruptedException::class)
|
||||
@Suppress("MagicNumber")
|
||||
@Suppress("MagicNumber", "SwallowedException")
|
||||
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.Q)
|
||||
@Flaky("Login no longer uses an in-app WebView, so espresso-web (Espresso.onWebView) cannot drive it. ")
|
||||
fun login() {
|
||||
|
||||
@@ -10,24 +10,14 @@ package com.owncloud.android.ui.activity
|
||||
|
||||
import android.accounts.Account
|
||||
import android.accounts.AccountManager
|
||||
import android.content.ContentUris
|
||||
import android.content.ContentValues
|
||||
import android.net.Uri
|
||||
import android.os.SystemClock
|
||||
import androidx.test.core.app.ActivityScenario
|
||||
import androidx.test.core.app.launchActivity
|
||||
import androidx.test.espresso.Espresso.onView
|
||||
import androidx.test.espresso.action.ViewActions.click
|
||||
import androidx.test.espresso.contrib.DrawerActions
|
||||
import androidx.test.espresso.contrib.NavigationViewActions
|
||||
import androidx.test.espresso.intent.Intents
|
||||
import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent
|
||||
import androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra
|
||||
import androidx.test.espresso.matcher.ViewMatchers.withId
|
||||
import androidx.test.espresso.matcher.ViewMatchers.withText
|
||||
import androidx.test.espresso.action.ViewActions
|
||||
import androidx.test.espresso.matcher.ViewMatchers
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import androidx.test.rule.GrantPermissionRule
|
||||
import com.google.android.material.navigation.NavigationView
|
||||
import com.nextcloud.client.account.User
|
||||
import com.nextcloud.client.account.UserAccountManager
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl
|
||||
import com.nextcloud.test.Flaky
|
||||
@@ -36,21 +26,17 @@ import com.nextcloud.test.RetryTestRule
|
||||
import com.owncloud.android.AbstractIT
|
||||
import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
|
||||
import com.owncloud.android.lib.common.ExternalLinkType
|
||||
import com.owncloud.android.lib.common.accounts.AccountUtils
|
||||
import com.owncloud.android.ui.navigation.NavigatorActivity
|
||||
import com.owncloud.android.ui.navigation.NavigatorScreen
|
||||
import org.hamcrest.Matchers.allOf
|
||||
import org.hamcrest.Matchers.anyOf
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.hamcrest.Matchers
|
||||
import org.junit.Assert
|
||||
import org.junit.BeforeClass
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import java.util.function.Supplier
|
||||
|
||||
class DrawerActivityIT : AbstractIT() {
|
||||
@get:Rule
|
||||
@Rule
|
||||
@JvmField
|
||||
val retryTestRule = RetryTestRule()
|
||||
|
||||
@get:Rule
|
||||
@@ -59,136 +45,89 @@ class DrawerActivityIT : AbstractIT() {
|
||||
@Test
|
||||
@Flaky(reason = "Account switch relaunches FileDisplayActivity, which races with the drawer assertions")
|
||||
fun switchAccountViaAccountList() {
|
||||
// Switching accounts finishes and relaunches FileDisplayActivity (see
|
||||
// FileDisplayActivity.handleRestartIntent). That self-relaunch is incompatible with
|
||||
// ActivityScenario#close(), which cannot drive its tracked instance to DESTROYED, so the
|
||||
// scenario is launched without auto-closing.
|
||||
val scenario = launchActivity<FileDisplayActivity>()
|
||||
lateinit var sut: FileDisplayActivity
|
||||
scenario.onActivity { sut = it }
|
||||
scenario.onActivity { activity ->
|
||||
sut = activity
|
||||
}
|
||||
|
||||
assertEquals(account1, sut.user.get().toPlatformAccount())
|
||||
Assert.assertEquals(account1, sut.user.get().toPlatformAccount())
|
||||
|
||||
onView(withId(R.id.switch_account_button)).perform(click())
|
||||
onView(anyOf(withText(account2Name), withText(account2DisplayName))).perform(click())
|
||||
|
||||
assertEquals(account2, sut.user.get().toPlatformAccount())
|
||||
|
||||
onView(withId(R.id.switch_account_button)).perform(click())
|
||||
onView(withText(account1.name)).perform(click())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun externalLinkWithIdBeyondLegacyRangeIsOpened() {
|
||||
val linkId = insertExternalLink()
|
||||
assertTrue(linkId > LEGACY_EXTERNAL_LINK_RANGE)
|
||||
val menuItemId = MENU_ITEM_EXTERNAL_LINK + linkId
|
||||
|
||||
Intents.init()
|
||||
try {
|
||||
val intent = NavigatorActivity.intent(targetContext, NavigatorScreen.Community)
|
||||
ActivityScenario.launch<NavigatorActivity>(intent).use { scenario ->
|
||||
waitUntil { scenario.hasDrawerMenuItem(menuItemId) }
|
||||
|
||||
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open())
|
||||
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(menuItemId))
|
||||
|
||||
val externalSiteIntent = allOf(
|
||||
hasComponent(ExternalSiteWebView::class.java.name),
|
||||
hasExtra(ExternalSiteWebView.EXTRA_URL, EXTERNAL_LINK_URL)
|
||||
onView(ViewMatchers.withId(R.id.switch_account_button)).perform(ViewActions.click())
|
||||
onView(
|
||||
Matchers.anyOf(
|
||||
ViewMatchers.withText(account2Name),
|
||||
ViewMatchers.withText(
|
||||
account2DisplayName
|
||||
)
|
||||
waitUntil { Intents.getIntents().any(externalSiteIntent::matches) }
|
||||
}
|
||||
} finally {
|
||||
Intents.release()
|
||||
deleteExternalLink(linkId)
|
||||
}
|
||||
}
|
||||
)
|
||||
).perform(ViewActions.click())
|
||||
|
||||
private fun ActivityScenario<NavigatorActivity>.hasDrawerMenuItem(menuItemId: Int): Boolean {
|
||||
var found = false
|
||||
onActivity {
|
||||
found = it.findViewById<NavigationView>(R.id.nav_view).menu.findItem(menuItemId) != null
|
||||
}
|
||||
return found
|
||||
}
|
||||
Assert.assertEquals(account2, sut.user.get().toPlatformAccount())
|
||||
|
||||
private fun waitUntil(condition: () -> Boolean) {
|
||||
val deadline = SystemClock.elapsedRealtime() + WAIT_TIMEOUT_MILLIS
|
||||
while (!condition()) {
|
||||
check(SystemClock.elapsedRealtime() < deadline) { "Condition not met within $WAIT_TIMEOUT_MILLIS ms" }
|
||||
SystemClock.sleep(WAIT_POLL_INTERVAL_MILLIS)
|
||||
}
|
||||
}
|
||||
|
||||
private fun insertExternalLink(): Int {
|
||||
val values = ContentValues().apply {
|
||||
put(ProviderTableMeta._ID, EXTERNAL_LINK_ID)
|
||||
put(ProviderTableMeta.EXTERNAL_LINKS_ICON_URL, "")
|
||||
put(ProviderTableMeta.EXTERNAL_LINKS_LANGUAGE, "en")
|
||||
put(ProviderTableMeta.EXTERNAL_LINKS_TYPE, ExternalLinkType.LINK.toString())
|
||||
put(ProviderTableMeta.EXTERNAL_LINKS_NAME, EXTERNAL_LINK_NAME)
|
||||
put(ProviderTableMeta.EXTERNAL_LINKS_URL, EXTERNAL_LINK_URL)
|
||||
put(ProviderTableMeta.EXTERNAL_LINKS_REDIRECT, false)
|
||||
}
|
||||
|
||||
val uri = targetContext.contentResolver.insert(ProviderTableMeta.CONTENT_URI_EXTERNAL_LINKS, values)
|
||||
return ContentUris.parseId(requireNotNull(uri) { "External link could not be stored" }).toInt()
|
||||
}
|
||||
|
||||
private fun deleteExternalLink(linkId: Int) {
|
||||
targetContext.contentResolver.delete(
|
||||
ProviderTableMeta.CONTENT_URI_EXTERNAL_LINKS,
|
||||
"${ProviderTableMeta._ID} = ?",
|
||||
arrayOf(linkId.toString())
|
||||
)
|
||||
onView(ViewMatchers.withId(R.id.switch_account_button)).perform(ViewActions.click())
|
||||
onView(ViewMatchers.withText(account1?.name)).perform(ViewActions.click())
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val MENU_ITEM_EXTERNAL_LINK = 111
|
||||
private const val LEGACY_EXTERNAL_LINK_RANGE = 100
|
||||
|
||||
private const val EXTERNAL_LINK_ID = 501
|
||||
private const val EXTERNAL_LINK_NAME = "High ID Test"
|
||||
private const val EXTERNAL_LINK_URL = "https://nextcloud.com"
|
||||
|
||||
private const val WAIT_TIMEOUT_MILLIS = 5_000L
|
||||
private const val WAIT_POLL_INTERVAL_MILLIS = 100L
|
||||
|
||||
private const val SERVER_VERSION = "14.0.0.0"
|
||||
|
||||
private lateinit var account1: Account
|
||||
private lateinit var account2: Account
|
||||
private lateinit var account2Name: String
|
||||
private lateinit var account2DisplayName: String
|
||||
private var account1: Account? = null
|
||||
private var user1: User? = null
|
||||
private var account2: Account? = null
|
||||
private var account2Name: String? = null
|
||||
private var account2DisplayName: String? = null
|
||||
|
||||
@JvmStatic
|
||||
@BeforeClass
|
||||
fun beforeClass() {
|
||||
val baseUrl = Uri.parse(InstrumentationRegistry.getArguments().getString("TEST_SERVER_URL"))
|
||||
val arguments = InstrumentationRegistry.getArguments()
|
||||
val baseUrl = Uri.parse(arguments.getString("TEST_SERVER_URL"))
|
||||
|
||||
val platformAccountManager = AccountManager.get(targetContext)
|
||||
val userAccountManager: UserAccountManager = UserAccountManagerImpl.fromContext(targetContext)
|
||||
|
||||
platformAccountManager.accounts.forEach(platformAccountManager::removeAccountExplicitly)
|
||||
|
||||
account1 = addAccount(platformAccountManager, "user1", baseUrl)
|
||||
account2 = addAccount(platformAccountManager, "user2", baseUrl)
|
||||
account2Name = account2.name
|
||||
account2DisplayName = "User Two@$baseUrl"
|
||||
}
|
||||
|
||||
private fun addAccount(platformAccountManager: AccountManager, loginName: String, baseUrl: Uri): Account {
|
||||
val accountName = "$loginName@$baseUrl"
|
||||
val account = Account(accountName, MainApp.getAccountType(targetContext))
|
||||
|
||||
platformAccountManager.run {
|
||||
addAccountExplicitly(account, loginName, null)
|
||||
setUserData(
|
||||
account,
|
||||
AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION,
|
||||
UserAccountManager.ACCOUNT_VERSION.toString()
|
||||
)
|
||||
setUserData(account, AccountUtils.Constants.KEY_OC_VERSION, SERVER_VERSION)
|
||||
setUserData(account, AccountUtils.Constants.KEY_OC_BASE_URL, baseUrl.toString())
|
||||
setUserData(account, AccountUtils.Constants.KEY_USER_ID, loginName)
|
||||
for (account in platformAccountManager.accounts) {
|
||||
platformAccountManager.removeAccountExplicitly(account)
|
||||
}
|
||||
|
||||
return requireNotNull(UserAccountManagerImpl.fromContext(targetContext).getAccountByName(accountName))
|
||||
var loginName = "user1"
|
||||
var password = "user1"
|
||||
|
||||
var temp = Account("$loginName@$baseUrl", MainApp.getAccountType(targetContext))
|
||||
platformAccountManager.addAccountExplicitly(temp, password, null)
|
||||
platformAccountManager.setUserData(
|
||||
temp,
|
||||
AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION,
|
||||
UserAccountManager.ACCOUNT_VERSION.toString()
|
||||
)
|
||||
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_VERSION, "14.0.0.0")
|
||||
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_BASE_URL, baseUrl.toString())
|
||||
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_USER_ID, loginName) // same as userId
|
||||
|
||||
account1 = userAccountManager.getAccountByName("$loginName@$baseUrl")
|
||||
user1 = userAccountManager.getUser(account1!!.name)
|
||||
.orElseThrow<IllegalAccessError?>(Supplier { IllegalAccessError() })
|
||||
|
||||
loginName = "user2"
|
||||
password = "user2"
|
||||
|
||||
temp = Account("$loginName@$baseUrl", MainApp.getAccountType(targetContext))
|
||||
platformAccountManager.addAccountExplicitly(temp, password, null)
|
||||
platformAccountManager.setUserData(
|
||||
temp,
|
||||
AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION,
|
||||
UserAccountManager.ACCOUNT_VERSION.toString()
|
||||
)
|
||||
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_VERSION, "14.0.0.0")
|
||||
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_BASE_URL, baseUrl.toString())
|
||||
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_USER_ID, loginName) // same as userId
|
||||
|
||||
account2 = userAccountManager.getAccountByName("$loginName@$baseUrl")
|
||||
account2Name = "$loginName@$baseUrl"
|
||||
account2DisplayName = "User Two@$baseUrl"
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -31,6 +31,7 @@ import javax.inject.Provider
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
@Suppress("TooManyFunctions")
|
||||
class UnifiedSearchListAdapterIT : AbstractIT() {
|
||||
|
||||
private val testClassName = "com.owncloud.android.ui.adapter.UnifiedSearchListAdapterIT"
|
||||
@@ -141,7 +142,7 @@ class UnifiedSearchListAdapterIT : AbstractIT() {
|
||||
fileThumbnailGenerator = FileThumbnailGenerator(
|
||||
storageManager = Provider { sut.storageManager },
|
||||
preferences = preferences,
|
||||
viewThemeUtils = Provider { sut.viewThemeUtils },
|
||||
viewThemeUtils = sut.viewThemeUtils,
|
||||
context = targetContext,
|
||||
accountManager = accountManager
|
||||
),
|
||||
|
||||
@@ -38,15 +38,15 @@ import com.nextcloud.client.account.RegisteredUser
|
||||
import com.nextcloud.client.account.Server
|
||||
import com.nextcloud.client.device.DeviceInfo
|
||||
import com.nextcloud.client.documentscan.AppScanOptionalFeature
|
||||
import com.nextcloud.ui.dialog.account.ChooseAccountDialogFragment
|
||||
import com.nextcloud.ui.dialog.account.ChooseAccountDialogFragment.Companion.newInstance
|
||||
import com.nextcloud.ui.dialog.account.onlineStatus.SetOnlineStatusBottomSheet
|
||||
import com.nextcloud.ui.ChooseAccountDialogFragment
|
||||
import com.nextcloud.ui.ChooseAccountDialogFragment.Companion.newInstance
|
||||
import com.nextcloud.ui.SetOnlineStatusBottomSheet
|
||||
import com.nextcloud.ui.fileactions.FileActionsBottomSheet.Companion.newInstance
|
||||
import com.nextcloud.utils.EditorUtils
|
||||
import com.owncloud.android.AbstractIT
|
||||
import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.authentication.server.EnforcedServer
|
||||
import com.owncloud.android.authentication.EnforcedServer
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProvider
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProviderImpl
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
@@ -78,6 +78,7 @@ import org.junit.Test
|
||||
import java.net.URI
|
||||
import java.util.function.Supplier
|
||||
|
||||
@Suppress("TooManyFunctions")
|
||||
class DialogFragmentIT : AbstractIT() {
|
||||
private val testClassName = "com.owncloud.android.ui.dialog.DialogFragmentIT"
|
||||
private val serverUrl = "https://nextcloud.localhost"
|
||||
@@ -611,8 +612,7 @@ class DialogFragmentIT : AbstractIT() {
|
||||
fda,
|
||||
user,
|
||||
hoverCard,
|
||||
fda.viewThemeUtils,
|
||||
fda.avatarGenerator
|
||||
fda.viewThemeUtils
|
||||
)
|
||||
sut.show()
|
||||
}
|
||||
|
||||
@@ -16,12 +16,12 @@ import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
|
||||
import androidx.test.espresso.matcher.ViewMatchers.isRoot
|
||||
import androidx.test.espresso.matcher.ViewMatchers.withId
|
||||
import com.nextcloud.test.TestActivity
|
||||
import com.nextcloud.utils.view.ScreenMetrics
|
||||
import com.owncloud.android.AbstractIT
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.lib.resources.users.StatusType
|
||||
import com.owncloud.android.ui.TextDrawable
|
||||
import com.owncloud.android.utils.BitmapUtils
|
||||
import com.owncloud.android.utils.DisplayUtils
|
||||
import com.owncloud.android.utils.ScreenshotTest
|
||||
import org.junit.Test
|
||||
|
||||
@@ -42,7 +42,7 @@ class AvatarIT : AbstractIT() {
|
||||
|
||||
scenario.onActivity { sut ->
|
||||
val avatarRadius = targetContext.resources.getDimension(R.dimen.list_item_avatar_icon_radius)
|
||||
val width = ScreenMetrics.dpToPx(2 * avatarRadius, targetContext)
|
||||
val width = DisplayUtils.convertDpToPixel(2 * avatarRadius, targetContext)
|
||||
val fragment = sut.supportFragmentManager.fragments.last() as AvatarTestFragment
|
||||
|
||||
fragment.run {
|
||||
@@ -79,7 +79,7 @@ class AvatarIT : AbstractIT() {
|
||||
|
||||
scenario.onActivity { sut ->
|
||||
val avatarRadius = targetContext.resources.getDimension(R.dimen.list_item_avatar_icon_radius)
|
||||
val width = ScreenMetrics.dpToPx(2 * avatarRadius, targetContext)
|
||||
val width = DisplayUtils.convertDpToPixel(2 * avatarRadius, targetContext)
|
||||
|
||||
val paulette = BitmapFactory.decodeFile(getFile("paulette.jpg").absolutePath)
|
||||
val christine = BitmapFactory.decodeFile(getFile("christine.jpg").absolutePath)
|
||||
|
||||
+4
-4
@@ -155,7 +155,7 @@ class FileDetailFragmentStaticServerIT : AbstractIT() {
|
||||
val fragment = FileDetailFragment.newInstance(oCFile, user, 0)
|
||||
sut.addFragment(fragment)
|
||||
sut.supportFragmentManager.executePendingTransactions()
|
||||
fragment.fileDetailActivitiesFragment?.populateList(activities as List<Any>?, true)
|
||||
fragment.fileDetailActivitiesFragment.populateList(activities as List<Any>?, true)
|
||||
}
|
||||
|
||||
val screenShotName = createName(testClassName + "_" + "showDetailsActivities", "")
|
||||
@@ -174,7 +174,7 @@ class FileDetailFragmentStaticServerIT : AbstractIT() {
|
||||
val fragment = FileDetailFragment.newInstance(oCFile, user, 0)
|
||||
sut.addFragment(fragment)
|
||||
activity.supportFragmentManager.executePendingTransactions()
|
||||
fragment.fileDetailActivitiesFragment?.populateList(emptyList(), true)
|
||||
fragment.fileDetailActivitiesFragment.populateList(emptyList(), true)
|
||||
}
|
||||
|
||||
val screenShotName = createName(testClassName + "_" + "showDetailsActivitiesNone", "")
|
||||
@@ -193,8 +193,8 @@ class FileDetailFragmentStaticServerIT : AbstractIT() {
|
||||
val fragment = FileDetailFragment.newInstance(oCFile, user, 0)
|
||||
sut.addFragment(fragment)
|
||||
sut.supportFragmentManager.executePendingTransactions()
|
||||
fragment.fileDetailActivitiesFragment?.disableLoadingActivities()
|
||||
fragment.fileDetailActivitiesFragment?.setErrorContent(
|
||||
fragment.fileDetailActivitiesFragment.disableLoadingActivities()
|
||||
fragment.fileDetailActivitiesFragment.setErrorContent(
|
||||
targetContext.resources.getString(R.string.file_detail_activity_error)
|
||||
)
|
||||
}
|
||||
|
||||
+1
@@ -58,6 +58,7 @@ import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
|
||||
@Suppress("TooManyFunctions")
|
||||
class FileDetailSharingFragmentIT : AbstractIT() {
|
||||
private val testClassName = "com.owncloud.android.ui.fragment.FileDetailSharingFragmentIT"
|
||||
|
||||
|
||||
@@ -151,6 +151,7 @@ class GalleryFragmentIT : AbstractIT() {
|
||||
}
|
||||
|
||||
/** Recursively walk view tree to find the first RecyclerView. Runs on the same thread that calls it. */
|
||||
@Suppress("ReturnCount")
|
||||
private fun findRecyclerViewRecursively(root: View?): RecyclerView? {
|
||||
if (root == null) return null
|
||||
if (root is RecyclerView) return root
|
||||
|
||||
@@ -115,6 +115,7 @@ class NotificationsFragmentIT : AbstractIT() {
|
||||
add(buildNotificationManyActions())
|
||||
}
|
||||
|
||||
@Suppress("ReturnCount")
|
||||
private fun findFragment(sut: NavigatorActivity): NotificationsFragment? {
|
||||
val allFragments = sut.supportFragmentManager.fragments
|
||||
for (f in allFragments) {
|
||||
|
||||
Loaded 100 of 786 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user