Compare commits

..
Author SHA1 Message Date
tobiasKaminsky 124892e96d use gradle-cache
Signed-off-by: tobiasKaminsky <[email protected]>
2026-09-08 08:59:32 +02:00
tobiasKaminsky e31e891e6e use gradle-cache
Signed-off-by: tobiasKaminsky <[email protected]>
2026-09-08 08:54:38 +02:00
Marcel Müller 87797fac2a try cache 2026-09-04 16:21:13 +02:00
Marcel Müller 4372bf87ea format document 2026-09-04 15:57:41 +02:00
Marcel Müller 4ce89d6e58 use 10GB on max 2026-09-04 15:57:20 +02:00
Marcel Müller a49a6affd6 Also upload hidden files 2026-09-04 15:56:53 +02:00
tobiasKaminsky 0f06a59f3a wip
Signed-off-by: tobiasKaminsky <[email protected]>
2026-09-04 08:54:25 +02:00
tobiasKaminsky 3f2a31b196 wip
Signed-off-by: tobiasKaminsky <[email protected]>
2026-09-04 08:19:06 +02:00
tobiasKaminsky ad48bd94ef CI: first build, then assemble
Signed-off-by: tobiasKaminsky <[email protected]>
2026-09-03 10:08:34 +02:00
tobiasKaminsky c106507a0e CI: first build, then assemble
Signed-off-by: tobiasKaminsky <[email protected]>
2026-09-03 09:44:23 +02:00
1011 changed files with 40254 additions and 54643 deletions

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.
@@ -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.
+5
View File
@@ -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 -1
View File
@@ -1,4 +1,4 @@
FROM ubuntu:resolute@sha256:6a06111c3b0a8600feadb270aec771dc239bf407b25625f93f44ab00e11f4d3c
FROM ubuntu:resolute@sha256:2260313b31c8c011cd2eebe728008efac1b3982be73eb71348ea2648d2c0e09b
ARG DEBIAN_FRONTEND=noninteractive
ENV ANDROID_HOME=/usr/lib/android-sdk
Binary file not shown.
@@ -1,2 +0,0 @@
SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
SPDX-License-Identifier: AGPL-3.0-or-later
-179
View File
@@ -1,179 +0,0 @@
# This workflow is provided via the organization template repository
#
# https://github.com/nextcloud/.github
# https://docs.github.com/en/actions/learn-github-actions/sharing-workflows-with-your-organization
#
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
# SPDX-License-Identifier: MIT
name: AI Policy
on:
pull_request:
types: [opened, synchronize, reopened]
branches: [master, main]
permissions:
contents: read
# Required to add the "AI assisted" label via `gh pr edit --add-label`
pull-requests: write
# Required to create the "AI assisted" label via the REST labels endpoint
# (labels are an issues-scoped resource in the GitHub API)
issues: write
concurrency:
group: ai-policy-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
check-ai-trailers:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- name: Collect PR commit messages
id: collect
env:
BASE_REF: ${{ github.base_ref }}
run: |
set -euo pipefail
git fetch origin "${BASE_REF}"
MERGE_BASE=$(git merge-base "origin/${BASE_REF}" HEAD)
git log --format="%B" "${MERGE_BASE}..HEAD" > /tmp/pr_commits.txt
echo "--- PR commit messages ---"
cat /tmp/pr_commits.txt
echo "--------------------------"
- name: Define shared agent detection patterns
run: |
set -euo pipefail
# Email addresses known to be used by coding agents.
# These should never appear in Signed-off-by because the DCO can only be attested by a human.
EMAIL_PATTERN="copilot@github\.com\
|noreply@anthropic\.com\
|devin@cognition\.ai\
|devin@cognition-labs\.com\
|aider@aider\.chat\
|noreply@aider\.chat\
|codex@openai\.com\
|cursor@anysphere\.com\
|windsurf@codeium\.com\
|codeium@codeium\.com\
|amazon-q@amazon\.com\
|codewhisperer@amazon\.com\
|gemini-code-assist@google\.com\
|openhands@all-hands\.dev\
|swe-agent@princeton\.edu"
# Strip embedded whitespace (used above only for readability)
EMAIL_PATTERN=$(echo "$EMAIL_PATTERN" | tr -d ' \n')
echo "AGENT_EMAIL_PATTERN=${EMAIL_PATTERN}" >> "$GITHUB_ENV"
# Display-name prefixes used by known coding agents (shared by Signed-off-by and Co-Authored-By checks)
# shellcheck disable=SC2016
echo 'AGENT_NAMES=GitHub Copilot|Claude( [A-Za-z0-9. -]+)?|Devin( AI)?|aider( \(.*\))?|OpenAI Codex|Cursor( AI)?|Windsurf|Amazon Q|CodeWhisperer|Gemini Code Assist|OpenHands|SWE-agent|AutoCodeRover|Tabnine' >> "$GITHUB_ENV"
- name: Check for AI-assistant / Assisted-by trailers
id: ai_trailers
run: |
set -euo pipefail
AI_ASSISTED=false
if grep -qiE '^(AI-assistant|Assisted-by):' /tmp/pr_commits.txt; then
AI_ASSISTED=true
echo "Found AI-assistant/Assisted-by trailer(s):"
grep -iE '^(AI-assistant|Assisted-by):' /tmp/pr_commits.txt
fi
echo "ai_assisted=${AI_ASSISTED}" >> "$GITHUB_OUTPUT"
- name: Check for coding-agent Signed-off-by trailers
id: agent_signoff
run: |
set -euo pipefail
EMAIL_HITS=$(grep -iE "^Signed-off-by:.*<(${AGENT_EMAIL_PATTERN})>" /tmp/pr_commits.txt 2>/dev/null || true)
NAME_HITS=$(grep -iE "^Signed-off-by: *(${AGENT_NAMES}) *[<(]" /tmp/pr_commits.txt 2>/dev/null || true)
AGENT_LINES=$(printf '%s\n%s' "$EMAIL_HITS" "$NAME_HITS" | sort -u | sed '/^[[:space:]]*$/d')
AGENT_SIGNOFF=false
if [ -n "$AGENT_LINES" ]; then
AGENT_SIGNOFF=true
fi
echo "agent_signoff=${AGENT_SIGNOFF}" >> "$GITHUB_OUTPUT"
{
echo "agent_lines<<AGENT_EOF"
echo "${AGENT_LINES}"
echo "AGENT_EOF"
} >> "$GITHUB_OUTPUT"
- name: Check for coding-agent Co-Authored-By trailers
id: co_authored
run: |
set -euo pipefail
EMAIL_HITS=$(grep -iE "^Co-Authored-By:.*<(${AGENT_EMAIL_PATTERN})>" /tmp/pr_commits.txt 2>/dev/null || true)
NAME_HITS=$(grep -iE "^Co-Authored-By: *(${AGENT_NAMES}) *[<(]" /tmp/pr_commits.txt 2>/dev/null || true)
CO_AUTHORED=false
if [ -n "$EMAIL_HITS" ] || [ -n "$NAME_HITS" ]; then
CO_AUTHORED=true
echo "Found coding-agent Co-Authored-By trailer(s):"
printf '%s\n%s' "$EMAIL_HITS" "$NAME_HITS" | sort -u | sed '/^[[:space:]]*$/d'
fi
echo "co_authored=${CO_AUTHORED}" >> "$GITHUB_OUTPUT"
- name: Create 'AI assisted' label if absent
if: steps.ai_trailers.outputs.ai_assisted == 'true' || steps.agent_signoff.outputs.agent_signoff == 'true' || steps.co_authored.outputs.co_authored == 'true'
env:
GH_TOKEN: ${{ github.token }}
run: |
gh api "repos/${{ github.repository }}/labels" \
--method POST \
-f name="AI assisted" \
-f color="d93f0b" \
-f description="This PR contains AI-assisted commits" \
2>/dev/null || true
- name: Label PR as AI assisted
if: steps.ai_trailers.outputs.ai_assisted == 'true' || steps.agent_signoff.outputs.agent_signoff == 'true' || steps.co_authored.outputs.co_authored == 'true'
env:
GH_TOKEN: ${{ github.token }}
run: |
gh pr edit "${{ github.event.pull_request.number }}" \
--repo "${{ github.repository }}" \
--add-label "AI assisted"
echo "Added 'AI assisted' label to PR #${{ github.event.pull_request.number }}"
- name: Fail on coding-agent Signed-off-by
if: steps.agent_signoff.outputs.agent_signoff == 'true'
env:
AGENT_LINES: ${{ steps.agent_signoff.outputs.agent_lines }}
AGENTS_MD_URL: https://github.com/${{ github.repository }}/blob/${{ github.base_ref }}/AGENTS.md
run: |
echo "::error title=Coding-agent sign-off detected::A Signed-off-by trailer from a known coding agent was found in one or more commits."
echo ""
echo "Offending trailer(s):"
echo "${AGENT_LINES}"
echo ""
echo "The 'Signed-off-by' trailer represents the Developer Certificate of Origin (DCO)"
echo "and must only be attested by a human contributor."
echo "Please amend the affected commit(s) to remove the coding-agent sign-off"
echo "and replace it with an 'Assisted-by' trailer, for example:"
echo ""
echo " Assisted-by: Claude Code:claude-sonnet-4-6"
echo ""
echo "References:"
echo " • AGENTS.md (this repository)"
echo " ${AGENTS_MD_URL}"
echo " • AI Contribution Policy"
echo " https://github.com/nextcloud/.github/blob/master/AI_POLICY.md"
echo " • Contribution Guidelines"
echo " https://github.com/nextcloud/.github/blob/master/CONTRIBUTING.md"
exit 1
-76
View File
@@ -1,76 +0,0 @@
# synced from @nextcloud/android-config
# SPDX-FileCopyrightText: 2023-2024 Nextcloud GmbH and Nextcloud contributors
# SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
# SPDX-FileCopyrightText: 2023 Tobias Kaminsky <[email protected]>
# SPDX-FileCopyrightText: 2023 Andy Scherzinger <[email protected]>
# SPDX-FileCopyrightText: 2023 Josh Richards <[email protected]>
# SPDX-FileCopyrightText: 2025 Marcel Hibbe <[email protected]>
# SPDX-License-Identifier: GPL-3.0-or-later
name: "Analysis"
on:
pull_request:
branches: [ "master", "main", "stable-*" ]
push:
branches: [ "master", "main", "stable-*" ]
permissions:
pull-requests: write
contents: write
concurrency:
group: analysis-wrapper-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
analysis:
runs-on: ubuntu-latest-max
steps:
- name: Disabled on forks
if: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }}
run: |
echo 'Can not analyze PRs from forks'
exit 1
- name: Setup variables # zizmor: ignore[template-injection]
id: get-vars
run: |
if [ -z "$GITHUB_HEAD_REF" ]; then
# push
{
echo "branch=$GITHUB_REF_NAME"
echo "pr=$GITHUB_RUN_ID"
echo "repo=${{ github.repository }}"
} >> "$GITHUB_OUTPUT"
else
# pull request
{
echo "branch=$GITHUB_HEAD_REF"
echo "pr=${{ github.event.pull_request.number }}"
echo "repo=${{ github.event.pull_request.head.repo.full_name }}"
} >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
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
with:
distribution: "temurin"
java-version: 25
- name: Install dependencies
run: |
sudo apt install python3-defusedxml
- name: Run analysis wrapper
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
mkdir -p "$HOME/.gradle"
{
echo "org.gradle.jvmargs=-Xmx6g -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 }}"
+46 -29
View File
@@ -5,9 +5,7 @@ name: "Assemble"
on:
pull_request:
branches: [ master, stable-* ]
push:
branches: [ master ]
branches: [master, stable-*]
# Declare default permissions as read only.
permissions: read-all
@@ -17,35 +15,54 @@ concurrency:
cancel-in-progress: true
jobs:
compile:
runs-on: ubuntu-latest-max
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: set up JDK 21
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
with:
distribution: "temurin"
java-version: 21
- name: compile
run: |
echo "org.gradle.dependency.verification=lenient" >> gradle.properties
echo "org.gradle.jvmargs=-Xmx10g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" >> gradle.properties
echo "org.gradle.caching=true" >> gradle.properties
echo "org.gradle.parallel=true" >> gradle.properties
echo "org.gradle.configureondemand=true" >> gradle.properties
- uses: gradle/actions/wrapper-validation@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
- name: Gradle Cache
uses: burrunan/gradle-cache-action@404534c34a2faa40430357a3183522a845b04f3b # v3.0.3
with:
job-id: assemble
arguments: assembleGeneric
flavor:
name: flavor (${{ matrix.flavor }})
runs-on: ubuntu-latest
needs: [compile]
strategy:
fail-fast: false
matrix:
include:
- flavor: Generic
tasks: assembleGenericDebug
- flavor: Gplay
tasks: assembleGplayDebug assembleGplayRelease
- flavor: Huawei
tasks: assembleHuaweiDebug
flavor: [Generic, Gplay, Huawei]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: set up JDK 21
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
with:
distribution: "temurin"
java-version: 21
- uses: gradle/actions/wrapper-validation@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1
- name: Setup Gradle
uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1
- name: Build ${{ matrix.flavor }}
run: |
{
echo "org.gradle.jvmargs=-Xmx4g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=768m"
echo "kotlin.daemon.jvmargs=-Xmx3g -XX:+UseParallelGC -XX:MaxMetaspaceSize=512m"
echo "org.gradle.workers.max=2"
} >> gradle.properties
./gradlew ${{ matrix.tasks }}
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: set up JDK 21
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
with:
distribution: "temurin"
java-version: 21
- uses: gradle/actions/wrapper-validation@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
- name: compile
run: |
echo "org.gradle.dependency.verification=lenient" >> gradle.properties
echo "org.gradle.jvmargs=-Xmx10g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" >> gradle.properties
echo "org.gradle.caching=true" >> gradle.properties
echo "org.gradle.parallel=true" >> gradle.properties
echo "org.gradle.configureondemand=true" >> gradle.properties
- uses: gradle/actions/wrapper-validation@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
- name: Gradle Cache
uses: burrunan/gradle-cache-action@404534c34a2faa40430357a3183522a845b04f3b # v3.0.3
with:
job-id: assemble
arguments: assemble${{ matrix.flavor }}
-40
View File
@@ -1,40 +0,0 @@
# synced from @nextcloud/android-config
# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors
# SPDX-FileCopyrightText: 2023 Álvaro Brey <[email protected]>
# SPDX-License-Identifier: GPL-3.0-or-later
name: Auto approve sync
on:
pull_request_target: # zizmor: ignore[dangerous-triggers]
branches:
- master
- main
types:
- opened
- reopened
- synchronize
- labeled
concurrency:
group: sync-approve-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
permissions:
pull-requests: write
jobs:
auto-approve:
name: Auto approve sync
runs-on: ubuntu-latest-low
if: ${{ contains(github.event.pull_request.labels.*.name, 'sync') && github.actor == 'nextcloud-android-bot' }}
steps:
- name: Disabled on forks
if: ${{ github.event.pull_request.head.repo.full_name != github.repository }}
run: |
echo 'Can not approve PRs from forks'
exit 1
- uses: hmarr/auto-approve-action@f0939ea97e9205ef24d872e76833fa908a770363 # v4.0.0
with:
github-token: "${{ secrets.GITHUB_TOKEN }}"
-36
View File
@@ -1,36 +0,0 @@
# SPDX-FileCopyrightText: 2020-2024 Nextcloud GmbH and Nextcloud contributors
# SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
name: Check
on:
pull_request:
branches: [ master, stable-* ]
push:
branches: [ master ]
# Declare default permissions as read only.
permissions: read-all
concurrency:
group: check-kotlin-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
check:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
task: [ detekt, spotlessKotlinCheck, lint ]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Set up JDK 21
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
with:
distribution: "temurin"
java-version: 21
- name: Setup Gradle
uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1
- name: Check ${{ matrix.task }}
run: ./gradlew ${{ matrix.task }}
-66
View File
@@ -1,66 +0,0 @@
# 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]>
# SPDX-FileCopyrightText: 2025 Marcel Hibbe <[email protected]>
# SPDX-License-Identifier: GPL-3.0-or-later
name: "CodeQL"
on:
push:
branches: [ "master", "main", "stable-*" ]
pull_request:
branches: [ "master", "main" ]
schedule:
- cron: '24 18 * * 3'
permissions:
contents: read
concurrency:
group: codeql-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest-max
timeout-minutes: 90
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'java' ]
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Set Swap Space
if: runner.environment == 'github-hosted'
uses: pierotofy/set-swap-space@49819abfb41bd9b44fb781159c033dba90353a7c # v1.0
with:
swap-size-gb: 10
- name: Initialize CodeQL
uses: github/codeql-action/init@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2
with:
languages: ${{ matrix.language }}
- name: Set up JDK 21
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
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
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2
-86
View File
@@ -1,86 +0,0 @@
#!/bin/sh
# Nextcloud Android Library
#
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
# SPDX-License-Identifier: MIT
#
if [ $1 = "master" ]; then
SERVER_VERSION_MAIN="main"
SERVER_VERSION_MASTER="master"
else
SERVER_VERSION_MAIN=$1
SERVER_VERSION_MASTER=$1
fi
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
. ~/.bashrc; nvm install node
php /var/www/html/occ log:manage --level warning
OC_PASS=user1 php /var/www/html/occ user:add --password-from-env --display-name='User One' user1
OC_PASS=user2 php /var/www/html/occ user:add --password-from-env --display-name='User Two' user2
OC_PASS=user3 php /var/www/html/occ user:add --password-from-env --display-name='User Three' user3
OC_PASS=test php /var/www/html/occ user:add --password-from-env --display-name='Test@Test' test@test
OC_PASS=test php /var/www/html/occ user:add --password-from-env --display-name='Test Spaces' 'test test'
php /var/www/html/occ user:setting user2 files quota 1G
php /var/www/html/occ group:add users
php /var/www/html/occ group:adduser users user1
php /var/www/html/occ group:adduser users user2
php /var/www/html/occ group:adduser users test
git clone --depth=1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/activity.git /var/www/html/apps/activity/
php /var/www/html/occ app:enable -f activity
git clone --depth=1 -b $SERVER_VERSION_MAIN https://github.com/nextcloud/text.git /var/www/html/apps/text/
php /var/www/html/occ app:enable -f text
git clone --depth=1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/end_to_end_encryption.git /var/www/html/apps/end_to_end_encryption/
php /var/www/html/occ app:enable -f end_to_end_encryption
git clone --depth=1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/password_policy.git /var/www/html/apps/password_policy/
php /var/www/html/occ app:enable -f password_policy
git clone --depth=1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/external.git /var/www/html/apps/external/
cd /var/www/html/apps/external; composer install --no-dev
php /var/www/html/occ app:enable -f external
php /var/www/html/occ config:app:set external sites --value="{\"1\":{\"id\":1,\"name\":\"Nextcloud\",\"url\":\"https:\/\/www.nextcloud.com\",\"lang\":\"\",\"type\":\"link\",\"device\":\"\",\"icon\":\"external.svg\",\"groups\":[],\"redirect\":false},\"2\":{\"id\":2,\"name\":\"Forum\",\"url\":\"https:\/\/help.nextcloud.com\",\"lang\":\"\",\"type\":\"link\",\"device\":\"\",\"icon\":\"external.svg\",\"groups\":[],\"redirect\":false}}"
git clone --depth=1 -b $SERVER_VERSION_MAIN https://github.com/nextcloud/files_lock.git /var/www/html/apps/files_lock/
php /var/www/html/occ app:enable -f files_lock
git clone --depth=1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/notifications.git /var/www/html/apps/notifications/
cd /var/www/html/apps/notifications; composer install --no-dev
php /var/www/html/occ app:enable -f notifications
if [ $1 = 'stable22' ]; then
php /var/www/html/occ notification:generate test test
else
php /var/www/html/occ notification:generate test -d test
fi
git clone --depth=1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/photos.git /var/www/html/apps/photos/
cd /var/www/html/apps/photos; composer install --no-dev
php /var/www/html/occ app:enable -f photos
git clone --depth=1 -b $SERVER_VERSION_MAIN https://github.com/nextcloud/assistant.git /var/www/html/apps/assistant/
cd /var/www/html/apps/assistant; . ~/.bashrc; make
php /var/www/html/occ app:enable -f assistant
php /var/www/html/occ app:enable -f testing
git clone --depth 1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/files_downloadlimit.git /var/www/html/apps/files_downloadlimit/
php /var/www/html/occ app:enable -f files_downloadlimit
git clone --depth 1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/recommendations.git /var/www/html/apps/recommendations/
cd /var/www/html/apps/recommendations; composer install --no-dev
php /var/www/html/occ app:enable -f recommendations
git clone --depth 1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/viewer.git /var/www/html/apps/viewer/
php /var/www/html/occ app:enable -f viewer
php /var/www/html/occ config:system:set ratelimit.protection.enabled --value false --type bool
-20
View File
@@ -1,20 +0,0 @@
#!/bin/sh
# Nextcloud Android Library
#
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
# SPDX-License-Identifier: MIT
#
wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg
apt-get update && apt-get install -y composer
mkdir /var/www/.nvm /var/www/.npm
mkdir /var/www/.cache/
touch /var/www/.bashrc
chown -R 33:33 /var/www/.nvm /var/www/.npm /var/www/.bashrc /var/www/.cache
cd /var/www/html/
rm data -rf
rm config/config.php
su www-data -c "git reset --hard"
BRANCH="$1" /usr/local/bin/initnc.sh
-43
View File
@@ -1,43 +0,0 @@
# synced from @nextcloud/android-config
# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors
# SPDX-FileCopyrightText: 2023 Andy Scherzinger <[email protected]>
# SPDX-FileCopyrightText: 2022 Tobias Kaminsky <[email protected]>
# SPDX-FileCopyrightText: 2022 Álvaro Brey <[email protected]>
# SPDX-License-Identifier: GPL-3.0-or-later
name: "Detect new java files"
on:
pull_request:
branches: [ master, main, stable-* ]
permissions: read-all
concurrency:
group: detect-new-java-files-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
detectNewJavaFiles:
runs-on: ubuntu-latest-low
steps:
- id: file_changes
uses: trilom/file-changes-action@a6ca26c14274c33b15e6499323aac178af06ad4b # v1.2.4
with:
output: ','
- name: Detect new java files
run: |
if [ -z '${{ steps.file_changes.outputs.files_added }}' ]; then
echo "No new files added"
exit 0
fi
new_java=$(echo '${{ steps.file_changes.outputs.files_added }}' | tr ',' '\n' | grep '\.java$' | cat)
if [ -n "$new_java" ]; then
# shellcheck disable=SC2016
printf 'New java files detected:\n```\n%s\n```\n' "$new_java" | tee "$GITHUB_STEP_SUMMARY"
exit 1
else
echo "No new java files detected"
exit 0
fi
-30
View File
@@ -1,30 +0,0 @@
# SPDX-FileCopyrightText: 2023-2024 Nextcloud GmbH and Nextcloud contributors
# SPDX-FileCopyrightText: 2023 Tobias Kaminsky <[email protected]>
# SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
name: "Detect wrong settings"
on:
pull_request:
branches: [ master, stable-* ]
# Declare default permissions as read only.
permissions: read-all
concurrency:
group: detect-wrong-settings-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
detectWrongSettings:
runs-on: ubuntu-26.04
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Set up JDK 21
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
with:
distribution: "temurin"
java-version: 21
- name: Detect SNAPSHOT
run: scripts/analysis/detectWrongSettings.sh
-103
View File
@@ -1,103 +0,0 @@
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
# SPDX-License-Identifier: MIT
name: "Garm"
on:
pull_request:
branches: [ master, stable-* ]
permissions:
contents: read
pull-requests: write
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
test:
runs-on: ubuntu-26.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' }}
options: --name server
ports:
- 80:80
strategy:
fail-fast: false
matrix:
server: [ stable22, stable35, master ]
api-level: [ 29 ] # [ 21, 36 ]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: configure server
run: |
sudo apt-get update && sudo apt-get install unzip cpu-checker qemu-system-x86 --yes
sudo chmod 666 /dev/kvm
docker cp .github/workflows/configServer.sh server:/tmp/
docker exec server chmod +x /tmp/configServer.sh
docker exec server /tmp/configServer.sh ${{ matrix.server }}
docker cp .github/workflows/configNC.sh server:/tmp/
docker exec server chmod +x /tmp/configNC.sh
docker exec --user www-data server /tmp/configNC.sh ${{ matrix.server }}
docker exec server /usr/local/bin/run.sh
- name: set up JDK 21
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
with:
distribution: "temurin"
java-version: 21
- name: Configure gradle daemon
run: |
mkdir -p $HOME/.gradle
echo "org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" >> $HOME/.gradle/gradle.properties
echo "org.gradle.caching=true" >> $HOME/.gradle/gradle.properties
echo "org.gradle.parallel=true" >> $HOME/.gradle/gradle.properties
echo "org.gradle.configureondemand=true" >> $HOME/.gradle/gradle.properties
- name: Config gplay
run: |
sed -i s#http://server#http://10.0.2.2# gradle.properties
sed -i s'#<bool name="is_beta">false</bool>#<bool name="is_beta">true</bool>#'g app/src/main/res/values/setup.xml
- name: wait and ping server
run: |
while ! curl http://localhost/status.php 2>&1 | grep installed; do
echo "wait…"
sleep 5
done
- name: gplay
env:
GITHUB_TOKEN: ${{ secrets.GIT_TOKEN }}
uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d # v2.38.0
with:
api-level: ${{ matrix.api-level }}
cmake: 4.1.2
force-avd-creation: false
arch: x86_64
sdcard-path-or-size: 100M
ram-size: 4096M
heap-size: 512M
target: google_apis
emulator-options: -no-metrics -no-window -gpu swiftshader_indirect -no-snapshot -noaudio -no-boot-anim -skin 500x833
script: scripts/runCombinedTest.sh ${{github.event.number}} ${{ secrets.LOG_USERNAME }} ${{ secrets.LOG_PASSWORD }} ${{github.event.number}} ${{ matrix.server }}
- name: upload failing results
if: ${{ failure() }}
env:
LOG_USERNAME: ${{ secrets.LOG_USERNAME }}
LOG_PASSWORD: ${{ secrets.LOG_PASSWORD }}
GIT_USERNAME: ${{ secrets.GIT_USERNAME }}
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
if: ${{ always() }}
with:
name: Report-${{ matrix.server }}-${{ matrix.api-level }}
path: app/build/reports
retention-days: 4
-27
View File
@@ -1,27 +0,0 @@
#!/usr/bin/env bash
#
# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors
# SPDX-FileCopyrightText: 2022 Álvaro Brey <[email protected]>
# SPDX-License-Identifier: AGPL-3.0-or-later
#
## This file is intended to be sourced by other scripts
function err() {
echo >&2 "$@"
}
function curl_gh() {
if [[ -n "$GITHUB_TOKEN" ]]
then
curl \
--silent \
--header "Authorization: token $GITHUB_TOKEN" \
"$@"
else
err "WARNING: No GITHUB_TOKEN found. Skipping API call"
fi
}
-2
View File
@@ -1,2 +0,0 @@
SPDX-FileCopyrightText: 2019-2025 Nextcloud GmbH and Nextcloud contributors
SPDX-License-Identifier: AGPL-3.0-or-later
-39
View File
@@ -1,39 +0,0 @@
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
# SPDX-License-Identifier: MIT
name: Lint translation files
on:
pull_request:
branches: [ master, main, stable-* ]
push:
branches: [ master, main, stable-* ]
permissions:
contents: read
concurrency:
group: lint-php-cs-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
lint:
runs-on: ubuntu-latest-low
name: translations-string-xml
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check for new lines in translation strings
id: counter
run: |
grep -P '<string name' app/src/main/res/values/strings.xml | grep -vcP '</string>' | grep '^0$'
- name: Output
if: failure()
run: |
grep -P '<string name' app/src/main/res/values/strings.xml | grep -vP '</string>'
-55
View File
@@ -1,55 +0,0 @@
# This workflow is provided via the organization template repository
#
# https://github.com/nextcloud/.github
# https://docs.github.com/en/actions/learn-github-actions/sharing-workflows-with-your-organization
# SPDX-FileCopyrightText: 2023-2024 Nextcloud GmbH and Nextcloud contributors
# SPDX-FileCopyrightText: 2023 Marcel Klehr <[email protected]>
# SPDX-FileCopyrightText: 2023 Joas Schilling <[email protected]>
# SPDX-FileCopyrightText: 2023 Daniel Kesselberg <[email protected]>
# SPDX-FileCopyrightText: 2023 Florian Steffens <[email protected]>
# SPDX-License-Identifier: MIT
name: 'Ask for feedback on PRs'
on:
schedule:
- cron: '30 1 * * *'
permissions:
contents: read
pull-requests: write
jobs:
pr-feedback:
if: ${{ github.repository_owner == 'nextcloud' }}
runs-on: ubuntu-latest-low
steps:
- name: The get-github-handles-from-website action
uses: marcelklehr/get-github-handles-from-website-action@06b2239db0a48fe1484ba0bfd966a3ab81a08308 # v1.0.1
id: scrape
with:
website: 'https://nextcloud.com/team/'
- name: Get blocklist
id: blocklist
run: |
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
with:
feedback-message: |
Hello there,
Thank you so much for taking the time and effort to create a pull request to our Nextcloud project.
We hope that the review process is going smooth and is helpful for you. We want to ensure your pull request is reviewed to your satisfaction. If you have a moment, our community management team would very much appreciate your feedback on your experience with this PR review process.
Your feedback is valuable to us as we continuously strive to improve our community developer experience. Please take a moment to complete our short survey by clicking on the following link: https://cloud.nextcloud.com/apps/forms/s/i9Ago4EQRZ7TWxjfmeEpPkf6
Thank you for contributing to Nextcloud and we hope to hear from you soon!
(If you believe you should not receive this message, you can add yourself to the [blocklist](https://github.com/nextcloud/.github/blob/master/non-community-usernames.txt).)
days-before-feedback: 14
start-date: '2024-04-30'
exempt-authors: '${{ steps.blocklist.outputs.blocklist }},${{ steps.scrape.outputs.users }}'
exempt-bots: true
-116
View File
@@ -1,116 +0,0 @@
# 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"
on:
pull_request:
branches: [ main, master, stable-* ]
permissions:
pull-requests: write
contents: read
concurrency:
group: qa-build-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
qa:
runs-on: ubuntu-latest-max
steps:
- name: Check if secrets are available
run: echo "ok=${{ secrets.KS_PASS != '' }}" >> "$GITHUB_OUTPUT"
id: check-secrets
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
with:
persist-credentials: false
- name: set up JDK 21
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
with:
distribution: "temurin"
java-version: 25
- name: Build QA
id: build-qa
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
env:
KS_PASS: ${{ secrets.KS_PASS }}
KEY_PASS: ${{ secrets.KEY_PASS }}
LOG_USERNAME: ${{ secrets.LOG_USERNAME }}
LOG_PASSWORD: ${{ secrets.LOG_PASSWORD }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
mkdir -p "$HOME/.gradle"
{
echo "org.gradle.jvmargs=-Xmx3g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g"
echo "org.gradle.caching=true"
echo "org.gradle.parallel=true"
echo "org.gradle.configureondemand=true"
} > "$HOME/.gradle/gradle.properties"
[ -e app/build.gradle ] && sed -i "/qa/,/\}/ s/versionCode .*/versionCode ${{github.event.number}} /" "app/build.gradle"
[ -e app/build.gradle ] && sed -i "/qa/,/\}/ s/versionName .*/versionName \"${{github.event.number}}\"/" "app/build.gradle"
[ -e app/build.gradle.kts ] && sed -i "/qa/,/\}/ s/versionCode .*/versionCode = ${{github.event.number}} /" "app/build.gradle.kts"
[ -e app/build.gradle.kts ] && sed -i "/qa/,/\}/ s/versionName .*/versionName = \"${{github.event.number}}\"/" "app/build.gradle.kts"
./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"
- name: Upload APK
id: upload-apk
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f
with:
path: app/build/outputs/apk/qa/debug/*qa-debug*.apk
retention-days: 7
archive: false
- name: Create QR Code
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
env:
ARTIFACT_URL: ${{ steps.upload-apk.outputs.artifact-url }}
run: |
sudo apt-get -y install qrencode
qrencode -s 8 -o qr.png "$ARTIFACT_URL"
- name: Upload QR
id: upload-qr
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f
with:
path: qr.png
if-no-files-found: error
retention-days: 7
archive: false
- name: Comment PR
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
uses: thollander/actions-comment-pull-request@e4a76dd2b0a3c2027c3fd84147a67c22ee4c90fa
with:
comment-tag: qa-apk
mode: upsert
message: |
### :iphone: QA build
| | |
|---|---|
| **Download** | [${{ steps.build-qa.outputs.apk-name }}](${{ steps.upload-apk.outputs.artifact-url }}) |
| **QR code** | [Open the QR code for this download](${{ steps.upload-qr.outputs.artifact-url }}) |
| **Commit** | ${{ github.event.pull_request.head.sha }} |
| **Version** | `${{ github.event.number }}` |
| **Available until** | 7 days after this build |
The QA build installs alongside a released Nextcloud app, so you can keep
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.
@@ -1,61 +0,0 @@
# This workflow is provided via the organization template repository
#
# https://github.com/nextcloud/.github
# https://docs.github.com/en/actions/learn-github-actions/sharing-workflows-with-your-organization
#
# SPDX-FileCopyrightText: Nextcloud GmbH and Nextcloud contributors
# SPDX-License-Identifier: MIT
name: Auto approve renovate PRs
on:
pull_request_target: # zizmor: ignore[dangerous-triggers]
branches:
- main
- master
- stable*
permissions:
contents: read
concurrency:
group: renovate-approve-merge-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
auto-approve-merge:
if: github.event.pull_request.user.login == 'renovate[bot]'
runs-on: ubuntu-latest-low
permissions:
# for hmarr/auto-approve-action to approve PRs
pull-requests: write
steps:
- name: Disabled on forks
if: ${{ github.event.pull_request.head.repo.full_name != github.repository }}
run: |
echo 'Can not approve PRs from forks'
exit 1
- uses: mdecoleman/pr-branch-name@55795d86b4566d300d237883103f052125cc7508 # v3.0.0
id: branchname
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
# GitHub actions bot approve
- uses: hmarr/auto-approve-action@f0939ea97e9205ef24d872e76833fa908a770363 # v4.0.0
if: github.actor == 'renovate[bot]'
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.head_ref }}
# Enable GitHub auto merge
- name: Enable Pull Request Automerge
if: github.actor == 'renovate[bot]'
run: gh pr merge --merge --auto
env:
GH_TOKEN: ${{ secrets.AUTOMERGE }}
-27
View File
@@ -1,27 +0,0 @@
# This workflow is provided via the organization template repository
#
# https://github.com/nextcloud/.github
# https://docs.github.com/en/actions/learn-github-actions/sharing-workflows-with-your-organization
# SPDX-FileCopyrightText: 2022 Free Software Foundation Europe e.V. <https://fsfe.org>
#
# SPDX-License-Identifier: CC0-1.0
name: REUSE Compliance Check
on: [pull_request]
permissions:
contents: read
jobs:
reuse-compliance-check:
runs-on: ubuntu-latest-low
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: REUSE Compliance Check
uses: fsfe/reuse-action@676e2d560c9a403aa252096d99fcab3e1132b0f5 # v6.0.0
-47
View File
@@ -1,47 +0,0 @@
# synced from @nextcloud/android-config
# SPDX-FileCopyrightText: 2023-2024 Nextcloud GmbH and Nextcloud contributors
# SPDX-FileCopyrightText: 2023 Andy Scherzinger <[email protected]>
# SPDX-License-Identifier: GPL-3.0-or-later
name: Scorecard supply-chain security
on:
branch_protection_rule:
schedule:
- cron: '32 23 * * 4'
push:
branches: [ "main", "master" ]
# Declare default permissions as read only.
permissions: read-all
concurrency:
group: scorecard-supply-chain-security-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
analysis:
name: Scorecard analysis
runs-on: ubuntu-latest
permissions:
# Needed to upload the results to code-scanning dashboard.
security-events: write
steps:
- name: "Checkout code"
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: "Run analysis"
uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0
with:
results_file: results.sarif
results_format: sarif
publish_results: false
# Upload the results to GitHub's code scanning dashboard.
- name: "Upload to code-scanning"
uses: github/codeql-action/upload-sarif@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2
with:
sarif_file: results.sarif
-35
View File
@@ -1,35 +0,0 @@
# synced from @nextcloud/android-config
# SPDX-FileCopyrightText: 2023-2024 Nextcloud GmbH and Nextcloud contributors
# SPDX-FileCopyrightText: 2023 Tobias Kaminsky <[email protected]>
# SPDX-FileCopyrightText: 2022 Álvaro Brey <[email protected]>
# SPDX-License-Identifier: GPL-3.0-or-later
name: 'Close stale issues'
on:
schedule:
- cron: '0 0 * * *'
# Declare default permissions as read only.
permissions: read-all
jobs:
stale:
runs-on: ubuntu-latest-low
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0
with:
days-before-stale: 28
days-before-close: 14
days-before-pr-close: -1
only-labels: 'bug,needs info'
exempt-issue-labels: 'no-stale'
stale-issue-message: >-
This bug report did not receive an update in the last 4 weeks.
Please take a look again and update the issue with new details,
otherwise the issue will be automatically closed in 2 weeks. Thank you!
exempt-all-pr-milestones: true
labels-to-remove-when-unstale: 'needs info'
-64
View File
@@ -1,64 +0,0 @@
# SPDX-FileCopyrightText: 2022-2025 Nextcloud GmbH and contributors
# SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
name: Unit tests
on:
pull_request:
branches: [ master, stable-* ]
push:
branches: [ master, stable-* ]
permissions:
contents: read
pull-requests: write
concurrency:
group: unit-tests-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Set up JDK 21
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
with:
distribution: "temurin"
java-version: 21
- name: Delete old comments
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
if: ${{ always() }}
run: scripts/deleteOldComments.sh "test" "Unit" ${{github.event.number}}
- name: Setup Gradle
uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1
- name: Run unit tests with coverage
run: ./gradlew jacocoTestGplayDebugUnitTest
- name: Upload failing results
if: ${{ failure() }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: scripts/uploadReport.sh "${{ secrets.LOG_USERNAME }}" "${{ secrets.LOG_PASSWORD }}" ${{github.event.number}} "test" "Unit" ${{github.event.number}}
- name: Upload coverage to codecov
uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
with:
token: ${{ secrets.CODECOV_TOKEN }}
flags: unit
fail_ci_if_error: true
files: app/build/reports/jacoco/jacocoTestGplayDebugUnitTestReport/jacoco.xml
- name: Upload jacoco artifacts
if: ${{ failure() }}
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: test-results
path: app/build/reports/jacoco/jacocoTestGplayDebugUnitTestReport/html/
-44
View File
@@ -1,44 +0,0 @@
#!/usr/bin/env bash
#
# SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
# SPDX-FileCopyrightText: 2019-2022 Tobias Kaminsky <[email protected]>
# SPDX-License-Identifier: AGPL-3.0-or-later
#
#1: LOG_USERNAME
#2: LOG_PASSWORD
#3: DRONE_BUILD_NUMBER
#4: DRONE_PULL_REQUEST
PUBLIC_URL=https://www.kaminsky.me/nc-dev/android-artifacts
USER=$1
PASS=$2
BUILD=$3
PR=$4
GITHUB_TOKEN=$5
DAV_URL=https://nextcloud.kaminsky.me/remote.php/dav/files/$USER/android-artifacts/
source .github/workflows/lib.sh
REPO=$(cat scripts/repo)
if ! test -e app/build/outputs/apk/qa/debug/*qa-debug*.apk ; then
exit 1
fi
echo "Uploaded artifact to $DAV_URL/$BUILD.apk"
# delete all old comments, starting with "APK file:"
oldComments=$(curl_gh -X GET https://api.github.com/repos/nextcloud/$REPO/issues/$PR/comments | jq '.[] | (.id |tostring) + "|" + (.user.login | test("github-actions") | tostring) + "|" + (.body | test("APK file:.*") | tostring)' | grep "true|true" | tr -d "\"" | cut -f1 -d"|")
echo $oldComments | while read comment ; do
curl_gh -X DELETE https://api.github.com/repos/nextcloud/$REPO/issues/comments/$comment
done
sudo apt-get -y install qrencode
qrencode -o $PR.png "$PUBLIC_URL/$BUILD.apk"
curl -u $USER:$PASS -X PUT $DAV_URL/$BUILD.apk --upload-file app/build/outputs/apk/qa/debug/*qa-debug*.apk
curl -u $USER:$PASS -X PUT $DAV_URL/$BUILD.png --upload-file $PR.png
curl_gh -X POST https://api.github.com/repos/nextcloud/$REPO/issues/$PR/comments -d "{ \"body\" : \"APK file: $PUBLIC_URL/$BUILD.apk <br/><br/> ![qrcode]($PUBLIC_URL/$BUILD.png) <br/><br/>To test this change/fix you can simply download above APK file and install and test it in parallel to your existing Nextcloud app. \" }"
-1
View File
@@ -60,7 +60,6 @@ build
/gradle.properties
.attach_pid*
fastlane/Fastfile
fastlane/ruby
*.hprof
# NDK / C++
-18
View File
@@ -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.
+6 -3
View File
@@ -1,7 +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__), '.', 'Pluginfile')
plugins_path = File.join(File.dirname(__FILE__), 'fastlane', 'Pluginfile')
eval_gemfile(plugins_path) if File.exist?(plugins_path)
+45 -50
View File
@@ -8,8 +8,8 @@ GEM
artifactory (3.0.17)
atomos (0.1.3)
aws-eventstream (1.4.0)
aws-partitions (1.1290.0)
aws-sdk-core (3.257.0)
aws-partitions (1.1281.0)
aws-sdk-core (3.254.1)
aws-eventstream (~> 1, >= 1.3.0)
aws-partitions (~> 1, >= 1.992.0)
aws-sigv4 (~> 1.9)
@@ -17,12 +17,11 @@ GEM
bigdecimal
jmespath (~> 1, >= 1.6.1)
logger
rexml (~> 3.4, >= 3.4.2)
aws-sdk-kms (1.132.0)
aws-sdk-core (~> 3, >= 3.256.0)
aws-sdk-kms (1.130.0)
aws-sdk-core (~> 3, >= 3.254.0)
aws-sigv4 (~> 1.5)
aws-sdk-s3 (1.232.2)
aws-sdk-core (~> 3, >= 3.256.0)
aws-sdk-s3 (1.229.0)
aws-sdk-core (~> 3, >= 3.254.1)
aws-sdk-kms (~> 1)
aws-sigv4 (~> 1.5)
aws-sigv4 (1.12.1)
@@ -30,8 +29,8 @@ 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)
@@ -41,13 +40,12 @@ GEM
declarative (0.0.20)
digest-crc (0.7.0)
rake (>= 12.0.0, < 14.0.0)
domain_name (0.6.20260921)
domain_name (0.6.20240107)
dotenv (2.8.1)
emoji_regex (3.2.3)
erb (6.0.7)
excon (1.7.1)
logger
faraday (2.14.4)
excon (0.112.0)
faraday (2.14.3)
faraday-net_http (>= 2.0, < 3.5)
json
logger
@@ -58,12 +56,11 @@ GEM
faraday (>= 1, < 3)
faraday-multipart (1.2.0)
multipart-post (~> 2.0)
faraday-net_http (3.4.4)
net-http (~> 0.5)
faraday-net_http (2.1.0)
faraday-retry (2.4.0)
faraday (~> 2.0)
fastimage (2.4.1)
fastlane (2.240.1)
fastlane (2.238.0)
CFPropertyList (>= 2.3, < 5.0.0)
abbrev (~> 0.1)
addressable (>= 2.9.0, < 3.0.0)
@@ -73,7 +70,6 @@ GEM
base64 (~> 0.2)
benchmark (>= 0.1.0)
bundler (>= 2.4.0, < 5.0.0)
cgi (~> 0.4)
colored (~> 1.2)
commander (~> 4.6)
csv (~> 3.3)
@@ -88,11 +84,12 @@ GEM
fastimage (>= 2.1.0, < 3.0.0)
fastlane-sirp (>= 1.1.0)
gh_inspector (>= 1.1.2, < 2.0.0)
google-apis-androidpublisher_v3 (~> 0.99)
google-apis-androidpublisher_v3 (~> 0.3)
google-apis-playcustomapp_v1 (~> 0.1)
google-cloud-env (>= 1.6.0, < 2.4.0)
google-cloud-env (>= 1.6.0, < 2.3.0)
google-cloud-storage (~> 1.31)
highline (~> 2.0)
http-cookie (~> 1.0.5)
irb (>= 1.8)
json (< 3.0.0)
jwt (>= 2.10.3, < 4)
@@ -106,8 +103,8 @@ GEM
optparse (>= 0.1.1, < 1.0.0)
ostruct (>= 0.1.0)
plist (>= 3.1.0, < 4.0.0)
rubyzip (>= 3.4.0, < 4.0.0)
security (~> 0.3)
rubyzip (>= 2.0.0, < 3.0.0)
security (= 0.1.5)
simctl (~> 1.6.3)
terminal-notifier (>= 2.0.0, < 3.0.0)
terminal-table (~> 4)
@@ -117,29 +114,30 @@ 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.109.0)
google-apis-androidpublisher_v3 (0.106.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-core (1.2.5)
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.68.0)
google-apis-storage_v1 (0.66.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.3.1)
google-cloud-env (2.2.2)
base64 (~> 0.2)
faraday (>= 1.0, < 3.a)
google-cloud-errors (1.7.0)
@@ -153,7 +151,7 @@ GEM
googleauth (~> 1.9)
mini_mime (~> 1.0)
google-logging-utils (0.2.0)
googleauth (1.17.4)
googleauth (1.17.3)
faraday (>= 1.0, < 3.a)
google-cloud-env (~> 2.2)
google-logging-utils (~> 0.1)
@@ -162,9 +160,11 @@ GEM
pstore (~> 0.1)
signet (>= 0.16, < 2.a)
highline (2.0.3)
http-cookie (1.1.6)
http-cookie (1.0.8)
domain_name (~> 0.5)
io-console (0.9.4)
httpclient (2.9.0)
mutex_m
io-console (0.9.2)
irb (1.18.0)
pp (>= 0.6.0)
prism (>= 1.3.0)
@@ -172,18 +172,16 @@ 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)
mini_mime (1.1.5)
multi_json (1.21.2)
multi_json (1.21.1)
multipart-post (2.4.1)
mutex_m (0.3.0)
nanaimo (0.4.0)
naturally (2.3.0)
net-http (0.9.1)
uri (>= 0.11.1)
nkf (0.3.0)
optparse (0.8.1)
os (1.1.4)
@@ -194,9 +192,9 @@ GEM
prettyprint (0.2.0)
prism (1.9.0)
pstore (0.2.1)
public_suffix (7.0.5)
public_suffix (6.0.2)
rake (13.4.2)
rbs (4.2.0)
rbs (4.1.3)
logger
prism (>= 1.6.0)
tsort
@@ -207,15 +205,15 @@ GEM
tsort
reline (0.7.0)
io-console (~> 0.5)
representable (3.3.0)
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.3.0)
rubyzip (2.4.1)
security (0.1.5)
signet (0.22.0)
addressable (~> 2.8)
faraday (>= 0.17.5, < 3.a)
@@ -233,10 +231,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.1)
unicode-display_width (2.6.0)
word_wrap (1.0.0)
xcodeproj (1.28.1)
CFPropertyList (>= 2.3.3, < 4.0)
@@ -256,8 +251,8 @@ PLATFORMS
x86_64-linux
DEPENDENCIES
abbrev
fastlane
fastlane-plugin-huawei_appgallery_connect
BUNDLED WITH
2.5.4
+1 -1
View File
@@ -4,7 +4,7 @@
-->
# [Nextcloud](https://nextcloud.com) Android app :iphone:
[![REUSE status](https://api.reuse.software/badge/github.com/nextcloud/android)](https://api.reuse.software/info/github.com/nextcloud/android) [![Build Status](https://drone.nextcloud.com/api/badges/nextcloud/android/status.svg)](https://drone.nextcloud.com/nextcloud/android) [![Releases](https://img.shields.io/github/release/nextcloud/android.svg)](https://github.com/nextcloud/android/releases/latest)
[![REUSE status](https://api.reuse.software/badge/github.com/nextcloud/android)](https://api.reuse.software/info/github.com/nextcloud/android) [![Build Status](https://drone.nextcloud.com/api/badges/nextcloud/android/status.svg)](https://drone.nextcloud.com/nextcloud/android) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/fb4cf26336774ee3a5c9adfe829c41aa)](https://app.codacy.com/gh/nextcloud/android/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade) [![Releases](https://img.shields.io/github/release/nextcloud/android.svg)](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"
+1
View File
@@ -6,6 +6,7 @@
[![حالة REUSE](https://api.reuse.software/badge/github.com/nextcloud/android)](https://api.reuse.software/info/github.com/nextcloud/android)
[![حالة البناء](https://drone.nextcloud.com/api/badges/nextcloud/android/status.svg)](https://drone.nextcloud.com/nextcloud/android)
[![تقييم Codacy](https://app.codacy.com/project/badge/Grade/fb4cf26336774ee3a5c9adfe829c41aa)](https://app.codacy.com/gh/nextcloud/android/dashboard)
[![الإصدارات](https://img.shields.io/github/release/nextcloud/android.svg)](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 -25
View File
@@ -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 = 0
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("arm64-v8a", "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)
@@ -514,7 +526,10 @@ dependencies {
// region Kotlin
implementation(libs.kotlin.stdlib)
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
+10 -10
View File
@@ -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 -10
View File
@@ -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>
@@ -75,11 +76,6 @@
<ignore path="build" />
</issue>
<!-- Dagger factories generated for media3 @UnstableApi types cannot carry an @OptIn annotation. -->
<issue id="UnsafeOptInUsageError" severity="error">
<ignore path="build" />
</issue>
<issue id="ObsoleteLintCustomCheck" severity="warning">
<ignore path="**/fragment-1.2.5/**/lint.jar" />
<ignore path="**/work-runtime-2.**/**/lint.jar" />
@@ -90,11 +86,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 diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -99,7 +99,7 @@ class ActivitiesFragmentIT : AbstractIT() {
fun showActivities() {
val capability = OCCapability()
capability.versionMayor = 20
storageManager.saveCapabilities(capability)
fileDataStorageManager.saveCapabilities(capability)
val date = GregorianCalendar()
date.set(2005, 4, 17, 10, 35, 30)
@@ -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
@@ -23,7 +23,6 @@ import com.owncloud.android.R
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.ui.activity.FileDisplayActivity
import com.owncloud.android.ui.fragment.EmptyListState
import com.owncloud.android.ui.fragment.FabState
import com.owncloud.android.utils.ScreenshotTest
import org.junit.Assert
import org.junit.Rule
@@ -49,7 +48,7 @@ class FileDisplayActivityScreenshotIT : AbstractIT() {
scenario.onActivity { sut ->
sut.run {
listOfFilesFragment?.let {
it.setFabState(FabState.DISABLED)
it.setFabEnabled(false)
resetScrolling(true)
it.setEmptyListMessage(EmptyListState.LOADING)
it.isLoading = false
@@ -79,7 +78,7 @@ class FileDisplayActivityScreenshotIT : AbstractIT() {
activity = sut
val fragment = sut.listOfFilesFragment
Assert.assertNotNull(fragment)
fragment!!.setFabState(FabState.DISABLED)
fragment!!.setFabEnabled(false)
fragment.setEmptyListMessage(EmptyListState.LOADING)
fragment.isLoading = false
}
@@ -92,7 +91,7 @@ class FileDisplayActivityScreenshotIT : AbstractIT() {
.perform(NavigationViewActions.navigateTo(R.id.nav_all_files))
val fragment = activity!!.listOfFilesFragment
fragment!!.setFabState(FabState.DISABLED)
fragment!!.setFabEnabled(false)
fragment.setEmptyListMessage(EmptyListState.LOADING)
fragment.isLoading = false
@@ -118,7 +117,7 @@ class FileDisplayActivityScreenshotIT : AbstractIT() {
resetScrolling(true)
listOfFilesFragment?.let {
it.setFabState(FabState.DISABLED)
it.setFabEnabled(false)
it.setEmptyListMessage(EmptyListState.LOADING)
it.isLoading = false
}
@@ -14,6 +14,7 @@ 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.test.GrantStoragePermissionRule.Companion.grant
import com.owncloud.android.AbstractIT
import com.owncloud.android.datamodel.ArbitraryDataProviderImpl
import com.owncloud.android.ui.activity.RequestCredentialsActivity
@@ -21,12 +22,17 @@ import com.owncloud.android.ui.activity.SettingsActivity
import com.owncloud.android.utils.EncryptionUtils
import com.owncloud.android.utils.ScreenshotTest
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestRule
@Suppress("FunctionNaming")
class SettingsActivityIT : AbstractIT() {
private val testClassName = "com.nextcloud.client.SettingsActivityIT"
@get:Rule
var storagePermissionRule: TestRule = grant()
@Test
@ScreenshotTest
fun open() {
@@ -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)
}
}
}
@@ -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())
@@ -8,7 +8,6 @@
package com.nextcloud.client.assistant
import com.nextcloud.client.assistant.repository.remote.AssistantRemoteRepositoryImpl
import com.nextcloud.test.SinceServer
import com.owncloud.android.AbstractOnServerIT
import com.owncloud.android.lib.resources.assistant.v2.model.TaskTypeData
import com.owncloud.android.lib.resources.status.NextcloudVersion
@@ -18,21 +17,20 @@ import org.junit.Before
import org.junit.Test
@Suppress("MagicNumber")
@SinceServer(majorVersion = 28)
class AssistantRepositoryTests : AbstractOnServerIT() {
private var sut: AssistantRemoteRepositoryImpl? = null
@Before
fun setup() {
sut = AssistantRemoteRepositoryImpl(nextcloudClient, getCapability())
sut = AssistantRemoteRepositoryImpl(nextcloudClient, capability)
}
@Test
fun testGetTaskTypes() {
testOnlyOnServer(NextcloudVersion.nextcloud_28)
if (getCapability().assistant.isFalse) {
if (capability.assistant.isFalse) {
return
}
@@ -46,7 +44,7 @@ class AssistantRepositoryTests : AbstractOnServerIT() {
fun testGetTaskList() {
testOnlyOnServer(NextcloudVersion.nextcloud_28)
if (getCapability().assistant.isFalse) {
if (capability.assistant.isFalse) {
return
}
@@ -60,7 +58,7 @@ class AssistantRepositoryTests : AbstractOnServerIT() {
fun testCreateTask() {
testOnlyOnServer(NextcloudVersion.nextcloud_28)
if (getCapability().assistant.isFalse) {
if (capability.assistant.isFalse) {
return
}
@@ -83,7 +81,7 @@ class AssistantRepositoryTests : AbstractOnServerIT() {
fun testDeleteTask() {
testOnlyOnServer(NextcloudVersion.nextcloud_28)
if (getCapability().assistant.isFalse) {
if (capability.assistant.isFalse) {
return
}
@@ -101,7 +101,7 @@ class ContactsBackupIT : AbstractOnServerIT() {
fail("folderPath cannot be empty")
}
val folder = storageManager.getFileByDecryptedRemotePath(folderPath)
val folder = fileDataStorageManager.getFileByDecryptedRemotePath(folderPath)
if (folder == null) {
fail("folder cannot be null")
}
@@ -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>()
@@ -1,25 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.test
import org.junit.runner.Description
import org.junit.runner.manipulation.Filter
class FlakyTestFilter : Filter() {
override fun shouldRun(description: Description): Boolean = when {
description.isTest -> !description.isFlaky()
else -> description.children.any { shouldRun(it) }
}
override fun describe(): String = "skip tests annotated with @Flaky"
private fun Description.isFlaky(): Boolean {
val onMethod = getAnnotation(Flaky::class.java) != null
val onClass = testClass?.isAnnotationPresent(Flaky::class.java) == true
return onMethod || onClass
}
}
@@ -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() {
@@ -1,43 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.test
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.runner.Description
import org.junit.runner.manipulation.Filter
class ServerVersionFilter : Filter() {
private val serverVersion: Int? by lazy {
InstrumentationRegistry
.getArguments()
.getString(SERVER_VERSION_ARGUMENT)
?.toIntOrNull()
}
override fun shouldRun(description: Description): Boolean {
val currentVersion = serverVersion ?: return true
return when {
description.isTest -> description.requiredServerVersion() <= currentVersion
else -> description.children.any { shouldRun(it) }
}
}
override fun describe(): String = "skip tests annotated with @SinceServer above server version $serverVersion"
private fun Description.requiredServerVersion(): Int {
val onMethod = getAnnotation(SinceServer::class.java)?.majorVersion ?: ANY_SERVER
val onClass = testClass?.getAnnotation(SinceServer::class.java)?.majorVersion ?: ANY_SERVER
return maxOf(onMethod, onClass)
}
companion object {
private const val SERVER_VERSION_ARGUMENT = "TEST_SERVER_VERSION"
private const val ANY_SERVER = 0
}
}
@@ -1,11 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.test
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
annotation class SinceServer(val majorVersion: Int)
@@ -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
@@ -8,7 +8,6 @@
package com.nextcloud.utils
import com.nextcloud.test.SinceServer
import com.nextcloud.utils.autoRename.AutoRename
import com.owncloud.android.AbstractOnServerIT
import com.owncloud.android.datamodel.e2e.v2.decrypted.DecryptedFile
@@ -18,10 +17,10 @@ import com.owncloud.android.lib.resources.status.OCCapability
import org.junit.Before
import org.junit.Test
@SinceServer(majorVersion = 30)
@Suppress("TooManyFunctions")
class AutoRenameTests : AbstractOnServerIT() {
private var capability: OCCapability = storageManager.getCapability(account.name)
private var capability: OCCapability = fileDataStorageManager.getCapability(account.name)
private val forbiddenFilenameExtension = "."
private val forbiddenFilenameCharacter = ">"
@@ -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
@@ -7,7 +7,6 @@
package com.nextcloud.utils
import com.nextcloud.test.SinceServer
import com.nextcloud.utils.fileNameValidator.FileNameValidator
import com.owncloud.android.AbstractOnServerIT
import com.owncloud.android.R
@@ -21,12 +20,10 @@ 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 = storageManager.getCapability(account.name)
private var capability: OCCapability = fileDataStorageManager.getCapability(account.name)
@Before
fun setup() {
@@ -45,7 +42,6 @@ class FileNameValidatorTests : AbstractOnServerIT() {
}
@Test
@SinceServer(majorVersion = 30)
fun testInvalidCharacter() {
testOnlyOnServer(NextcloudVersion.nextcloud_30)
@@ -57,7 +53,6 @@ class FileNameValidatorTests : AbstractOnServerIT() {
}
@Test
@SinceServer(majorVersion = 30)
fun testReservedName() {
testOnlyOnServer(NextcloudVersion.nextcloud_30)
@@ -66,7 +61,6 @@ class FileNameValidatorTests : AbstractOnServerIT() {
}
@Test
@SinceServer(majorVersion = 30)
fun testForbiddenFilenameExtension() {
testOnlyOnServer(NextcloudVersion.nextcloud_30)
@@ -111,20 +105,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")
@@ -161,7 +141,6 @@ class FileNameValidatorTests : AbstractOnServerIT() {
}
@Test
@SinceServer(majorVersion = 30)
fun testFolderPathWithReservedName() {
testOnlyOnServer(NextcloudVersion.nextcloud_30)
@@ -173,7 +152,6 @@ class FileNameValidatorTests : AbstractOnServerIT() {
}
@Test
@SinceServer(majorVersion = 30)
fun testFilePathWithReservedName() {
testOnlyOnServer(NextcloudVersion.nextcloud_30)
@@ -185,7 +163,6 @@ class FileNameValidatorTests : AbstractOnServerIT() {
}
@Test
@SinceServer(majorVersion = 30)
fun testFolderPathWithInvalidCharacter() {
testOnlyOnServer(NextcloudVersion.nextcloud_30)
@@ -197,7 +174,6 @@ class FileNameValidatorTests : AbstractOnServerIT() {
}
@Test
@SinceServer(majorVersion = 30)
fun testFilePathWithInvalidCharacter() {
testOnlyOnServer(NextcloudVersion.nextcloud_30)
@@ -227,7 +203,6 @@ class FileNameValidatorTests : AbstractOnServerIT() {
}
@Test
@SinceServer(majorVersion = 30)
fun testFilePathWithNestedFolder() {
testOnlyOnServer(NextcloudVersion.nextcloud_30)
@@ -247,7 +222,6 @@ class FileNameValidatorTests : AbstractOnServerIT() {
}
@Test
@SinceServer(majorVersion = 30)
fun testOnlyFolderPathWithOneReservedName() {
testOnlyOnServer(NextcloudVersion.nextcloud_30)
@@ -17,9 +17,9 @@ 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 = storageManager.getCapability(account.name)
private var capability: OCCapability = fileDataStorageManager.getCapability(account.name)
// region Valid Input
@Test
@@ -1,38 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.utils
import com.nextcloud.client.device.BatteryStatus
import com.nextcloud.client.device.PowerManagementService
object PowerManagementFactory {
@JvmStatic
val mock: PowerManagementService = object : PowerManagementService {
override val isIgnoringOptimization: Boolean
get() = true
override val isPowerSavingEnabled: Boolean
get() = false
override val battery: BatteryStatus
get() = BatteryStatus(false, 0)
override val blocksAutoUpload: Boolean
get() = false
}
@JvmStatic
@Suppress("MagicNumber")
val mockCharging: PowerManagementService = object : PowerManagementService {
override val isIgnoringOptimization: Boolean
get() = true
override val isPowerSavingEnabled: Boolean
get() = false
override val battery: BatteryStatus
get() = BatteryStatus(true, 100)
override val blocksAutoUpload: Boolean
get() = false
}
}
@@ -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 =
@@ -9,22 +9,18 @@
package com.nextcloud.utils
import android.content.Context
import android.content.res.Configuration
import android.text.format.DateUtils
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 org.junit.After
import com.owncloud.android.utils.DisplayUtils
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Test
import java.text.DateFormat
import java.util.Date
import java.util.Locale
class UploadDateTests {
@@ -34,32 +30,17 @@ class UploadDateTests {
private const val ONE_HOUR = 60 * ONE_MINUTE
private const val ONE_DAY = 24 * ONE_HOUR
private const val ONE_AND_A_HALF_MINUTES = ONE_MINUTE + THIRTY_SECONDS
private const val TWO_AND_A_HALF_HOURS = 2 * ONE_HOUR + ONE_HOUR / 2
private const val TWO_DAYS = 2 * ONE_DAY
private const val ONE_WEEK = 7 * ONE_DAY
private const val ONE_MONTH = 30 * ONE_DAY
private const val ONE_YEAR = 365 * ONE_DAY
private const val DATE_AND_TIME_PARTS = 2
private const val TIME_OF_DAY_SEPARATOR = ":"
private const val NARROW_NO_BREAK_SPACE = ' '
private const val NO_BREAK_SPACE = ' '
private const val ONE_YEAR = 365L * ONE_DAY
private const val ONE_MONTH = 30L * ONE_DAY
private const val ONE_WEEK = 7L * ONE_DAY
private const val TWO_HOURS = 2L * ONE_HOUR
}
private lateinit var context: Context
private lateinit var systemLocale: Locale
@Before
fun setup() {
systemLocale = Locale.getDefault()
Locale.setDefault(Locale.US)
context = InstrumentationRegistry.getInstrumentation().targetContext.localized(Locale.US)
}
@After
fun tearDown() {
Locale.setDefault(systemLocale)
context = InstrumentationRegistry.getInstrumentation().targetContext
}
@Test
@@ -101,139 +82,189 @@ class UploadDateTests {
@Test
fun getRelativeDateTimeStringReturnsSecondsAgoForRecentPast() {
assertRelativeDateTimeString(
time = System.currentTimeMillis() - THIRTY_SECONDS,
expected = context.getString(R.string.file_list_seconds_ago)
val result = DisplayUtils.getRelativeDateTimeString(
context,
System.currentTimeMillis() - THIRTY_SECONDS,
DateUtils.MINUTE_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
0
)
assertEquals(context.getString(R.string.file_list_seconds_ago), result.toString())
}
@Test
fun getRelativeDateTimeStringReturnsFutureAsAbsoluteWhenShowFutureIsFalse() {
val time = System.currentTimeMillis() + ONE_AND_A_HALF_MINUTES
val time = System.currentTimeMillis() + ONE_MINUTE
val expected = java.text.DateFormat.getDateTimeInstance().format(Date(time))
assertRelativeDateTimeString(
time = time,
expected = DateFormat.getDateTimeInstance().format(Date(time))
val result = DisplayUtils.getRelativeDateTimeString(
context,
time,
DateUtils.SECOND_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
0,
false
)
assertEquals(expected, result.toString())
}
@Test
fun getRelativeDateTimeStringReturnsFutureAsRelativeWhenShowFutureIsTrue() {
assertRelativeDateTimeString(
time = System.currentTimeMillis() + ONE_AND_A_HALF_MINUTES,
expected = "In 1 minute",
showFuture = true
)
val expected = "In 1 minute"
val time = System.currentTimeMillis() + ONE_MINUTE
assertRelativeDateTimeString(time, expected, DateUtils.MINUTE_IN_MILLIS, showFuture = true)
}
@Test
fun getRelativeDateTimeStringReturnsRelativeStringForHoursAgo() {
assertRelativeDateTimeString(
time = System.currentTimeMillis() - TWO_AND_A_HALF_HOURS,
expected = "2 hours ago",
minResolution = DateUtils.SECOND_IN_MILLIS
val expected = "2 hours ago"
val time = System.currentTimeMillis() - TWO_HOURS
assertRelativeDateTimeString(time, expected, DateUtils.SECOND_IN_MILLIS)
}
@Test
fun getRelativeDateTimeStringReturnsAbbreviatedStringForOneWeekAgo() {
val time = System.currentTimeMillis() - ONE_WEEK
val expectedString = DateUtils.getRelativeDateTimeString(
context,
time,
DateUtils.MINUTE_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
0
).toString()
val parts = expectedString.split(",")
val expected = if (parts.size == 2) {
if (parts[1].contains(":") && !parts[0].contains(":")) parts[0].trim() else parts[1].trim()
} else {
expectedString
}
assertRelativeDateTimeString(time, expected)
}
@Test
fun getRelativeDateTimeStringReturnsAbbreviatedStringForOneMonthAgo() {
val time = System.currentTimeMillis() - ONE_MONTH
val expectedString = DateUtils.getRelativeDateTimeString(
context,
time,
DateUtils.SECOND_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
0
).toString()
val parts = expectedString.split(",")
val expected = if (parts.size == 2) {
if (parts[1].contains(":") && !parts[0].contains(":")) parts[0].trim() else parts[1].trim()
} else {
expectedString
}
assertRelativeDateTimeString(time, expected, DateUtils.SECOND_IN_MILLIS)
}
@Test
fun getRelativeDateTimeStringReturnsAbsoluteStringForOneYearAgo() {
val time = System.currentTimeMillis() - ONE_YEAR
val expectedString = DateUtils.getRelativeDateTimeString(
context,
time,
DateUtils.SECOND_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
0
).toString()
val parts = expectedString.split(",")
val expected = if (parts.size == 2) {
if (parts[1].contains(":") && !parts[0].contains(":")) parts[0].trim() else parts[1].trim()
} else {
expectedString
}
assertRelativeDateTimeString(time, expected, DateUtils.SECOND_IN_MILLIS)
}
@Suppress("MagicNumber")
@Test
fun getRelativeDateTimeStringReturnsDaysForDayInMillis() {
var testTimestamp = System.currentTimeMillis()
var expected = "Today"
var result = DisplayUtils.getRelativeDateTimeString(
context,
testTimestamp,
DateUtils.DAY_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
0,
false
)
}
assertEquals(expected, result)
@Test
fun getRelativeDateTimeStringReturnsTodayForNow() {
assertRelativeDateTimeString(
time = System.currentTimeMillis(),
expected = "Today",
minResolution = DateUtils.DAY_IN_MILLIS
testTimestamp = System.currentTimeMillis() - DateUtils.DAY_IN_MILLIS
expected = "Yesterday"
result = DisplayUtils.getRelativeDateTimeString(
context,
testTimestamp,
DateUtils.DAY_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
0,
false
)
}
assertEquals(expected, result)
@Test
fun getRelativeDateTimeStringReturnsYesterdayForOneDayAgo() {
assertRelativeDateTimeString(
time = System.currentTimeMillis() - ONE_DAY,
expected = "Yesterday",
minResolution = DateUtils.DAY_IN_MILLIS
testTimestamp = System.currentTimeMillis() - 2 * DateUtils.DAY_IN_MILLIS
expected = "2 days ago"
result = DisplayUtils.getRelativeDateTimeString(
context,
testTimestamp,
DateUtils.DAY_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
0,
false
)
}
assertEquals(expected, result)
@Test
fun getRelativeDateTimeStringReturnsDaysAgoForTwoDaysAgo() {
assertRelativeDateTimeString(
time = System.currentTimeMillis() - TWO_DAYS,
expected = "2 days ago",
minResolution = DateUtils.DAY_IN_MILLIS
testTimestamp = System.currentTimeMillis() - 7 * DateUtils.DAY_IN_MILLIS
val expectedString = DateUtils.getRelativeDateTimeString(
context,
testTimestamp,
DateUtils.DAY_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
0
).toString()
val parts = expectedString.split(",")
expected = if (parts.size == 2) {
if (parts[1].contains(":") && !parts[0].contains(":")) parts[0].trim() else parts[1].trim()
} else {
expectedString
}
result = DisplayUtils.getRelativeDateTimeString(
context,
testTimestamp,
DateUtils.DAY_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
0,
false
)
}
@Test
fun getRelativeDateTimeStringDropsTimeOfDayForOneWeekAgo() {
assertDateWithoutTimeOfDay(System.currentTimeMillis() - ONE_WEEK, DateUtils.MINUTE_IN_MILLIS)
}
@Test
fun getRelativeDateTimeStringDropsTimeOfDayForOneWeekAgoWithDayResolution() {
assertDateWithoutTimeOfDay(System.currentTimeMillis() - ONE_WEEK, DateUtils.DAY_IN_MILLIS)
}
@Test
fun getRelativeDateTimeStringDropsTimeOfDayForOneMonthAgo() {
assertDateWithoutTimeOfDay(System.currentTimeMillis() - ONE_MONTH, DateUtils.SECOND_IN_MILLIS)
}
@Test
fun getRelativeDateTimeStringDropsTimeOfDayForOneYearAgo() {
assertDateWithoutTimeOfDay(System.currentTimeMillis() - ONE_YEAR, DateUtils.SECOND_IN_MILLIS)
assertEquals(expected, result)
}
private fun assertRelativeDateTimeString(
time: Long,
expected: String,
minResolution: Long = DateUtils.MINUTE_IN_MILLIS,
transitionResolution: Long = DateUtils.WEEK_IN_MILLIS,
showFuture: Boolean = false
) {
val result = DisplayTextFormatter.formatRelativeDateTime(
val result = DisplayUtils.getRelativeDateTimeString(
context,
time,
minResolution,
DateUtils.WEEK_IN_MILLIS,
transitionResolution,
0,
showFuture
)
assertEquals(expected.normalizeSpaces(), result.toString().normalizeSpaces())
assertEquals(expected.normalizeResult(), result.toString().normalizeResult())
}
private fun assertDateWithoutTimeOfDay(time: Long, minResolution: Long) = assertRelativeDateTimeString(
time = time,
expected = platformDateClause(time, minResolution),
minResolution = minResolution
)
private fun platformDateClause(time: Long, minResolution: Long): String {
val platformString = DateUtils.getRelativeDateTimeString(
context,
time,
minResolution,
DateUtils.WEEK_IN_MILLIS,
0
).toString()
val parts = platformString.split(",").map(String::trim)
if (parts.size != DATE_AND_TIME_PARTS) {
return platformString
}
val (date, timeOfDay) = parts
return when {
timeOfDay.hasTimeOfDay() && !date.hasTimeOfDay() -> date
date.hasTimeOfDay() && !timeOfDay.hasTimeOfDay() -> timeOfDay
else -> platformString
}
}
private fun Context.localized(locale: Locale): Context {
val configuration = Configuration(resources.configuration).apply { setLocale(locale) }
return createConfigurationContext(configuration)
}
private fun String.hasTimeOfDay(): Boolean = contains(TIME_OF_DAY_SEPARATOR)
private fun String.normalizeSpaces(): String = replace(NARROW_NO_BREAK_SPACE, ' ').replace(NO_BREAK_SPACE, ' ')
private fun String.normalizeResult(): String = replace('\u202F', ' ').replace('\u00A0', ' ')
}
@@ -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)
}
}
}
Loaded 100 of 1011 files, more files were not shown because too many files have changed in this diff. Show more