Compare commits

..
2 Commits
Author SHA1 Message Date
alperozturk96 d99e601a09 wip
Signed-off-by: alperozturk96 <[email protected]>
2026-05-06 09:02:15 +02:00
alperozturk96 85c047ee85 wip
Signed-off-by: alperozturk96 <[email protected]>
2026-05-06 08:20:30 +02:00
607 changed files with 14506 additions and 25710 deletions

No files matched your search

@@ -1,130 +0,0 @@
---
name: android-java-to-kotlin
description: >
Use when finishing a Java-to-Kotlin conversion in an Android project, when the user
mentions "java to kotlin", "j2k", "convert java", "migrate java to kotlin", "finish the
conversion", "make it idiomatic", or when a freshly IDE-converted .kt file needs to be
turned into clean, modern, idiomatic Kotlin. The developer first runs the IDE converter
(Android Studio: Code > Convert Java File to Kotlin File), then this skill drives the
second pass: idiomatic cleanup, fail-fast control flow, coroutines/lifecycleScope,
modern Android APIs, function decomposition, and a behaviour-locking 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"
---
# Android Java to Kotlin Conversion (Second Pass)
The IDE converter produces Kotlin that *compiles* but is not *idiomatic*: platform types
everywhere, one giant function per lifecycle callback, nested `if`/`else`, `new Thread`,
`switch`, `TextUtils.isEmpty`, magic numbers. This skill drives the disciplined second
pass that turns that output into clean, modern, testable Kotlin — **without changing
observable behaviour** — and then writes a test that proves behaviour is unchanged.
## The Two-Person Workflow
This skill assumes a hand-off:
1. **Developer** runs the mechanical IDE conversion (`Code > Convert Java File to Kotlin
File`, or ⌥⇧⌘K), producing a `.kt` file that compiles but is not idiomatic.
2. **You (Claude)** drive everything after that:
Step 0 Baseline → Step 1 Idiomatic pass → Step 2 Behaviour-locking test → Step 3
Verify. If Step 3 fails or behaviour drifts, loop back to Step 1.
If you are handed a `.java` file instead, first apply a faithful 1:1 translation to reach
the same starting point, then continue.
## The Prime Directive: Behaviour Must Not Change
Every transformation in this skill is **behaviour-preserving**. You are refactoring for
readability, safety, and modern API usage — not adding features or fixing bugs. If you
spot a real bug, surface it to the developer; do not silently "fix" it inside a
conversion. The behaviour-locking test in Step 3 exists to keep you honest.
## Step 0: Establish Baseline
Before editing anything:
1. Read the whole `.kt` file (and, if you can, the original `.java` via
`git show <rev>:<path>.java` or the IDE's local history) to understand *what it does*.
2. Write down the **public/observable surface** you must keep intact:
- Lifecycle callbacks (`onCreate`, `onViewCreated`, `onSaveInstanceState`, …) and their
ordering of side-effects.
- Any Parcelable/Bundle keys, intent extras, and `newInstance(...)` factory shapes.
3. Note threading: which work runs off the main thread today (`Thread`, `AsyncTask`,
`runOnUiThread`, executors) — this maps to coroutines in Step 2.
## Step 1: Idiomatic Pass
Apply, in this order, then re-check the invariants:
1. **Kill platform types.** Give every `!` platform type an explicit nullable/non-null
type based on the Java source and call sites.
2. **Fail fast.** Replace nested `if`/`else` pyramids and null-checks with guard clauses
and `require`/`requireNotNull`/`?: return`. See [FAIL-FAST.md](references/FAIL-FAST.md).
3. **Decompose.** Break each oversized lifecycle callback / `setupView`-style method into
small, single-purpose private functions named for their intent. See
[ANDROID-IDIOMS.md](references/ANDROID-IDIOMS.md).
4. **Modern concurrency.** Replace `new Thread`, `AsyncTask`, `runOnUiThread`, and
callback pairs with `lifecycleScope` + `suspend` + `withContext`. See
[CONCURRENCY.md](references/CONCURRENCY.md).
5. **Modern Android + Kotlin idioms.** Scope functions (`run`/`apply`/`let`), extension
functions, `when`/`partition`/`filter` over `switch`, string templates, `isNullOrEmpty`,
view/KTX extensions. See [ANDROID-IDIOMS.md](references/ANDROID-IDIOMS.md). Retire
deprecated Android APIs (`onActivityResult`, options-menu overrides,
`java.util.Observable`) — see [DEPRECATED-APIS.md](references/DEPRECATED-APIS.md).
6. **Project conventions.** SPDX header, no magic numbers (`companion object` +
`const val`), resources not hardcoded strings, ≤300 lines/file, ≤120 cols. See
[PROJECT-CONVENTIONS.md](references/PROJECT-CONVENTIONS.md).
7. **Testability seams.** Extract pure logic (URL building, permission math, partitioning)
into functions you can unit-test; mark with `@VisibleForTesting` where they must stay
`internal`/`private`-ish but be reachable from tests.
Do NOT expand scope. Unrelated files stay untouched (AGENTS.md / AI policy).
## Step 2: Write a Behaviour-Locking Test (Mandatory)
A conversion is not complete until a test proves behaviour is unchanged. See
[TESTING.md](references/TESTING.md) for the decision tree. In short:
- **Pure functions you extracted** (e.g. link builders, `isReshareForbidden`,
partitioning) → fast JVM unit tests in `app/src/test/` (JUnit4 + mockito-kotlin).
- **Fragment/Activity/DB behaviour** → instrumented test in `app/src/androidTest/`
extending the project's base test class, or a Robolectric test where the project uses it.
- Prefer testing the **seams you just created**. If the Java original had no test, your
new test is the characterization test that locks current behaviour.
Every test file gets the SPDX header and follows the project's test conventions.
## Step 3: Verify
Run and report real output — never claim green without evidence:
```bash
# Formatting + static analysis on the changed files
./gradlew spotlessKotlinCheck detektGplayDebug lintGplayDebug spotbugsGplayDebug
# Unit tests
./gradlew jacocoTestGplayDebugUnitTest
# Instrumented tests (if you wrote one), scoped to the class
./gradlew createGplayDebugCoverageReport -Pcoverage=true \
-Pandroid.testInstrumentationRunnerArguments.class=<fully.qualified.TestClass>
```
## Worked Example
[assets/worked-example.md](assets/worked-example.md) is a real before/after from
`FileDetailSharingFragment` (871-line Java fragment → idiomatic Kotlin) showing each
transformation class in context. Read it when you need a concrete pattern.
## Batch Conversion
Convert one file at a time, leaf dependencies first. Report progress per file. Warn the
developer before a change set grows into several thousand lines — split into focused PRs
(AGENTS.md). Each commit needs `Assisted-by: <agent>:<model>`; only the human adds
`Signed-off-by`.
@@ -1,163 +0,0 @@
# Worked Example: FileDetailSharingFragment
A real conversion of an 871-line Java fragment
(`com.owncloud.android.ui.fragment.FileDetailSharingFragment`) into idiomatic Kotlin. Each
section shows one transformation class from the skill, in context. Behaviour is unchanged
throughout; the only new capability (`@VisibleForTesting createInternalLink`) is a
testability seam that returns the same URL the Java produced.
## A. SPDX Header Rewrite
```diff
-/*
- * Nextcloud Android client application
- *
- * @author Andy Scherzinger
- * ...
- * Copyright (C) 2018 Andy Scherzinger
- * SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
- */
+/*
+ * Nextcloud - Android Client
+ *
+ * SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
```
## B. Fail-Fast Preconditions
```diff
-if (file == null) throw new IllegalArgumentException("File may not be null");
-if (user == null) throw new IllegalArgumentException("Account may not be null");
-fileActivity = (FileActivity) getActivity();
-if (fileActivity == null) throw new IllegalArgumentException("FileActivity may not be null");
+fileActivity = (activity as FileActivity?)
+requireNotNull(file) { "File may not be null" }
+requireNotNull(user) { "Account may not be null" }
+requireNotNull(fileActivity) { "FileActivity may not be null" }
```
## C. Decomposition of `onViewCreated`
The Java `onViewCreated` inlined adapter creation (duplicated for internal/external),
layout managers, listeners, and the fetch kick-off. It became a readable sequence plus
extracted helpers `getUserId()`, `setupInternalShares()`, `setupExternalShares()`,
`createShareListAdapter(userId, type)`, `startAnimation()`. The two near-identical adapter
blocks collapsed into one parameterized factory:
```kotlin
private fun createShareListAdapter(userId: String, type: SharesType): ShareeListAdapter =
ShareeListAdapter(
fileActivity!!, ArrayList(), this, userId, user, viewThemeUtils,
(file?.isEncrypted == true), type
).apply { setHasStableIds(true) }
```
## D. `new Thread` + `runOnUiThread` → `lifecycleScope` + `suspend`
```diff
-private void fetchE2EECounter(Runnable onComplete) {
- new Thread(() -> {
- try { ... fileDataStorageManager.saveFile(file); }
- catch (Exception e) { Log_OC.e(TAG, "..." + e.getMessage()); }
- Activity a = getActivity();
- if (a != null) a.runOnUiThread(onComplete);
- }).start();
-}
+private suspend fun fetchE2EECounter(): Boolean = withContext(Dispatchers.IO) {
+ return@withContext try {
+ val client = clientFactory.create(user)
+ val metadata = RefreshFolderOperation.getDecryptedFolderMetadata(true, file, client, user, requireContext())
+ if (metadata is DecryptedFolderMetadataFile) {
+ file?.setE2eCounter(metadata.metadata.counter)
+ fileDataStorageManager?.saveFile(file)
+ }
+ true
+ } catch (e: Exception) {
+ Log_OC.e(TAG, "Error refreshing E2E counter: " + e.message)
+ false
+ }
+}
```
Caller now `lifecycleScope.launch { if (!fetchE2EECounter()) return@launch; withContext(Main){ ... } }`.
The callback-pair `fetchSharees(onSuccess, onError)` was likewise turned into a `suspend`
call returning `Boolean`.
## E. `switch` Bucketing → `partition` + Set
```diff
-for (OCShare share : shares) {
- if (share.getShareType() != null) {
- switch (share.getShareType()) {
- case PUBLIC_LINK: case FEDERATED_GROUP: case FEDERATED: case EMAIL:
- externalShares.add(share); break;
- default: internalShares.add(share); break;
- }
- }
-}
+private val externalShareTypes = setOf(
+ ShareType.PUBLIC_LINK, ShareType.FEDERATED_GROUP, ShareType.FEDERATED, ShareType.EMAIL
+)
+val (external, internal) = shares
+ .filter { it.shareType != null }
+ .partition { it.shareType in externalShareTypes }
```
## F. Nested `if` Cursor Handling → Guard Clauses
The three-level-nested `handleContactResult` became flat sequential guards, each showing
the snackbar + log and returning, with `cursor.close()` preserved on every path. See
[FAIL-FAST.md](../references/FAIL-FAST.md) section "Deeply Nested".
## G. Scope Functions & KTX
```diff
-final LinearLayout shimmerLayout = binding.shimmerLayout.getRoot();
-shimmerLayout.clearAnimation();
-shimmerLayout.setVisibility(View.GONE);
-binding.shareContainer.setVisibility(View.VISIBLE);
+binding?.run {
+ shimmerLayout.root.run { clearAnimation(); visibility = View.GONE }
+ shareContainer.visibility = View.VISIBLE
+}
```
```diff
-for (int i = 0; i < viewGroup.getChildCount(); i++) { toggleSearchViewEnable(viewGroup.getChildAt(i), enable); }
+for (i in 0..<view.size) { toggleSearchViewEnable(view.getChildAt(i), enable) } // androidx.core.view.size
```
## H. Constants + Companion + `@JvmStatic`
```diff
-private static final String TAG = "FileDetailSharingFragment";
-ViewExtensionsKt.setVisibleIf(binding.sharesListInternalShowAll, adapter.shares.size() > 3);
+companion object {
+ private const val TAG = "FileDetailSharingFragment"
+ private const val MIN_SHOW_ALL_VISIBLE_ITEM_COUNT = 3
+ @JvmStatic fun newInstance(file: OCFile?, user: User?) = FileDetailSharingFragment().apply { ... }
+}
+binding.sharesListInternalShowAll.setVisibleIf(internalShares.size > MIN_SHOW_ALL_VISIBLE_ITEM_COUNT)
```
## I. Testability Seam
`createInternalLink` was inlined string concatenation in Java. It was extracted to a pure
`@VisibleForTesting internal fun createInternalLink(user, file, capabilities): String` that
returns the identical URL — enabling the unit test in
[TESTING.md](../references/TESTING.md) without a device.
## J. Detekt Suppression (Last Resort)
The class is genuinely large and can't be fully split within one conversion, so a
file-level suppression documents the debt honestly:
```kotlin
@Suppress("TooManyFunctions", "LargeClass", "TooGenericExceptionCaught", "ReturnCount")
class FileDetailSharingFragment : Fragment(), ... {
```
Prefer real decomposition; use this only when splitting is out of scope, and tell the
developer.
@@ -1,170 +0,0 @@
<!--
~ Nextcloud - Android Client
~
~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
~ SPDX-License-Identifier: AGPL-3.0-or-later
-->
# Android + Kotlin Idioms
Transformations applied during the idiomatic pass. Every one is behaviour-preserving.
Examples are drawn from a real fragment conversion.
## 1. Decompose Oversized Functions
The IDE keeps the Java structure: one enormous `onViewCreated`/`setupView` that inflates,
themes, wires listeners, and kicks off loading in a single 80-line block. Split by
intent into small private functions. The lifecycle callback becomes a readable table of
contents.
```kotlin
// BEFORE: onViewCreated does everything inline (adapters, layout managers, listeners, fetch)
// AFTER
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fileActivity ?: return
fileDataStorageManager = fileActivity?.storageManager
fileOperationsHelper = fileActivity?.fileOperationsHelper
startAnimation()
val userId = getUserId()
setupInternalShares(userId)
setupExternalShares(userId)
binding?.pickContactEmailBtn?.setOnClickListener { checkContactPermission() }
fetchSharees()
setupView()
}
```
Rules:
- One function = one reason to change. Name it for *what it accomplishes*
(`setupInternalShares`, `themeView`, `disableE2EEShareForV1`), not *how*.
- Factor duplicated blocks into a parameterized helper
(`createShareListAdapter(userId, SharesType.INTERNAL)`).
- Keep files ≤300 lines (project rule). Heavy decomposition sometimes means splitting a
god-class into collaborators — raise that with the developer rather than exceeding 300.
## 2. Scope Functions Over Repetition
Replace repeated `binding.x` / `viewThemeUtils.material.y` chains with `run`/`apply`/`with`.
```kotlin
// BEFORE
viewThemeUtils.material.themeSearchCardView(binding.searchCardWrapper);
viewThemeUtils.material.colorMaterialButtonPrimaryOutlined(binding.sendCopyBtn);
viewThemeUtils.material.colorMaterialButtonPrimaryBorderless(binding.sharesListInternalShowAll);
// AFTER
binding.run {
viewThemeUtils.material.run {
themeSearchCardView(searchCardWrapper)
colorMaterialButtonPrimaryOutlined(sendCopyBtn)
colorMaterialButtonPrimaryBorderless(sharesListInternalShowAll)
}
}
```
Use `apply {}` when configuring and returning the receiver:
```kotlin
ShareeListAdapter(fileActivity!!, ArrayList(), this, userId, user, viewThemeUtils, encrypted, type)
.apply { setHasStableIds(true) }
```
## 3. `switch` → `when` / `filter` + `partition`
Collapse a `switch` that sorts items into buckets into a declarative pipeline with a
constant `Set`.
```kotlin
// BEFORE: for-loop with switch(shareType) adding to internalShares / externalShares
// AFTER
private val externalShareTypes = setOf(
ShareType.PUBLIC_LINK, ShareType.FEDERATED_GROUP, ShareType.FEDERATED, ShareType.EMAIL
)
val (external, internal) = shares
.filter { it.shareType != null }
.partition { it.shareType in externalShareTypes }
```
## 4. Extension Functions & KTX
Import members directly and lean on AndroidX KTX instead of verbose Java utilities.
| Java / verbose | Idiomatic Kotlin |
|---|---|
| `TextUtils.isEmpty(s)` | `s.isNullOrEmpty()` |
| `BundleExtensionsKt.getParcelableArgument(b, k, T.class)` | `b.getParcelableArgument(k, T::class.java)` |
| `for (int i = 0; i < vg.getChildCount(); i++)` | `for (i in 0..<view.size)` (`androidx.core.view.size`) |
| manual getter/setter methods | Kotlin property access (`view.visibility = View.GONE`) |
| `private int x; public int getX()` (read-only to callers) | `var columnsCount = 0; private set` |
| empty override method body | `= Unit` single-expression body |
| free-standing util call | receiver extension (`externalShares.mergeDistinctByToken(publicShares)`) |
Domain-specific extensions read best as receivers on the relevant type:
```kotlin
private fun OCCapability?.isPasswordEnforced(): Boolean =
this?.filesSharingPublicPasswordEnforced?.isTrue == true &&
filesSharingPublicAskForOptionalPassword.isTrue
```
## 5. Null Safety Instead of Platform Types
The IDE leaves `!` platform types and defensive Java null-checks. Replace with `?.`,
`?:`, and Kotlin's `require`/`requireNotNull`. A nullable `binding` (cleared in
`onDestroyView`) is the canonical Android case — guard it with `?.` / `?: return`.
```kotlin
// BEFORE
if (binding == null) return;
final LinearLayout shimmer = binding.shimmerLayout.getRoot();
shimmer.clearAnimation();
// AFTER
binding?.run {
shimmerLayout.root.run {
clearAnimation()
visibility = View.GONE
}
shareContainer.visibility = View.VISIBLE
}
```
## 6. Constants & Companion Object
Move `static final` and magic literals into a `companion object`; use `const val` for
compile-time constants. Add `@JvmStatic` to factory methods still called from Java.
```kotlin
companion object {
private const val TAG = "FileDetailSharingFragment"
private const val ARG_FILE = "FILE"
private const val MIN_SHOW_ALL_VISIBLE_ITEM_COUNT = 3
private const val INTERNAL_LINK_PATH_PRETTY = "/f/"
@JvmStatic
fun newInstance(file: OCFile?, user: User?) = FileDetailSharingFragment().apply {
arguments = Bundle().apply {
putParcelable(ARG_FILE, file)
putParcelable(ARG_USER, user)
}
}
}
```
## 7. Detekt Suppressions Are a Last Resort
If a legacy god-class genuinely cannot be split within the conversion's scope, a
file/class-level `@Suppress("TooManyFunctions", "LargeClass", ...)` is acceptable — but
prefer real decomposition and tell the developer what you suppressed and why.
## 8. `// region` Organization
For large classes, grouping members under `// region <name>` / `// endregion` (lifecycle,
private methods, overrides, companion) aids IDE folding. This is IDE structure, not a
decorative divider. Match the surrounding file's existing style; do not introduce ASCII
banner comments (`// ==== ====`), which the project forbids.
@@ -1,213 +0,0 @@
<!--
~ Nextcloud - Android Client
~
~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
~ SPDX-License-Identifier: AGPL-3.0-or-later
-->
# Concurrency: Java Threads → Coroutines & `lifecycleScope`
Replace `new Thread`, `AsyncTask`, executors, and `runOnUiThread`/`Handler.post`
callback-passing with structured coroutines scoped to the component lifecycle. This is
behaviour-preserving *and* fixes leaks: `lifecycleScope`/`viewModelScope` cancel
automatically when the owner is destroyed, so no work touches a dead view.
## Choose the Right Scope
| Context | Scope |
|---|---|
| `Fragment` (UI work tied to view) | `viewLifecycleOwner.lifecycleScope` (preferred) or `lifecycleScope` |
| `Activity` | `lifecycleScope` |
| `ViewModel` | `viewModelScope` |
| No lifecycle owner | inject a `CoroutineScope` / use a repository suspend fun |
Use `Dispatchers.IO` for disk/network/DB, `Dispatchers.Main` (or `withContext(Main)`) to
touch views.
## `AsyncTask` → Coroutines
`AsyncTask` is deprecated. Map its callbacks onto a single `launch`:
| `AsyncTask` | Coroutine |
|---|---|
| `onPreExecute()` | code before `withContext(IO)` (runs on Main) |
| `doInBackground()` | `withContext(Dispatchers.IO) { ... }` |
| `onPostExecute(result)` | code after, back on `Dispatchers.Main` |
| `isCancelled()` | `isActive` (or `ensureActive()`) |
| `cancel(true)` | `job.cancel()` |
| the `AsyncTask` instance field | the returned `Job` |
A self-contained task class stops extending `AsyncTask` and holds the lifecycle owner so
its scope cancels with the screen:
```kotlin
// BEFORE: class GallerySearchTask extends AsyncTask<Void, Void, Result> { ... }
class GallerySearchTask(
private val fragment: GalleryFragment,
private val user: User,
private val storageManager: FileDataStorageManager,
private val endDate: Long,
private val limit: Int
) {
fun execute(): Job = fragment.lifecycleScope.launch(Dispatchers.IO) {
if (!isActive) return@launch
val context = fragment.context ?: return@launch
val result = performSearch(context)
withContext(Dispatchers.Main) {
fragment.searchCompleted(result.emptySearch, result.lastTimestamp)
}
}
}
```
The caller keeps the `Job` and cancels it with the view:
```kotlin
private var photoSearchTask: Job? = null
// ...
photoSearchTask = GallerySearchTask(this, user, storageManager, endDate, limit).execute()
override fun onDestroyView() {
photoSearchTask?.cancel()
photoSearchTask = null
}
```
Because `lifecycleScope` cancels on destroy, the old `WeakReference<Fragment>` leak-guard
disappears — a direct `fragment` reference plus `fragment.context ?: return@launch` is
enough. (PR #16908)
## `AsyncTask` Behind a Callback API → `runCatching` + `fold`
When a service method hid an `AsyncTask` that set mutable fields (a boolean success flag,
`errorMessage`, result fields) and dispatched them in `onPostExecute`, keep the public
callback signature but drive it from a coroutine. Return an **immutable** result from the
background function and branch with `fold`:
```kotlin
private data class ActivitiesResult(
val activities: List<Any>,
val client: NextcloudClient,
val lastGiven: Long
)
override fun getActivities(lastGiven: Long, callback: ActivitiesServiceCallback) {
scope.launch {
runCatching { withContext(Dispatchers.IO) { fetchActivities(lastGiven) } }
.fold(
onSuccess = { (activities, client, updated) ->
callback.onLoaded(activities, client, updated)
},
onFailure = { callback.onError(it.message ?: "") }
)
}
}
```
`runCatching` / `fold` replaces the boolean-success + `errorMessage`-field idiom; the
background function `fetchActivities` throws on failure instead of returning `false`, and
the immutable `ActivitiesResult` destructures straight into `onSuccess`. (PR #16654)
> **Scope caveat:** that PR launched on an ad-hoc `CoroutineScope(Dispatchers.Main)` with
> no lifecycle owner — it never cancels and can leak. Prefer an injected `CoroutineScope`
> or expose a `suspend` function the presenter runs on `lifecycleScope` / `viewModelScope`.
> Flag ad-hoc scopes in review.
## `new Thread { ... runOnUiThread(...) }` → `lifecycleScope.launch` + `withContext`
```kotlin
// BEFORE
private void fetchE2EECounter(Runnable onComplete) {
new Thread(() -> {
try {
OwnCloudClient client = clientFactory.create(user);
Object metadata = RefreshFolderOperation.getDecryptedFolderMetadata(true, file, client, user, ctx);
if (metadata instanceof DecryptedFolderMetadataFile m) {
file.setE2eCounter(m.getMetadata().getCounter());
fileDataStorageManager.saveFile(file);
}
} catch (Exception e) { Log_OC.e(TAG, "..." + e.getMessage()); }
Activity a = getActivity();
if (a != null) a.runOnUiThread(onComplete);
}).start();
}
// AFTER: background work is a suspend fun on IO; the UI reaction runs on Main
private suspend fun fetchE2EECounter(): Boolean = withContext(Dispatchers.IO) {
return@withContext try {
val context = requireContext()
val client = clientFactory.create(user)
val metadata = RefreshFolderOperation.getDecryptedFolderMetadata(true, file, client, user, context)
if (metadata is DecryptedFolderMetadataFile) {
file?.setE2eCounter(metadata.metadata.counter)
fileDataStorageManager?.saveFile(file)
}
true
} catch (e: Exception) {
Log_OC.e(TAG, "Error refreshing E2E counter: " + e.message)
false
}
}
// caller
lifecycleScope.launch {
val ok = fetchE2EECounter()
if (!ok) return@launch
withContext(Dispatchers.Main) { /* update views */ }
}
```
Notes:
- The old code returned nothing and drove the UI via a `Runnable`. The idiomatic version
returns a `Boolean` result and lets the caller decide — same observable outcome, no
callback threading.
- `getActivity() != null` guard becomes `lifecycleScope` cancellation + `binding?`/`?:
return` guards. Preserve any "is the view still alive?" check as a `binding == null`
guard inside `launch`.
## Callback-Pair API → `suspend` Result
Repositories that took `onSuccess`/`onError` lambdas become `suspend` functions returning
a result, awaited inside a coroutine.
```kotlin
// BEFORE
shareRepository.fetchSharees(remotePath, onSuccess = { ... }, onError = { ... });
// AFTER
lifecycleScope.launch {
val result = shareRepository.fetchSharees(remotePath)
if (binding == null) return@launch
if (result) { refreshSharesFromDB(); stopLoadingAnimationAndShowShareContainer() }
else { stopLoadingAnimationAndShowShareContainer(); showError() }
}
```
## Moving DB/IO off the Main Thread
Wrap the blocking DB read in `withContext(Dispatchers.IO)` and hop back to `Main` to touch
adapters/views. This can be a *behaviour improvement* (fewer main-thread stalls) — flag it
to the developer if the Java version was doing DB work on the main thread synchronously,
since timing changes can be observable (e.g. tests that assumed synchronous population).
```kotlin
private suspend fun loadAndPartitionShares(): Pair<List<OCShare>, List<OCShare>> =
withContext(Dispatchers.IO) {
val shares = fileDataStorageManager?.getSharesWithForAFile(file?.remotePath, user?.accountName)
?: emptyList()
val (external, internal) = shares.filter { it.shareType != null }
.partition { it.shareType in externalShareTypes }
internal to external
}
```
## Pitfalls
- Never launch on `GlobalScope` — it outlives the screen and leaks.
- An ad-hoc `CoroutineScope(Dispatchers.Main)` created inside a service/presenter has the
same problem: no lifecycle owner, no cancellation, a leak. Use an injected scope or a
`suspend` function the caller runs on `lifecycleScope` / `viewModelScope`.
- Keep `try/catch` semantics: coroutine cancellation throws `CancellationException`;
rethrow it (don't swallow in a broad `catch (e: Exception)` that logs and continues) or
catch `Exception` only around the real work, not around the whole `launch`.
- Preserve exception-to-UI mapping exactly (same snackbar, same log tag/message).
@@ -1,85 +0,0 @@
<!--
~ Nextcloud - Android Client
~
~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
~ SPDX-License-Identifier: AGPL-3.0-or-later
-->
# Retiring Deprecated Android APIs During Conversion
A Java→Kotlin conversion is the right moment to replace deprecated Android APIs the IDE
converter leaves untouched. Each replacement below is behaviour-preserving. Examples are
real conversions (nextcloud/android PRs #16878, #16792).
## `startActivityForResult` / `onActivityResult` → Activity Result API
The request-code + `onActivityResult` protocol is deprecated. Register a launcher at
construction time and receive the result in its callback.
```kotlin
// BEFORE
startActivityForResult(action, SELECT_LOCATION_REQUEST_CODE)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == SELECT_LOCATION_REQUEST_CODE && data != null) { handle(data) }
}
// AFTER
private val folderPickerLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
handle(result.data)
}
}
// launch it:
folderPickerLauncher.launch(intent)
```
Type-safe, no manual request-code bookkeeping, and it survives process death because
registration is declarative. Register during initialization (a field initializer or
`onCreate`/`onViewCreated`) — never inside a click handler, or the registration is lost.
## `onCreateOptionsMenu` / `onOptionsItemSelected` → `MenuProvider`
`setHasOptionsMenu(true)` plus the two menu overrides are deprecated on `Fragment`. Add a
`MenuProvider` bound to the view lifecycle instead.
```kotlin
// AFTER
val menuHost: MenuHost = requireActivity()
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, inflater: MenuInflater) =
inflater.inflate(R.menu.gallery_menu, menu)
override fun onMenuItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.action_select_all -> { selectAll(); true }
else -> false
}
}, viewLifecycleOwner, Lifecycle.State.RESUMED)
```
Passing `viewLifecycleOwner` + `Lifecycle.State.RESUMED` auto-adds and removes the menu as
the view's lifecycle changes — no leak, no manual `setHasOptionsMenu`. (PR #16878)
## `java.util.Observable` — Keep or Migrate?
`java.util.Observable` / `Observer` are deprecated (Java 9+). But a conversion is
behaviour-locked, so **do not** silently swap the notification mechanism — existing Java
observers rely on `setChanged()` / `notifyObservers()`. PR #16792 deliberately KEPT it:
```kotlin
class UploadsStorageManager(...) : Observable() {
fun notifyObserversNow() {
Handler(Looper.getMainLooper()).post {
setChanged()
notifyObservers()
}
}
}
```
Migrating to `StateFlow` / `SharedFlow` changes the observation contract and every call
site — that is a separate, opt-in refactor, not part of a 1:1 conversion. Note the
deprecation, propose the flow migration as a follow-up, and keep the current mechanism
unless the developer scopes the larger change.
@@ -1,115 +0,0 @@
<!--
~ Nextcloud - Android Client
~
~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
~ SPDX-License-Identifier: AGPL-3.0-or-later
-->
# Fail Fast: Guard Clauses Over Nested `if`/`else`
The IDE preserves Java's nested-`if` pyramids. Invert them into guard clauses that return
(or throw) early, leaving the happy path at the lowest indentation. Behaviour is
identical — the branches are the same, only the shape changes.
## Precondition Checks → `require` / `requireNotNull`
`requireNotNull` returns the smart-cast non-null value AND throws
`IllegalArgumentException` with the message — exactly matching the Java `if (x == null)
throw new IllegalArgumentException(...)`.
```kotlin
// BEFORE
if (file == null) throw IllegalArgumentException("File may not be null");
if (user == null) throw IllegalArgumentException("Account may not be null");
fileActivity = (FileActivity) getActivity();
if (fileActivity == null) throw IllegalArgumentException("FileActivity may not be null");
// AFTER
fileActivity = activity as? FileActivity
requireNotNull(file) { "File may not be null" }
requireNotNull(user) { "Account may not be null" }
requireNotNull(fileActivity) { "FileActivity may not be null" }
```
Use `require(condition) { msg }` for boolean preconditions:
```kotlin
require(activity is FileActivity) { "Calling activity must be of type FileActivity" }
```
`check`/`checkNotNull` are the `IllegalStateException` equivalents — use them when the Java
threw `IllegalStateException`. Match the original exception type; that is observable
behaviour.
## Early Return Over Nested Success Path
```kotlin
// BEFORE
private void checkShareViaUser() {
if (!MDMConfig.INSTANCE.shareViaUser(requireContext())) {
binding.searchContainer.setVisibility(View.GONE);
}
}
// AFTER
private fun checkShareViaUser() {
if (shareViaUser(requireContext())) return
binding?.searchContainer?.visibility = View.GONE
}
```
## Deeply Nested `if`/`else` → Sequential Guards
The most valuable transformation. A cursor-handling method nested three levels deep
becomes a flat sequence of guard clauses, each handling one failure and returning.
```kotlin
// BEFORE: if (cursor != null) { if (moveToFirst()) { if (columnIndex != -1) {...} else ... } else ... } else ...
// AFTER
private fun handleContactResult(contactUri: Uri) {
val cursor = fileActivity?.contentResolver?.query(contactUri, projection, null, null, null)
if (cursor == null) {
DisplayUtils.showSnackMessage(this, R.string.email_pick_failed)
Log_OC.e(TAG, "Failed to pick email address as Cursor is null.")
return
}
if (!cursor.moveToFirst()) {
DisplayUtils.showSnackMessage(this, R.string.email_pick_failed)
Log_OC.e(TAG, "Failed to pick email address as no Email found.")
return
}
val columnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS)
if (columnIndex == -1) {
DisplayUtils.showSnackMessage(this, R.string.email_pick_failed)
Log_OC.e(TAG, "Failed to pick email address.")
cursor.close()
return
}
val email = cursor.getString(columnIndex)
// ... happy path at base indentation
cursor.close()
}
```
Watch the cleanup: if the Java relied on falling through to a single `cursor.close()`,
each early return must still close it (or wrap in `use {}`). Missing that changes
behaviour (resource leak) — verify it.
## Nullable-Guard Idioms
```kotlin
val activity = fileActivity ?: return
val clientRepository = activity.clientRepository ?: return
val remotePath = file?.remotePath ?: return
```
Each `?: return` collapses one Java `if (x == null) return;`. Chain them at the top of the
function so the body works with non-null smart-cast locals.
## When NOT to Invert
- Do not turn a genuine two-branch decision (both branches do real work) into a guard if
it obscures the symmetry — a `when`/`if-else` expression is clearer there.
- Do not change the *order* of side-effects while inverting; the snackbar/log calls above
must fire in the same cases as before.
@@ -1,79 +0,0 @@
# Project Conventions (Nextcloud Android)
Apply these during Step 2 so the converted file passes review and the quality gates. They
are enforced by `spotlessKotlinCheck`, `detekt`, `lint`, and `spotbugsGplayDebug`.
## SPDX Header (every new/renamed file)
The IDE keeps the old license block. Replace it with the current template. The year is the
year the Kotlin file is created. New contributions are `AGPL-3.0-or-later`; keep
`OR GPL-2.0-only` only if the original file carried it.
```kotlin
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: <YEAR> Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
```
If the developer wants personal attribution (as in the real conversion), the form
`SPDX-FileCopyrightText: <YEAR> <Name> <email>` is also used — match what the developer
asks for; default to the "Nextcloud GmbH and Nextcloud contributors" line.
## Structural Rules
- **≤300 lines per file.** If decomposition pushes past it, split responsibilities into
separate files/collaborators and tell the developer. A file/class-level
`@Suppress("LargeClass", "TooManyFunctions")` is a last resort for legacy god-classes.
- **≤120 columns per line.**
- **One top-level type per file.** Extract models, states, sealed classes, and listener
interfaces into their own files rather than nesting many types in one.
- **Exactly one trailing newline** at end of file.
## No Magic Numbers / Hardcoded Resources
- Extract literals into named `const val` in a `companion object`
(`MIN_SHOW_ALL_VISIBLE_ITEM_COUNT = 3`, `INTERNAL_LINK_PATH_PRETTY = "/f/"`).
- Strings, colors, dimens come from resources (`R.string.*`, `R.dimen.*`), never inline.
- Only `app/src/main/res/values/strings.xml` may be edited for strings; never touch
`values-*` translation folders.
## Comments & Naming
- No decorative divider comments (`// ==== ====`, `// ---- Title ----`). `// region` /
`// endregion` for IDE folding is allowed and should match the file's existing style.
- Names carry the explanation, not comments. If a name needs a comment to be understood,
rename or decompose instead. Do not add KDoc to a function just because it is new.
- Preserve genuinely informative Javadoc as KDoc (invariant 4); drop noise. A comment
earns its place only for a non-obvious invariant, a platform/server workaround, or an
ordering requirement — and it explains **why**, never **what**.
- Never narrate the conversion itself: no "was a Java thread, now a coroutine", no
"changed from X to Y", no references to the PR, the issue, or this conversation.
Comments describe the code as it stands. That history belongs in the commit message.
- Do not use multiple boolean flags to model state — use an `enum`/sealed class.
## Modern Java Interop
When the file still has Java callers, keep the Java-facing API clean:
`@JvmStatic` for factory/companion functions, `@JvmField` for exposed constants,
`@JvmOverloads` for defaulted params, `@Throws` for checked exceptions.
## Git & Commits (developer-driven)
- Preserve history: the rename `git mv Foo.java Foo.kt` should be a **separate commit**
from the content change so `git blame` follows through.
- Conventional Commits (`refactor(sharing): convert FileDetailSharingFragment to Kotlin`).
- Every AI-assisted commit needs an `Assisted-by: <agent>:<model>` trailer.
- Only the human contributor adds `Signed-off-by` (DCO). You must never add it, and never
open PRs/issues autonomously (AI policy).
## Quality Gate
```bash
./gradlew spotlessKotlinCheck detektGplayDebug lintGplayDebug spotbugsGplayDebug \
jacocoTestGplayDebugUnitTest
```
Fix every finding in the files you changed before declaring done.
@@ -1,107 +0,0 @@
# Behaviour-Locking Tests (Mandatory Step)
A conversion is not done until a test proves behaviour did not change. If the Java class
already had tests, they are your primary safety net — run them and keep them green. If it
had none, you must add a **characterization test** that pins the current behaviour so the
refactor is provably safe.
## Decision Tree
```dot
digraph test_choice {
rankdir=LR;
"What are you locking?" -> "Pure logic (no Android SDK)" [label="fn returns a value"];
"What are you locking?" -> "Component behaviour" [label="Fragment/Activity/DB/View"];
"Pure logic (no Android SDK)" -> "JVM unit test app/src/test/ (JUnit4 + mockito-kotlin)";
"Component behaviour" -> "Robolectric unit test (if project uses it)";
"Component behaviour" -> "Instrumented test app/src/androidTest/ extends base IT class";
}
```
**Prefer the seams you just created.** The idiomatic pass extracts pure functions
(link builders, permission math, partitioning, `isReshareForbidden`) specifically so they
can be unit-tested fast without a device. Test those first; they give the most behaviour
coverage per second.
## 1. JVM Unit Tests — Pure Functions
Location: `app/src/test/`. Fast, no emulator. Command:
`./gradlew jacocoTestGplayDebugUnitTest`.
Mark the function `@VisibleForTesting internal` so the test module can reach it while it
stays out of the public API.
```kotlin
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.ui.fragment
import com.owncloud.android.lib.resources.status.OCCapability
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
class FileDetailSharingFragmentTest {
@Test
fun `internal link uses pretty path when modRewrite is on`() {
val user = mock<User> { whenever(it.server.uri).thenReturn(URI("https://cloud.example")) }
val file = mock<OCFile> { whenever(it.localId).thenReturn(42L) }
val caps = mock<OCCapability> { whenever(it.modRewriteWorking.isTrue).thenReturn(true) }
val link = FileDetailSharingFragment().createInternalLink(user, file, caps)
assertEquals("https://cloud.example/f/42", link)
}
@Test
fun `internal link falls back to index php path when modRewrite is off`() {
// ... same setup with modRewriteWorking.isTrue == false
// assertEquals("https://cloud.example/index.php/f/42", link)
}
}
```
The point: run this test's logic against **both** the pre-conversion and post-conversion
code paths mentally (or, if the Java is still on disk, literally) and confirm the assertion
holds for both. That is what "behaviour must not change" means concretely.
## 2. Instrumented Tests — Component Behaviour
Location: `app/src/androidTest/`. For Fragment/Activity/DB behaviour that needs the Android
runtime. Extend the project's base test class (`AbstractOnServerIT` when server
communication is required) and follow its conventions (separate test user, etc.).
```bash
./gradlew createGplayDebugCoverageReport -Pcoverage=true \
-Pandroid.testInstrumentationRunnerArguments.class=com.owncloud.android.ui.fragment.FileDetailSharingFragmentIT
```
Use `@VisibleForTesting` hooks the original exposed (e.g. a `search(query)` or
`showSharingMenuActionSheet(share)` method) to drive and assert UI state, exactly as the
existing IT suite does. Do not weaken visibility further than the Java original did.
## 3. What to Assert
Lock the observable contract, not the implementation:
- Same return values / thrown exception types for the same inputs (including the
`require`/`requireNotNull` messages if callers depend on them).
- Same Bundle keys, intent extras, and `newInstance` argument wiring.
- Same branch outcomes (e.g. "reshare forbidden when FEDERATED", "show-all button visible
only when > 3 shares").
- For coroutine conversions, assert the end state, and use the project's test dispatcher /
`runTest` so async work is deterministic — never assert on wall-clock timing.
## 4. Guardrails
- Every new test file gets the SPDX header and ends with exactly one trailing newline.
- Do not modify unrelated tests to make yours pass.
- Report actual test output. If a test reveals the conversion changed behaviour, fix the
conversion — do not adjust the test to match the drift.
- If a genuine pre-existing bug is uncovered, surface it to the developer separately; do
not fold a behaviour change into the conversion.
-5
View File
@@ -1,5 +0,0 @@
# 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:2260313b31c8c011cd2eebe728008efac1b3982be73eb71348ea2648d2c0e09b
FROM ubuntu:resolute@sha256:5e275723f82c67e387ba9e3c24baa0abdcb268917f276a0561c97bef9450d0b4
ARG DEBIAN_FRONTEND=noninteractive
ENV ANDROID_HOME=/usr/lib/android-sdk
+192
View File
@@ -0,0 +1,192 @@
---
kind: pipeline
type: docker
name: tests-stable
# SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
# SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
steps:
- name: gplay
image: ghcr.io/nextcloud/continuous-integration-android16:latest
privileged: true
environment:
LOG_USERNAME:
from_secret: LOG_USERNAME
LOG_PASSWORD:
from_secret: LOG_PASSWORD
GIT_USERNAME:
from_secret: GIT_USERNAME
GITHUB_TOKEN:
from_secret: GIT_TOKEN
commands:
- scripts/checkIfRunDrone.sh $DRONE_PULL_REQUEST || exit 0
- emulator -avd android -no-snapshot -gpu swiftshader_indirect -no-window -no-audio -skin 500x833 &
- sed -i s'#<bool name="is_beta">false</bool>#<bool name="is_beta">true</bool>#'g app/src/main/res/values/setup.xml
- ./gradlew assembleGplayDebugAndroidTest
- scripts/wait_for_emulator.sh
- ./gradlew installGplayDebugAndroidTest
- scripts/wait_for_server.sh "server"
- scripts/deleteOldComments.sh "stable" "IT" $DRONE_PULL_REQUEST
- ./gradlew createGplayDebugCoverageReport -Pcoverage -Pandroid.testInstrumentationRunnerArguments.notAnnotation=com.owncloud.android.utils.ScreenshotTest || scripts/uploadReport.sh $LOG_USERNAME $LOG_PASSWORD $DRONE_BUILD_NUMBER "stable" "IT" $DRONE_PULL_REQUEST
services:
- name: server
image: ghcr.io/nextcloud/continuous-integration-shallow-server:latest # also change in updateScreenshots.sh
environment:
EVAL: true
SERVER_VERSION: 'stable30'
commands:
- BRANCH="$SERVER_VERSION" /usr/local/bin/initnc.sh
- echo 127.0.0.1 server >> /etc/hosts
- rm /etc/apt/sources.list.d/php.list
- apt-get update && apt-get install -y composer
- su www-data -c "OC_PASS=user1 php /var/www/html/occ user:add --password-from-env --display-name='User One' user1"
- su www-data -c "OC_PASS=user2 php /var/www/html/occ user:add --password-from-env --display-name='User Two' user2"
- su www-data -c "OC_PASS=user3 php /var/www/html/occ user:add --password-from-env --display-name='User Three' user3"
- su www-data -c "php /var/www/html/occ user:setting user2 files quota 1G"
- su www-data -c "php /var/www/html/occ group:add users"
- su www-data -c "php /var/www/html/occ group:adduser users user1"
- su www-data -c "php /var/www/html/occ group:adduser users user2"
- su www-data -c "git clone --depth 1 -b $SERVER_VERSION https://github.com/nextcloud/activity.git /var/www/html/apps/activity/"
- su www-data -c "php /var/www/html/occ app:enable activity"
- su www-data -c "git clone --depth 1 -b $SERVER_VERSION https://github.com/nextcloud/text.git /var/www/html/apps/text/"
- su www-data -c "php /var/www/html/occ app:enable text"
- su www-data -c "git clone --depth 1 -b $SERVER_VERSION https://github.com/nextcloud/end_to_end_encryption.git /var/www/html/apps/end_to_end_encryption/"
- su www-data -c "php /var/www/html/occ app:enable end_to_end_encryption"
- su www-data -c "git clone --depth 1 -b $SERVER_VERSION https://github.com/nextcloud/photos.git /var/www/html/apps/photos/"
- su www-data -c "cd /var/www/html/apps/photos; composer install --no-dev"
- su www-data -c "php /var/www/html/occ app:enable -f photos"
- su www-data -c "php /var/www/html/occ config:system:set ratelimit.protection.enabled --value false --type bool"
- /usr/local/bin/run.sh
trigger:
branch:
- master
- stable-*
event:
- push
- pull_request
---
kind: pipeline
type: docker
name: tests-master
steps:
- name: gplay
image: ghcr.io/nextcloud/continuous-integration-android16:latest
privileged: true
environment:
LOG_USERNAME:
from_secret: LOG_USERNAME
LOG_PASSWORD:
from_secret: LOG_PASSWORD
GIT_USERNAME:
from_secret: GIT_USERNAME
GITHUB_TOKEN:
from_secret: GIT_TOKEN
commands:
- scripts/checkIfRunDrone.sh $DRONE_PULL_REQUEST || exit 0
- emulator -avd android -no-snapshot -gpu swiftshader_indirect -no-window -no-audio -skin 500x833 &
- sed -i s'#<bool name="is_beta">false</bool>#<bool name="is_beta">true</bool>#'g app/src/main/res/values/setup.xml
- scripts/runCombinedTest.sh $DRONE_PULL_REQUEST $LOG_USERNAME $LOG_PASSWORD $DRONE_BUILD_NUMBER
services:
- name: server
image: ghcr.io/nextcloud/continuous-integration-shallow-server:latest # also change in updateScreenshots.sh
environment:
EVAL: true
commands:
- /usr/local/bin/initnc.sh
- echo 127.0.0.1 server >> /etc/hosts
- rm /etc/apt/sources.list.d/php.list
- apt-get update && apt-get install -y composer
- su www-data -c "OC_PASS=user1 php /var/www/html/occ user:add --password-from-env --display-name='User One' user1"
- su www-data -c "OC_PASS=user2 php /var/www/html/occ user:add --password-from-env --display-name='User Two' user2"
- su www-data -c "OC_PASS=user3 php /var/www/html/occ user:add --password-from-env --display-name='User Three' user3"
- su www-data -c "php /var/www/html/occ user:setting user2 files quota 1G"
- su www-data -c "php /var/www/html/occ group:add users"
- su www-data -c "php /var/www/html/occ group:adduser users user1"
- su www-data -c "php /var/www/html/occ group:adduser users user2"
- su www-data -c "git clone --depth 1 -b master https://github.com/nextcloud/activity.git /var/www/html/apps/activity/"
- su www-data -c "php /var/www/html/occ app:enable activity"
- su www-data -c "git clone --depth 1 -b main https://github.com/nextcloud/text.git /var/www/html/apps/text/"
- su www-data -c "php /var/www/html/occ app:enable text"
- su www-data -c "git clone --depth 1 -b master https://github.com/nextcloud/end_to_end_encryption/ /var/www/html/apps/end_to_end_encryption/"
- su www-data -c "php /var/www/html/occ app:enable end_to_end_encryption"
- su www-data -c "git clone --depth 1 https://github.com/nextcloud/photos.git /var/www/html/apps/photos/"
- su www-data -c "cd /var/www/html/apps/photos; composer install --no-dev"
- su www-data -c "php /var/www/html/occ app:enable -f photos"
- su www-data -c "php /var/www/html/occ config:system:set ratelimit.protection.enabled --value false --type bool"
- /usr/local/bin/run.sh
trigger:
branch:
- master
- stable-*
event:
- push
- pull_request
---
kind: pipeline
type: docker
name: allScreenshots
steps:
- name: runAllScreenshots
image: ghcr.io/nextcloud/continuous-integration-android16:latest
privileged: true
environment:
GIT_USERNAME:
from_secret: GIT_USERNAME
GITHUB_TOKEN:
from_secret: GIT_TOKEN
LOG_USERNAME:
from_secret: LOG_USERNAME
LOG_PASSWORD:
from_secret: LOG_PASSWORD
commands:
- emulator -avd android -no-snapshot -gpu swiftshader_indirect -no-window -no-audio -skin 500x833 &
- sed -i s'#<bool name="is_beta">false</bool>#<bool name="is_beta">true</bool>#'g app/src/main/res/values/setup.xml
- sed -i s'#showOnlyFailingTestsInReports = ciBuild#showOnlyFailingTestsInReports = false#' build.gradle.kts
- scripts/wait_for_emulator.sh
- scripts/runAllScreenshotCombinations noCI false
- scripts/screenshotSummary.sh
- name: notify
image: drillster/drone-email
settings:
port: 587
from: [email protected]
recipients_only: true
username:
from_secret: EMAIL_USERNAME
password:
from_secret: EMAIL_PASSWORD
recipients:
from_secret: EMAIL_RECIPIENTS
host:
from_secret: EMAIL_HOST
when:
event:
- push
status:
- failure
branch:
- master
- stable-*
trigger:
event:
- cron
cron:
- allscreenshots
---
kind: secret
name: GIT_TOKEN
data: XIoa9IYq+xQ+N5iln8dlpWv0jV6ROr7HuE24ioUr4uQ8m8SjyH0yognWYLYLqnbTKrFWlFZiEMQTH/sZiWjRFvV1iL0=
---
kind: signature
hmac: de23b70b660e9f78e936d89699fd24777a83c8caaad97d086bbc0c8a0373aa91
...
+1 -8
View File
@@ -16,11 +16,4 @@ B | A
### 🏁 Checklist
- [ ] ⛑️ Tests (unit and/or integration) are included or not needed
- [ ] 🔙 Backport requests are created or not needed: `/backport to stable-xx.x`
- [ ] 📅 Milestone is set
- [ ] 🌸 PR title is meaningful (if it should be in the changelog: is it meaningful to users?)
## 🤖 AI (if applicable)
- [ ] The content of this PR was partly or fully generated using AI (N/A)
- [ ] Tests written, or not not needed
-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
+2 -2
View File
@@ -51,13 +51,13 @@ jobs:
echo "repo=${{ github.event.pull_request.head.repo.full_name }}"
} >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
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@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: "temurin"
java-version: 21
+3 -3
View File
@@ -22,13 +22,13 @@ jobs:
matrix:
flavor: [ Generic, Gplay, Huawei ]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: set up JDK 21
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: "temurin"
java-version: 21
- uses: gradle/actions/wrapper-validation@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
- uses: gradle/actions/wrapper-validation@50e97c2cd7a37755bbfafc9c5b7cafaece252f6e # v6.1.0
- name: Build ${{ matrix.flavor }}
run: |
echo "org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" >> gradle.properties
+1 -1
View File
@@ -26,7 +26,7 @@ permissions:
jobs:
auto-approve:
name: Auto approve sync
runs-on: ubuntu-latest-low
runs-on: ubuntu-latest
if: ${{ contains(github.event.pull_request.labels.*.name, 'sync') && github.actor == 'nextcloud-android-bot' }}
steps:
- name: Disabled on forks
+2 -2
View File
@@ -22,9 +22,9 @@ jobs:
matrix:
task: [ detekt, spotlessKotlinCheck, lint ]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Set up JDK 21
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: "temurin"
java-version: 21
+5 -5
View File
@@ -34,7 +34,7 @@ jobs:
language: [ 'java' ]
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Set Swap Space
@@ -43,18 +43,18 @@ jobs:
with:
swap-size-gb: 10
- name: Initialize CodeQL
uses: github/codeql-action/init@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4.37.9
uses: github/codeql-action/init@e46ed2cbd01164d986452f91f178727624ae40d7 # v4.35.3
with:
languages: ${{ matrix.language }}
- name: Set up JDK 21
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: "temurin"
java-version: 21
- name: Assemble
run: |
mkdir -p "$HOME/.gradle"
echo "org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError" > "$HOME/.gradle/gradle.properties"
echo "org.gradle.jvmargs=-Xmx3g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError" > "$HOME/.gradle/gradle.properties"
./gradlew --no-daemon assembleDebug
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4.37.9
uses: github/codeql-action/analyze@e46ed2cbd01164d986452f91f178727624ae40d7 # v4.35.3
-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
+1 -1
View File
@@ -20,7 +20,7 @@ concurrency:
jobs:
detectNewJavaFiles:
runs-on: ubuntu-latest-low
runs-on: ubuntu-latest
steps:
- id: file_changes
uses: trilom/file-changes-action@a6ca26c14274c33b15e6499323aac178af06ad4b # v1.2.4
+2 -2
View File
@@ -20,9 +20,9 @@ jobs:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Set up JDK 21
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: "temurin"
java-version: 21
-107
View File
@@ -1,107 +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-24.04
services:
server:
image: ${{ matrix.server == 'stable22' && 'ghcr.io/nextcloud/continuous-integration-shallow-server-php8.0:1' || 'ghcr.io/nextcloud/continuous-integration-shallow-server-php8.3:latest' }}
options: --name server
ports:
- 80:80
strategy:
fail-fast: false
matrix:
server: [ master ] # [ stable22, stable33, 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-kvm --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@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
with:
distribution: "temurin"
java-version: 21
- name: Enable KVM group perms
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=kvm
- name: Configure gradle daemon
run: |
mkdir -p $HOME/.gradle
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
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@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
if: ${{ always() }}
with:
name: Report-${{ matrix.server }}-${{ matrix.api-level }}
path: app/build/reports
retention-days: 4
-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>'
+2 -2
View File
@@ -22,7 +22,7 @@ permissions:
jobs:
pr-feedback:
if: ${{ github.repository_owner == 'nextcloud' }}
runs-on: ubuntu-latest-low
runs-on: ubuntu-latest
steps:
- name: The get-github-handles-from-website action
uses: marcelklehr/get-github-handles-from-website-action@06b2239db0a48fe1484ba0bfd966a3ab81a08308 # v1.0.1
@@ -36,7 +36,7 @@ jobs:
blocklist=$(curl https://raw.githubusercontent.com/nextcloud/.github/master/non-community-usernames.txt | paste -s -d, -)
echo "blocklist=$blocklist" >> "$GITHUB_OUTPUT"
- uses: nextcloud/pr-feedback-action@4709fa5b3e1821559d4c312ef937b61f1567aa44 # main
- uses: nextcloud/pr-feedback-action@5227c55be184087d0aef6338bee210d8620b6297 # main
with:
feedback-message: |
Hello there,
+2 -2
View File
@@ -24,13 +24,13 @@ jobs:
id: check-secrets
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
with:
persist-credentials: false
- name: set up JDK 21
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
with:
distribution: "temurin"
+2 -2
View File
@@ -25,7 +25,7 @@ concurrency:
jobs:
auto-approve-merge:
if: github.event.pull_request.user.login == 'renovate[bot]'
runs-on: ubuntu-latest-low
runs-on: ubuntu-latest
permissions:
# for hmarr/auto-approve-action to approve PRs
pull-requests: write
@@ -48,7 +48,7 @@ jobs:
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.head_ref }}
+1 -1
View File
@@ -19,7 +19,7 @@ jobs:
runs-on: ubuntu-latest-low
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
+3 -3
View File
@@ -29,12 +29,12 @@ jobs:
steps:
- name: "Checkout code"
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: "Run analysis"
uses: ossf/scorecard-action@2d1146689b8cda280b9bc96326124645441f03bc # v2.4.4
uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # v2.4.3
with:
results_file: results.sarif
results_format: sarif
@@ -42,6 +42,6 @@ jobs:
# Upload the results to GitHub's code scanning dashboard.
- name: "Upload to code-scanning"
uses: github/codeql-action/upload-sarif@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4.37.9
uses: github/codeql-action/upload-sarif@e46ed2cbd01164d986452f91f178727624ae40d7 # v4.35.3
with:
sarif_file: results.sarif
+6 -6
View File
@@ -25,17 +25,17 @@ jobs:
color: [ blue ]
api-level: [ 28 ]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Gradle cache
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*') }}-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties') }}
- name: AVD cache
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
id: avd-cache
with:
path: |
@@ -43,7 +43,7 @@ jobs:
~/.android/adb*
key: avd-${{ matrix.api-level }}
- uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
- uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: "temurin"
java-version: 21
@@ -56,7 +56,7 @@ jobs:
- name: create AVD and generate snapshot for caching
if: steps.avd-cache.outputs.cache-hit != 'true'
uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d # v2.38.0
uses: reactivecircus/android-emulator-runner@b530d96654c385303d652368551fb075bc2f0b6b # v2.35.0
with:
api-level: ${{ matrix.api-level }}
force-avd-creation: false
@@ -86,7 +86,7 @@ jobs:
- name: Run screenshot tests
env:
SHOT_TEST: "true"
uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d # v2.38.0
uses: reactivecircus/android-emulator-runner@b530d96654c385303d652368551fb075bc2f0b6b # v2.35.0
with:
api-level: ${{ matrix.api-level }}
force-avd-creation: false
+2 -2
View File
@@ -15,12 +15,12 @@ permissions: read-all
jobs:
stale:
runs-on: ubuntu-latest-low
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0
- uses: actions/stale@b5d41d4e1d5dceea10e7104786b73624c18a190f # v10.2.0
with:
days-before-stale: 28
days-before-close: 14
+4 -4
View File
@@ -22,10 +22,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Set up JDK 21
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: "temurin"
java-version: 21
@@ -37,7 +37,7 @@ jobs:
run: scripts/deleteOldComments.sh "test" "Unit" ${{github.event.number}}
- name: Setup Gradle
uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
uses: gradle/actions/setup-gradle@50e97c2cd7a37755bbfafc9c5b7cafaece252f6e # v6.1.0
- name: Run unit tests with coverage
run: ./gradlew jacocoTestGplayDebugUnitTest
@@ -49,7 +49,7 @@ jobs:
run: scripts/uploadReport.sh "${{ secrets.LOG_USERNAME }}" "${{ secrets.LOG_PASSWORD }}" ${{github.event.number}} "test" "Unit" ${{github.event.number}}
- name: Upload coverage to codecov
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0
uses: codecov/codecov-action@57e3a136b779b570ffcdbf80b3bdc90e7fab3de2 # v6.0.0
with:
token: ${{ secrets.CODECOV_TOKEN }}
flags: unit
+25
View File
@@ -2,6 +2,31 @@
<code_scheme name="Project" version="173">
<option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="99" />
<option name="NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND" value="99" />
<option name="PACKAGES_TO_USE_IMPORT_ON_DEMAND">
<value />
</option>
<option name="IMPORT_LAYOUT_TABLE">
<value>
<package name="android" withSubpackages="true" static="false" />
<emptyLine />
<package name="com" withSubpackages="true" static="false" />
<emptyLine />
<package name="junit" withSubpackages="true" static="false" />
<emptyLine />
<package name="net" withSubpackages="true" static="false" />
<emptyLine />
<package name="org" withSubpackages="true" static="false" />
<emptyLine />
<package name="java" withSubpackages="true" static="false" />
<emptyLine />
<package name="javax" withSubpackages="true" static="false" />
<emptyLine />
<package name="" withSubpackages="true" static="false" />
<emptyLine />
<package name="" withSubpackages="true" static="true" />
<emptyLine />
</value>
</option>
<option name="RIGHT_MARGIN" value="120" />
<JavaCodeStyleSettings>
<option name="IMPORT_LAYOUT_TABLE">
-63
View File
@@ -1,63 +0,0 @@
kotlin version: 2.3.0
error message: Daemon compilation failed: Connection to the Kotlin daemon has been unexpectedly lost. This might be caused by the daemon being killed by another process or the operating system, or by JVM crash.
org.jetbrains.kotlin.gradle.tasks.DaemonCrashedException: Connection to the Kotlin daemon has been unexpectedly lost. This might be caused by the daemon being killed by another process or the operating system, or by JVM crash.
at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.wrapCompilationExceptionIfNeeded(tasksUtils.kt:54)
at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.wrapAndRethrowCompilationException(tasksUtils.kt:65)
at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.compileWithDaemon(GradleKotlinCompilerWork.kt:227)
at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.compileWithDaemonOrFallbackImpl(GradleKotlinCompilerWork.kt:143)
at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.run(GradleKotlinCompilerWork.kt:107)
at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction.execute(GradleCompilerRunnerWithWorkers.kt:75)
at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:68)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.create(NoIsolationWorkerFactory.java:64)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.create(NoIsolationWorkerFactory.java:61)
at org.gradle.internal.classloader.ClassLoaderUtils.executeInClassloader(ClassLoaderUtils.java:102)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1.lambda$execute$0(NoIsolationWorkerFactory.java:61)
at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:44)
at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:41)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:209)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:166)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53)
at org.gradle.workers.internal.AbstractWorker.executeWrappedInBuildOperation(AbstractWorker.java:41)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1.execute(NoIsolationWorkerFactory.java:58)
at org.gradle.workers.internal.DefaultWorkerExecutor.lambda$submitWork$0(DefaultWorkerExecutor.java:176)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runExecution(DefaultConditionalExecutionQueue.java:194)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.access$700(DefaultConditionalExecutionQueue.java:127)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner$1.run(DefaultConditionalExecutionQueue.java:169)
at org.gradle.internal.Factories$1.create(Factories.java:30)
at org.gradle.internal.work.DefaultWorkerLeaseService.lambda$withLocksAcquired$0(DefaultWorkerLeaseService.java:269)
at org.gradle.internal.work.ResourceLockStatistics$1.measure(ResourceLockStatistics.java:42)
at org.gradle.internal.work.DefaultWorkerLeaseService.withLocksAcquired(DefaultWorkerLeaseService.java:267)
at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:259)
at org.gradle.internal.work.DefaultWorkerLeaseService.runAsWorkerThread(DefaultWorkerLeaseService.java:127)
at org.gradle.internal.work.DefaultWorkerLeaseService.runAsWorkerThread(DefaultWorkerLeaseService.java:132)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runBatch(DefaultConditionalExecutionQueue.java:164)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.run(DefaultConditionalExecutionQueue.java:133)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:572)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.AbstractManagedExecutor$1.run(AbstractManagedExecutor.java:47)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
at java.base/java.lang.Thread.run(Thread.java:1583)
Caused by: java.rmi.UnmarshalException: Error unmarshaling return header; nested exception is:
java.io.EOFException
at java.rmi/sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:255)
at java.rmi/sun.rmi.server.UnicastRef.invoke(UnicastRef.java:166)
at java.rmi/java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:215)
at java.rmi/java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:160)
at jdk.proxy4/jdk.proxy4.$Proxy184.compile(Unknown Source)
at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.incrementalCompilationWithDaemon(GradleKotlinCompilerWork.kt:312)
at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.compileWithDaemon(GradleKotlinCompilerWork.kt:219)
... 40 more
Caused by: java.io.EOFException
at java.base/java.io.DataInputStream.readUnsignedByte(DataInputStream.java:297)
at java.base/java.io.DataInputStream.readByte(DataInputStream.java:275)
at java.rmi/sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:241)
... 46 more
+14 -60
View File
@@ -30,13 +30,6 @@ Java, Kotlin, XML, Jetpack Compose are the key technologies used for building th
- `./app/src/test/` Unit tests (small, isolated tests without Android SDK)
- `./app/src/androidTest/` Instrumented tests (require Android SDK)
- `./app/src/main/res/values/` Translations. Only update `./app/src/main/res/values/strings.xml`. Do not modify any other translation files or folders. Ignore all `values-*` directories (e.g., `values-es`, `values-fr`).
- `./.claude/skills/` Reusable agent skills. Each subdirectory is one skill with a `SKILL.md` entry point plus `references/` and `assets/`.
## Agent Skills
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.
## General Guidance
@@ -131,32 +124,6 @@ All code is validated with the following tools. Fix findings in modified files:
Run all checks with: `./gradlew check`
## Nextcloud Contribution Policy
All contributions generated or assisted by this agent must fully comply with:
- **[AI Contribution Policy](https://github.com/nextcloud/.github/blob/master/AI_POLICY.md)** - the primary reference for AI-specific rules, covering disclosure, author accountability, communication, security, licensing, code quality, and autonomous agent behavior.
- **[Contribution Guidelines](https://github.com/nextcloud/.github/blob/master/CONTRIBUTING.md)** - covering testing requirements, the Developer Certificate of Origin (DCO), license headers, conventional commits, and translations. These apply in full to all contributions regardless of how they were produced.
### What this agent must always do
- Add an `Assisted-by: AGENT_NAME:MODEL_VERSION` git trailer to every commit containing AI-assisted content.
- Ensure every pull request includes a disclosure of AI tool use in the PR description.
- Produce focused, scoped pull requests that address exactly one concern. Do not touch unrelated files or introduce incidental refactors.
- Verify all dependencies against actual package registries before suggesting them. Do not use hallucinated or unverified package names.
- Explicitly inform the contributor when any action they are about to take, or have taken, would violate the AI Contribution Policy or the Contribution Guidelines. Do not silently proceed. State which rule is at risk and what the contributor should do instead.
- Warn the contributor if a pull request is growing too large. A PR approaching several thousand lines of changed code is a signal that it should be split into smaller, focused PRs. Suggest a logical split before the PR is opened, not after.
- Recommend opening a ticket for discussion before starting implementation whenever a feature or change is sufficiently complex - for example when it touches multiple subsystems, requires architectural decisions, or the right approach is not yet clear. A ticket allows maintainers and the contributor to align on direction before code is written, avoiding wasted effort on a PR that may be rejected or require fundamental rework.
### What this agent must never do
- Open issues, submit pull requests, post review comments, or send security reports autonomously. Every contribution must be reviewed and submitted by a human.
- Add `Signed-off-by` tags to commits. Only the human contributor can certify the Developer Certificate of Origin.
- Generate or submit security reports without independent human verification. Report verified vulnerabilities via [HackerOne](https://hackerone.com/nextcloud), not as GitHub issues.
- Write PR descriptions, review comments, or issue reports on behalf of the contributor. These must be in the contributor's own words.
- Fully automate the resolution of issues labeled [`good first issue`](https://github.com/issues?q=org%3Anextcloud+label%3A%22good+first+issue%22) or similar beginner-friendly labels.
- Submit code that has not been reviewed and cleaned up by the contributor. Dead code, redundant logic, excessive comments, and unrelated changes must be removed before submission.
## Commit and Pull Request Guidelines
### Commits
@@ -165,14 +132,22 @@ All contributions generated or assisted by this agent must fully comply with:
- Commit messages must follow the [Conventional Commits v1.0.0 specification](https://www.conventionalcommits.org/en/v1.0.0/#specification) — e.g. `feat(chat): add voice message playback`, `fix(call): handle MCU disconnect gracefully`.
- Every commit made with AI assistance must include an `Assisted-by: AGENT_NAME:MODEL_VERSION` git trailer identifying the coding agent and model used:
- Every commit made with AI assistance must include an `AI-assistant` trailer identifying the coding agent, its version, and the model(s) used:
```
Assisted-by: ClaudeCode:claude-sonnet-4-6
Assisted-by: Copilot:claude-sonnet-4-6
AI-assistant: Claude Code 2.1.80 (Claude Sonnet 4.6)
AI-assistant: Copilot 1.0.6 (Claude Sonnet 4.6)
```
General pattern: `Assisted-by: <coding-agent>:<model-version>`
General pattern: `AI-assistant: <coding-agent> <agent-version> (<model-name> <model-version>)`
If multiple models are used for different roles, extend the trailer with named roles:
```
AI-assistant: OpenCode v1.0.203 (plan: Claude Opus 4.5, edit: Claude Sonnet 4.5)
```
Pattern with roles: `AI-assistant: <coding-agent> <agent-version> (<role>: <model-name> <model-version>, <role>: <model-name> <model-version>)`
### Pull Requests
@@ -185,7 +160,9 @@ All contributions generated or assisted by this agent must fully comply with:
- Line length: **120 characters**
- Standard Android Studio formatter with EditorConfig.
- Kotlin preferred for new code; legacy Java still present.
- Do not use decorative section-divider comments of any kind (e.g. `// ── Title ───`, `// ------`, `// ======`).
- Every new file must end with exactly one empty trailing line (no more, no less).
- Do not add comments, documentation for every function you created instead make it self explanatory as much as possible.
- Create models, states in different files instead of doing it one single file.
- Do not use magic numbers.
- Apply fail fast principle instead of using nested if-else statements.
@@ -193,26 +170,3 @@ All contributions generated or assisted by this agent must fully comply with:
- Use modern Java for Java classes. Optionals, virtual threads, records, streams if necessary.
- Avoid hardcoded strings, colors, dimensions. Use resources.
- Run lint, spotbugsGplayDebug, detekt, spotlessKotlinCheck and fix findings inside the files that have been changed.
## Comments
Names carry the explanation, not comments. A function or variable whose purpose is not obvious from its
name is a naming problem or a decomposition problem — rename it or split it, do not describe it in a comment.
Assume the reader knows Kotlin, Java and the Android framework.
Write a comment only when the code cannot carry the information itself: a non-obvious invariant, a workaround
for a platform or server bug, an ordering requirement, or a decision whose alternatives look equally valid and
are not. When you do write one, explain **why**, never **what**.
Never write:
- Comments that restate the code (`// increase the counter` above `counter++`).
- KDoc/Javadoc added to a function just because the function is new.
- Narration of the change or its history: "changed from X to Y", "previously this failed", "this is not a
permanent failure so we now retry", "fixes the crash reported in the issue". Comments describe the code as
it is today. A reader six months from now has no access to the issue, the PR discussion, or the conversation
that produced the change — that context belongs in the commit message and the PR description.
- Decorative section-divider comments of any kind (e.g. `// ── Title ───`, `// ------`, `// ======`).
`// region` / `// endregion` for IDE folding is allowed where the file already uses it.
Existing comments that are still accurate stay. Delete the ones the change makes wrong or obsolete.
-1
View File
@@ -1 +0,0 @@
@AGENTS.md
+2 -2
View File
@@ -224,9 +224,9 @@ Source code of app:
- small, isolated tests, with no need of Android SDK
- code coverage can be directly shown via right click on test and select "Run Test with Coverage"
```bash
./gradlew jacocoTestGplayDebugUnitTest
```
./gradlew jacocoTestGplayDebugUnitTest
```bash
#### Instrumented tests
- tests to see larger code working in correct way
+79 -106
View File
@@ -8,8 +8,8 @@ GEM
artifactory (3.0.17)
atomos (0.1.3)
aws-eventstream (1.4.0)
aws-partitions (1.1281.0)
aws-sdk-core (3.254.1)
aws-partitions (1.1241.0)
aws-sdk-core (3.246.0)
aws-eventstream (~> 1, >= 1.3.0)
aws-partitions (~> 1, >= 1.992.0)
aws-sigv4 (~> 1.9)
@@ -17,18 +17,17 @@ GEM
bigdecimal
jmespath (~> 1, >= 1.6.1)
logger
aws-sdk-kms (1.130.0)
aws-sdk-core (~> 3, >= 3.254.0)
aws-sdk-kms (1.123.0)
aws-sdk-core (~> 3, >= 3.244.0)
aws-sigv4 (~> 1.5)
aws-sdk-s3 (1.229.0)
aws-sdk-core (~> 3, >= 3.254.1)
aws-sdk-s3 (1.220.0)
aws-sdk-core (~> 3, >= 3.244.0)
aws-sdk-kms (~> 1)
aws-sigv4 (~> 1.5)
aws-sigv4 (1.12.1)
aws-eventstream (~> 1, >= 1.0.2)
babosa (1.0.4)
base64 (0.3.0)
benchmark (0.5.0)
bigdecimal (3.3.1)
cgi (0.4.2)
claide (1.1.0)
@@ -36,78 +35,82 @@ GEM
colored2 (3.1.2)
commander (4.6.0)
highline (~> 2.0.0)
csv (3.3.6)
csv (3.3.5)
declarative (0.0.20)
digest-crc (0.7.0)
rake (>= 12.0.0, < 14.0.0)
domain_name (0.6.20240107)
dotenv (2.8.1)
emoji_regex (3.2.3)
erb (6.0.7)
excon (0.112.0)
faraday (2.14.3)
faraday-net_http (>= 2.0, < 3.5)
json
logger
faraday (1.10.5)
faraday-em_http (~> 1.0)
faraday-em_synchrony (~> 1.0)
faraday-excon (~> 1.1)
faraday-httpclient (~> 1.0)
faraday-multipart (~> 1.0)
faraday-net_http (~> 1.0)
faraday-net_http_persistent (~> 1.0)
faraday-patron (~> 1.0)
faraday-rack (~> 1.0)
faraday-retry (~> 1.0)
ruby2_keywords (>= 0.0.4)
faraday-cookie_jar (0.0.8)
faraday (>= 0.8.0)
http-cookie (>= 1.0.0)
faraday-follow_redirects (0.5.0)
faraday (>= 1, < 3)
faraday-em_http (1.0.0)
faraday-em_synchrony (1.0.1)
faraday-excon (1.1.0)
faraday-httpclient (1.0.1)
faraday-multipart (1.2.0)
multipart-post (~> 2.0)
faraday-net_http (2.1.0)
faraday-retry (2.4.0)
faraday (~> 2.0)
faraday-net_http (1.0.2)
faraday-net_http_persistent (1.2.0)
faraday-patron (1.0.0)
faraday-rack (1.0.0)
faraday-retry (1.0.4)
faraday_middleware (1.2.1)
faraday (~> 1.0)
fastimage (2.4.1)
fastlane (2.238.0)
CFPropertyList (>= 2.3, < 5.0.0)
abbrev (~> 0.1)
addressable (>= 2.9.0, < 3.0.0)
fastlane (2.229.0)
CFPropertyList (>= 2.3, < 4.0.0)
abbrev (~> 0.1.2)
addressable (>= 2.8, < 3.0.0)
artifactory (~> 3.0)
aws-sdk-s3 (~> 1.197)
aws-sdk-s3 (~> 1.0)
babosa (>= 1.0.3, < 2.0.0)
base64 (~> 0.2)
benchmark (>= 0.1.0)
bundler (>= 2.4.0, < 5.0.0)
bundler (>= 1.12.0, < 3.0.0)
colored (~> 1.2)
commander (~> 4.6)
csv (~> 3.3)
dotenv (>= 2.1.1, < 3.0.0)
emoji_regex (>= 0.1, < 4.0)
excon (>= 0.71.0, < 2.0.0)
faraday (~> 2.7)
faraday-cookie_jar (~> 0.0.8)
faraday-follow_redirects (~> 0.3)
faraday-multipart (~> 1.0)
faraday-retry (~> 2.0)
excon (>= 0.71.0, < 1.0.0)
faraday (~> 1.0)
faraday-cookie_jar (~> 0.0.6)
faraday_middleware (~> 1.0)
fastimage (>= 2.1.0, < 3.0.0)
fastlane-sirp (>= 1.1.0)
fastlane-sirp (>= 1.0.0)
gh_inspector (>= 1.1.2, < 2.0.0)
google-apis-androidpublisher_v3 (~> 0.3)
google-apis-playcustomapp_v1 (~> 0.1)
google-cloud-env (>= 1.6.0, < 2.3.0)
google-cloud-env (>= 1.6.0, < 2.0.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)
logger (>= 1.6, < 2.0)
jwt (>= 2.1.0, < 3)
mini_magick (>= 4.9.4, < 5.0.0)
multi_json (~> 1.12)
multipart-post (>= 2.0.0, < 3.0.0)
mutex_m (~> 0.3)
mutex_m (~> 0.3.0)
naturally (~> 2.2)
nkf (~> 0.2)
optparse (>= 0.1.1, < 1.0.0)
ostruct (>= 0.1.0)
plist (>= 3.1.0, < 4.0.0)
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)
terminal-table (~> 3)
tty-screen (>= 0.6.3, < 1.0.0)
tty-spinner (>= 0.8.0, < 1.0.0)
word_wrap (~> 1.0.0)
@@ -118,114 +121,86 @@ GEM
cgi
fastlane-sirp (1.1.0)
gh_inspector (1.1.3)
google-apis-androidpublisher_v3 (0.106.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-core (0.18.0)
google-apis-androidpublisher_v3 (0.54.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-core (0.11.3)
addressable (~> 2.5, >= 2.5.1)
googleauth (~> 1.9)
httpclient (>= 2.8.3, < 3.a)
googleauth (>= 0.16.2, < 2.a)
httpclient (>= 2.8.1, < 3.a)
mini_mime (~> 1.0)
mutex_m
representable (~> 3.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.66.0)
google-apis-core (>= 0.15.0, < 2.a)
google-cloud-core (1.9.0)
rexml
google-apis-iamcredentials_v1 (0.17.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-playcustomapp_v1 (0.13.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-storage_v1 (0.31.0)
google-apis-core (>= 0.11.0, < 2.a)
google-cloud-core (1.8.0)
google-cloud-env (>= 1.0, < 3.a)
google-cloud-errors (~> 1.0)
google-cloud-env (2.2.2)
base64 (~> 0.2)
faraday (>= 1.0, < 3.a)
google-cloud-errors (1.7.0)
google-cloud-storage (1.62.0)
google-cloud-env (1.6.0)
faraday (>= 0.17.3, < 3.0)
google-cloud-errors (1.6.0)
google-cloud-storage (1.47.0)
addressable (~> 2.8)
digest-crc (~> 0.4)
google-apis-core (>= 0.18, < 2)
google-apis-iamcredentials_v1 (~> 0.18)
google-apis-storage_v1 (>= 0.42)
google-apis-iamcredentials_v1 (~> 0.1)
google-apis-storage_v1 (~> 0.31.0)
google-cloud-core (~> 1.6)
googleauth (~> 1.9)
googleauth (>= 0.16.2, < 2.a)
mini_mime (~> 1.0)
google-logging-utils (0.2.0)
googleauth (1.17.3)
faraday (>= 1.0, < 3.a)
google-cloud-env (~> 2.2)
google-logging-utils (~> 0.1)
jwt (>= 1.4, < 4.0)
googleauth (1.8.1)
faraday (>= 0.17.3, < 3.a)
jwt (>= 1.4, < 3.0)
multi_json (~> 1.11)
os (>= 0.9, < 2.0)
pstore (~> 0.1)
signet (>= 0.16, < 2.a)
highline (2.0.3)
http-cookie (1.0.8)
domain_name (~> 0.5)
httpclient (2.9.0)
mutex_m
io-console (0.9.2)
irb (1.18.0)
pp (>= 0.6.0)
prism (>= 1.3.0)
rdoc (>= 4.0.0)
reline (>= 0.4.2)
jmespath (1.6.2)
json (2.21.2)
jwt (2.10.3)
json (2.19.4)
jwt (2.10.2)
base64
logger (1.7.0)
mini_magick (4.13.2)
mini_mime (1.1.5)
multi_json (1.21.1)
multi_json (1.20.1)
multipart-post (2.4.1)
mutex_m (0.3.0)
nanaimo (0.4.0)
naturally (2.3.0)
nkf (0.3.0)
optparse (0.8.1)
os (1.1.4)
ostruct (0.6.3)
plist (3.7.2)
pp (0.6.4)
prettyprint
prettyprint (0.2.0)
prism (1.9.0)
pstore (0.2.1)
public_suffix (6.0.2)
rake (13.4.2)
rbs (4.1.3)
logger
prism (>= 1.6.0)
tsort
rdoc (8.0.0)
erb
prism (>= 1.6.0)
rbs (>= 4.0.0)
tsort
reline (0.7.0)
io-console (~> 0.5)
representable (3.2.0)
declarative (< 0.1.0)
trailblazer-option (>= 0.1.1, < 0.2.0)
uber (< 0.2.0)
retriable (3.8.0)
retriable (3.4.1)
rexml (3.4.4)
rouge (3.28.0)
ruby2_keywords (0.0.5)
rubyzip (2.4.1)
security (0.1.5)
signet (0.22.0)
signet (0.21.0)
addressable (~> 2.8)
faraday (>= 0.17.5, < 3.a)
jwt (>= 1.5, < 4.0)
multi_json (~> 1.10)
simctl (1.6.10)
CFPropertyList
naturally
terminal-notifier (2.0.0)
terminal-table (4.0.0)
unicode-display_width (>= 1.1.1, < 4)
terminal-table (3.0.2)
unicode-display_width (>= 1.1.1, < 3)
trailblazer-option (0.1.2)
tsort (0.2.0)
tty-cursor (0.7.1)
tty-screen (0.8.2)
tty-spinner (0.9.3)
@@ -233,14 +208,12 @@ GEM
uber (0.1.0)
unicode-display_width (2.6.0)
word_wrap (1.0.0)
xcodeproj (1.28.1)
xcodeproj (1.27.0)
CFPropertyList (>= 2.3.3, < 4.0)
atomos (~> 0.1.3)
base64
claide (>= 1.0.2, < 2.0)
colored2 (~> 3.1)
nanaimo (~> 0.4.0)
nkf
rexml (>= 3.3.6, < 4.0)
xcpretty (0.4.1)
rouge (~> 3.28.0)
-6
View File
@@ -29,12 +29,6 @@ precedence = "aggregate"
SPDX-FileCopyrightText = "2015-2016 ownCloud Inc."
SPDX-License-Identifier = "GPL-2.0-only"
[[annotations]]
path = ["CLAUDE.md", "app/libs/local-maven/**/*.aar", "app/libs/local-maven/**/*.pom"]
precedence = "aggregate"
SPDX-FileCopyrightText = "2026 Nextcloud GmbH and Nextcloud contributors"
SPDX-License-Identifier = "AGPL-3.0-or-later"
[[annotations]]
path = ["app/src/**/res/mipmap-**dpi/ic_launcher.png", "app/src/**/ic_launcher-web.png", "src/**/fastlane/metadata/en-US/images/*.png", "src/generic/fastlane/metadata/android/en-US/images/icon.png", "src/versionDev/fastlane/metadata/android/en-US/images/icon.png", "app/src/main/ic_launcher-web-round.png"]
precedence = "aggregate"
+25 -57
View File
@@ -1,7 +1,6 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
* SPDX-FileCopyrightText: 2025 Jimly Asshiddiqy <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
@@ -44,35 +43,26 @@ configurations.configureEach {
exclude(group = "org.jetbrains", module = "annotations-java5")
resolutionStrategy {
force(libs.objenesis)
eachDependency {
when (requested.group) {
"org.checkerframework" if requested.name != "checker-compat-qual" -> {
useVersion(libs.versions.checker.get())
because("https://github.com/google/ExoPlayer/issues/10007")
}
"org.jacoco" -> {
useVersion(libs.versions.jacoco.get())
}
"commons-logging" if requested.name == "commons-logging" -> {
useTarget(libs.slfj)
}
"org.hamcrest" -> {
useVersion("2.2")
because(
"Align hamcrest on compile and runtime. 1.3 (via junit) exposes fixed-arity " +
"anyOf/allOf overloads that 2.2 (via androidx.test) removed, causing NoSuchMethodError."
)
}
if (requested.group == "org.checkerframework" && requested.name != "checker-compat-qual") {
useVersion(libs.versions.checker.get())
because("https://github.com/google/ExoPlayer/issues/10007")
} else if (requested.group == "org.jacoco") {
useVersion(libs.versions.jacoco.get())
} else if (requested.group == "commons-logging" && requested.name == "commons-logging") {
useTarget(libs.slfj)
}
}
}
}
// semantic versioning for version code
val versionMajor = 35
val versionMinor = 0
val versionMajor = 33
val versionMinor = 2
val versionPatch = 0
val versionBuild = 50 // 0-50=Alpha / 51-98=RC / 90-99=stable
val versionBuild = 0 // 0-50=Alpha / 51-98=RC / 90-99=stable
val ndkEnv = buildMap {
file("${project.rootDir}/ndk.env").readLines().forEach {
@@ -96,7 +86,6 @@ android {
externalNativeBuild {
cmake {
version = "${ndkEnv["CMAKE_VERSION"]}"
path = file("src/main/cpp/CMakeLists.txt")
}
}
@@ -115,10 +104,10 @@ android {
applicationId = "com.nextcloud.client"
minSdk = 28
targetSdk = 36
compileSdk = 37
compileSdk = 36
ndk {
abiFilters += listOf("arm64-v8a", "x86_64")
abiFilters += listOf("arm64-v8a", "x86_64", "x86")
}
buildConfigField("boolean", "CI", ciBuild.toString())
@@ -172,8 +161,8 @@ android {
register("versionDev") {
applicationId = "com.nextcloud.android.beta"
dimension = "default"
versionCode = 20260902
versionName = "20260902"
versionCode = 20220322
versionName = "20220322"
}
register("qa") {
@@ -203,7 +192,6 @@ android {
viewBinding = true
aidl = true
compose = true
prefab = true
}
compileOptions {
@@ -230,8 +218,7 @@ android {
"IconXmlAndPng",
"SelectedPhotoAccess",
"UnsafeIntentLaunch",
"OldTargetApi",
"AndroidGradlePluginVersion"
"OldTargetApi"
)
)
htmlOutput = layout.buildDirectory.file("reports/lint/lint.html").get().asFile
@@ -276,7 +263,6 @@ spotbugs {
}
tasks.register<Checkstyle>("checkstyle") {
description = "Runs Checkstyle static analysis on the Java sources to enforce the project's coding style."
configFile = file("${rootProject.projectDir}/checkstyle.xml")
setConfigProperties(
"checkstyleSuppressionsPath" to file("${rootProject.rootDir}/suppressions.xml").absolutePath
@@ -288,7 +274,6 @@ tasks.register<Checkstyle>("checkstyle") {
}
tasks.register<Pmd>("pmd") {
description = "Runs PMD static analysis on the Java sources to detect common programming flaws and bad practices."
ruleSetFiles = files("${rootProject.rootDir}/ruleset.xml")
ignoreFailures = true // should continue checking
ruleSets = emptyList()
@@ -344,17 +329,6 @@ tasks.named("check").configure {
dependsOn("checkstyle", "spotbugsGplayDebug", "pmd", "lint", "spotlessKotlinCheck", "detekt")
}
val kspConfiguration = "ksp"
val kspAndroidTestConfiguration = "kspAndroidTest"
val gplayImplementationConfiguration = "gplayImplementation"
val huaweiImplementationConfiguration = "huaweiImplementation"
val qaImplementationConfiguration = "qaImplementation"
val appScanConfigurations = listOf(
gplayImplementationConfiguration,
huaweiImplementationConfiguration,
qaImplementationConfiguration
)
dependencies {
// region Nextcloud library
implementation(libs.android.library) {
@@ -399,7 +373,6 @@ dependencies {
// region UI
implementation(libs.bundles.ui)
implementation(libs.browser)
// endregion
// region Worker
@@ -418,13 +391,10 @@ dependencies {
androidTestImplementation(libs.rules)
androidTestImplementation(libs.runner)
androidTestUtil(libs.orchestrator)
androidTestImplementation(libs.test.core)
androidTestImplementation(libs.core.ktx)
androidTestImplementation(libs.core.testing)
// endregion
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
@@ -452,10 +422,10 @@ dependencies {
// endregion
// region AppScan, document scanner not available on FDroid (generic) due to OpenCV binaries
// To enable the feature for another variant, add its "<variant>Implementation" here.
appScanConfigurations.forEach { configuration ->
add(configuration, project(":appscan"))
}
// To enable the feature for another variant, add it here.
"gplayImplementation"(project(":appscan"))
"huaweiImplementation"(project(":appscan"))
"qaImplementation"(project(":appscan"))
// endregion
// region SpotBugs
@@ -467,15 +437,13 @@ dependencies {
implementation(libs.dagger)
implementation(libs.dagger.android)
implementation(libs.dagger.android.support)
ksp(libs.dagger.compiler)
ksp(libs.dagger.processor)
listOf(kspConfiguration, kspAndroidTestConfiguration).forEach { configuration ->
add(configuration, libs.dagger.compiler)
}
kspAndroidTest(libs.dagger.compiler)
// endregion
// region Crypto
implementation(libs.conscrypt.android)
implementation(libs.android.openssl)
// endregion
// region Library
@@ -500,7 +468,7 @@ dependencies {
// region iCal4j
implementation(libs.ical4j) {
exclude(group = "commons-logging")
listOf("org.apache.commons", "commons-logging").forEach { groupName -> exclude(group = groupName) }
}
// endregion
@@ -533,7 +501,7 @@ dependencies {
// endregion
// region Google Play dependencies, upon each update first test: new registration, receive push
add(gplayImplementationConfiguration, libs.bundles.gplay)
"gplayImplementation"(libs.bundles.gplay)
// endregion
// region common
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -33,7 +33,8 @@ class FileDisplayActivityScreenshotIT : AbstractIT() {
@get:Rule
val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.POST_NOTIFICATIONS
)
companion object {
@@ -9,6 +9,7 @@
package com.nextcloud.client
import android.content.Intent
import android.os.Looper
import androidx.test.core.app.launchActivity
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
@@ -60,8 +61,12 @@ class SettingsActivityIT : AbstractIT() {
}
}
@Suppress("DEPRECATION")
@Test
fun showMnemonic() {
if (Looper.myLooper() == null) {
Looper.prepare()
}
val intent = Intent().apply {
putExtra(RequestCredentialsActivity.KEY_CHECK_RESULT, RequestCredentialsActivity.KEY_CHECK_RESULT_TRUE)
}
@@ -71,10 +76,13 @@ class SettingsActivityIT : AbstractIT() {
}
launchActivity<SettingsActivity>().use { scenario ->
onView(isRoot()).check(matches(isDisplayed()))
scenario.onActivity { sut ->
sut.handleMnemonicRequest(intent)
}
Looper.myLooper()?.quitSafely()
Assert.assertTrue(true)
}
}
@@ -87,13 +87,17 @@ class AssistantRepositoryTests : AbstractOnServerIT() {
testCreateTask()
sleep(120)
runBlocking {
val taskList = sut?.getTaskList("assistant")
assertTrue(taskList != null)
val taskId = taskList?.firstOrNull()?.id ?: return@runBlocking
sleep(120)
val result = sut?.deleteTask(taskId)
assert((taskList?.size ?: 0) > 0)
val result = sut?.deleteTask(taskList!!.first().id)
assertTrue(result?.isSuccess == true)
}
}
@@ -115,9 +115,9 @@ class ContactsBackupIT : AbstractOnServerIT() {
fail("ocFile.storagePath cannot be null")
}
assertTrue(DownloadFileOperation(user, ocFile!!, targetContext).execute(client).isSuccess)
assertTrue(DownloadFileOperation(user, ocFile, targetContext).execute(client).isSuccess)
val file = ocFile.storagePath?.let { File(it) }
val file = ocFile?.storagePath?.let { File(it) }
if (file == null) {
fail("file cannot be null")
}
@@ -9,9 +9,10 @@ package com.nextcloud.client.network
import android.accounts.AccountManager
import android.content.Context
import android.net.ConnectivityManager
import com.nextcloud.client.account.UserAccountManagerImpl
import com.nextcloud.client.core.ClockImpl
import com.nextcloud.client.network.ConnectivityServiceImpl.GetRequestBuilder
import com.nextcloud.operations.GetMethod
import com.owncloud.android.AbstractOnServerIT
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
@@ -20,14 +21,15 @@ import org.junit.Test
class ConnectivityServiceImplIT : AbstractOnServerIT() {
@Test
fun testInternetWalled() {
val connectivityManager = targetContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val accountManager = targetContext.getSystemService(Context.ACCOUNT_SERVICE) as AccountManager
val userAccountManager = UserAccountManagerImpl(targetContext, accountManager)
val clientFactory = ClientFactoryImpl(targetContext)
val requestBuilder = GetRequestBuilder { url -> GetMethod(url, false) }
val walledCheckCache = WalledCheckCache()
val requestBuilder = GetRequestBuilder()
val walledCheckCache = WalledCheckCache(ClockImpl())
val sut = ConnectivityServiceImpl(
targetContext,
connectivityManager,
userAccountManager,
clientFactory,
requestBuilder,
@@ -35,6 +37,6 @@ class ConnectivityServiceImplIT : AbstractOnServerIT() {
)
assertTrue(sut.connectivity.isConnected)
assertFalse(sut.isInternetWalled())
assertFalse(sut.isInternetWalled)
}
}
@@ -0,0 +1,23 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Philipp Hasper <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.test
import com.nextcloud.client.network.Connectivity
import com.nextcloud.client.network.ConnectivityService
/** A mocked connectivity service returning that the device is offline **/
class ConnectivityServiceOfflineMock : ConnectivityService {
override fun isNetworkAndServerAvailable(callback: ConnectivityService.GenericCallback<Boolean>) {
callback.onComplete(false)
}
override fun isConnected(): Boolean = false
override fun isInternetWalled(): Boolean = false
override fun getConnectivity(): Connectivity = Connectivity.CONNECTED_WIFI
}
@@ -1,51 +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 android.os.ParcelFileDescriptor
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
/**
* Disables system animations for the duration of the test.
*
* Espresso requires that no view keeps requesting layout while it waits for the root window. Animated components such
* as [com.google.android.material.snackbar.Snackbar] keep animating unless the global animation scales are set to zero.
* The Gradle `animationsDisabled` option only passes `--no-window-animation`, which leaves `animator_duration_scale`
* untouched, so animations still run on CI. This rule zeroes all scales directly via a shell command.
*/
class DisableAnimationsRule : TestRule {
override fun apply(base: Statement, description: Description): Statement = object : Statement() {
override fun evaluate() {
setAnimationScale("0.0")
try {
base.evaluate()
} finally {
setAnimationScale("1.0")
}
}
}
private fun setAnimationScale(scale: String) {
val uiAutomation = InstrumentationRegistry.getInstrumentation().uiAutomation
SCALE_SETTINGS.forEach { setting ->
val descriptor = uiAutomation.executeShellCommand("settings put global $setting $scale")
ParcelFileDescriptor.AutoCloseInputStream(descriptor).use { it.readBytes() }
}
}
companion object {
private val SCALE_SETTINGS = listOf(
"window_animation_scale",
"transition_animation_scale",
"animator_duration_scale"
)
}
}
@@ -25,17 +25,19 @@ import kotlin.random.Random
@Suppress("TooManyFunctions", "MagicNumber")
class FileDeletionTests : AbstractIT() {
private val createdFilePaths = mutableListOf<String>()
private lateinit var tempDir: File
@Before
fun setup() {
createdFilePaths.clear()
val parent = System.getProperty("java.io.tmpdir")
val childPath = "file_deletion_test_${System.currentTimeMillis()}"
tempDir = File(parent, childPath)
tempDir.mkdirs()
}
@After
fun cleanup() {
createdFilePaths.forEach { File(it).delete() }
createdFilePaths.clear()
tempDir.deleteRecursively()
}
private fun getRandomRemoteId(): String = Random
@@ -43,17 +45,6 @@ class FileDeletionTests : AbstractIT() {
.toString()
.padEnd(32, '0')
private fun createFileAtExpectedPath(ocFile: OCFile, content: String = "Temporary test content"): File {
val expectedPath = FileStorageUtils.getDefaultSavePathFor(user.accountName, ocFile)
val localFile = File(expectedPath).apply {
parentFile?.mkdirs()
createNewFile()
writeText(content)
}
createdFilePaths.add(localFile.absolutePath)
return localFile
}
private fun createAndSaveSingleFileWithLocalCopy(): OCFile {
val now = System.currentTimeMillis()
@@ -68,7 +59,11 @@ class FileDeletionTests : AbstractIT() {
permissions = "RWDNV"
}
val localFile = createFileAtExpectedPath(file)
val localFile = File(tempDir, "TestFile_${file.fileId}.txt").apply {
parentFile?.mkdirs()
createNewFile()
writeText("Temporary test content")
}
file.storagePath = localFile.absolutePath
storageManager.saveFile(file)
@@ -122,11 +117,11 @@ class FileDeletionTests : AbstractIT() {
listOf(rootFolder, subFolder, file1, file2).forEach { storageManager.saveFile(it) }
val localFile1 = createFileAtExpectedPath(file1)
val localFile2 = createFileAtExpectedPath(file2)
val file1Path = File(tempDir, "file1_${file1.fileId}.txt").apply { createNewFile() }
val file2Path = File(tempDir, "file2_${file2.fileId}.txt").apply { createNewFile() }
file1.storagePath = localFile1.absolutePath
file2.storagePath = localFile2.absolutePath
file1.storagePath = file1Path.absolutePath
file2.storagePath = file2Path.absolutePath
storageManager.saveFile(file1)
storageManager.saveFile(file2)
@@ -137,85 +132,69 @@ class FileDeletionTests : AbstractIT() {
private fun getMixedOcFiles(): List<OCFile> {
val now = System.currentTimeMillis()
fun saveFolder(parentId: Long, path: String): OCFile = OCFile(path).apply {
fun createFolder(id: Long, parentId: Long, path: String): OCFile = OCFile(path).apply {
fileId = id
this.parentId = parentId
remoteId = getRandomRemoteId()
mimeType = MimeType.DIRECTORY
creationTimestamp = now
modificationTimestamp = now
permissions = "RWDNVCK"
}.also { storageManager.saveFile(it) }
fun saveFileWithLocalCopy(parentId: Long, path: String, size: Long, mime: String): OCFile {
val ocFile = OCFile(path).apply {
this.parentId = parentId
remoteId = getRandomRemoteId()
fileLength = size
creationTimestamp = now
mimeType = mime
modificationTimestamp = now
permissions = "RWDNV"
storagePath = FileStorageUtils.getDefaultSavePathFor(user.accountName, this)
}
val localFile = File(ocFile.storagePath).apply {
parentFile?.mkdirs()
createNewFile()
writeText("test content")
}
createdFilePaths.add(localFile.absolutePath)
storageManager.saveFile(ocFile)
return ocFile
}
val root = saveFolder(0, "/")
val documents = saveFolder(root.fileId, "/Documents")
val photos = saveFolder(root.fileId, "/Photos")
val temp = saveFolder(root.fileId, "/Temp")
val projects = saveFolder(documents.fileId, "/Documents/Projects")
val vacation = saveFolder(photos.fileId, "/Photos/Vacation")
val archive = saveFolder(projects.fileId, "/Documents/Projects/Archive")
val nested = saveFolder(temp.fileId, "/Temp/Nested")
val emptyFolder = saveFolder(photos.fileId, "/Photos/EmptyFolder")
fun createFile(id: Long, parentId: Long, path: String, size: Long, mime: String): OCFile = OCFile(path).apply {
fileId = id
this.parentId = parentId
remoteId = getRandomRemoteId()
fileLength = size
creationTimestamp = now
mimeType = mime
modificationTimestamp = now
permissions = "RWDNV"
}
val allEntries = mutableListOf(root, documents, photos, temp, projects, vacation, archive, nested, emptyFolder)
val list = mutableListOf<OCFile>()
allEntries.add(
saveFileWithLocalCopy(
projects.fileId,
"/Documents/Projects/spec.txt",
12000,
MimeType.TEXT_PLAIN
)
)
allEntries.add(saveFileWithLocalCopy(vacation.fileId, "/Photos/Vacation/img2.jpg", 300000, MimeType.JPEG))
allEntries.add(saveFileWithLocalCopy(documents.fileId, "/Documents/example.pdf", 150000, MimeType.PDF))
allEntries.add(saveFileWithLocalCopy(photos.fileId, "/Photos/cover.png", 80000, MimeType.PNG))
allEntries.add(
saveFileWithLocalCopy(
projects.fileId,
"/Documents/Projects/readme.txt",
2000,
MimeType.TEXT_PLAIN
)
)
allEntries.add(
saveFileWithLocalCopy(
archive.fileId,
"/Documents/Projects/Archive/old.bmp",
900000,
MimeType.BMP
)
)
allEntries.add(saveFileWithLocalCopy(vacation.fileId, "/Photos/Vacation/img1.jpg", 250000, MimeType.JPEG))
allEntries.add(saveFileWithLocalCopy(temp.fileId, "/Temp/tmp_file_1.txt", 400, MimeType.TEXT_PLAIN))
allEntries.add(saveFileWithLocalCopy(temp.fileId, "/Temp/tmp_file_2.txt", 800, MimeType.TEXT_PLAIN))
allEntries.add(saveFileWithLocalCopy(nested.fileId, "/Temp/Nested/deep.txt", 100, MimeType.TEXT_PLAIN))
allEntries.add(saveFileWithLocalCopy(documents.fileId, "/Documents/notes.txt", 1500, MimeType.TEXT_PLAIN))
list.add(createFolder(1, 0, "/"))
return allEntries.sortedWith(
compareBy<OCFile> { it.isFolder }
.thenByDescending { it.remotePath.count { c -> c == '/' } }
)
list.add(createFolder(5, 2, "/Documents/Projects"))
list.add(createFile(9, 5, "/Documents/Projects/spec.txt", 12000, MimeType.TEXT_PLAIN))
list.add(createFolder(2, 1, "/Documents"))
list.add(createFile(11, 7, "/Photos/Vacation/img2.jpg", 300000, MimeType.JPEG))
list.add(createFolder(7, 3, "/Photos/Vacation"))
list.add(createFile(4, 2, "/Documents/example.pdf", 150000, MimeType.PDF))
list.add(createFolder(3, 1, "/Photos"))
list.add(createFile(12, 3, "/Photos/cover.png", 80000, MimeType.PNG))
list.add(createFile(6, 5, "/Documents/Projects/readme.txt", 2000, MimeType.TEXT_PLAIN))
list.add(createFolder(8, 5, "/Documents/Projects/Archive"))
list.add(createFile(13, 8, "/Documents/Projects/Archive/old.bmp", 900000, MimeType.BMP))
list.add(createFile(10, 7, "/Photos/Vacation/img1.jpg", 250000, MimeType.JPEG))
list.add(createFolder(14, 1, "/Temp"))
list.add(createFile(15, 14, "/Temp/tmp_file_1.txt", 400, MimeType.TEXT_PLAIN))
list.add(createFile(16, 14, "/Temp/tmp_file_2.txt", 800, MimeType.TEXT_PLAIN))
list.add(createFolder(17, 14, "/Temp/Nested"))
list.add(createFile(18, 17, "/Temp/Nested/deep.txt", 100, MimeType.TEXT_PLAIN))
list.add(createFile(19, 2, "/Documents/notes.txt", 1500, MimeType.TEXT_PLAIN))
list.add(createFolder(20, 3, "/Photos/EmptyFolder"))
list.forEach { ocFile ->
if (!ocFile.isFolder) {
val localFile = File(tempDir, ocFile.remoteId).apply {
parentFile?.mkdirs()
createNewFile()
writeText("test content")
}
ocFile.storagePath = localFile.absolutePath
storageManager.saveFile(ocFile)
} else {
// For folders, create the folder in tempDir
val localFolder = File(tempDir, ocFile.remoteId).apply { mkdirs() }
ocFile.storagePath = localFolder.absolutePath
storageManager.saveFile(ocFile)
}
}
return list
}
@Test
@@ -9,6 +9,7 @@ package com.nextcloud.test
import androidx.test.espresso.IdlingResource
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicReference
/**
@@ -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 Flaky(val reason: String)
@@ -1,36 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.test
import android.Manifest
import android.os.Build
import androidx.test.rule.GrantPermissionRule
/**
* Grants the runtime permissions UI tests need, matching what the manifest actually declares:
*
* - WRITE_EXTERNAL_STORAGE is capped at maxSdkVersion="29", so on API 30+ the app never requests it
* and granting it throws "has not requested permission WRITE_EXTERNAL_STORAGE". It is therefore
* granted only when SDK_INT <= 29.
* - POST_NOTIFICATIONS only exists on API 33+, so granting it on lower API levels fails with
* "Unknown permission" and it is granted only from TIRAMISU onwards.
*/
object GrantTestPermissionRule {
fun grantStorageAndNotification(): GrantPermissionRule {
val permissions = buildList {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) {
add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
add(Manifest.permission.POST_NOTIFICATIONS)
}
}
@Suppress("SpreadOperator")
return GrantPermissionRule.grant(*permissions.toTypedArray())
}
}
@@ -27,7 +27,10 @@ import org.junit.Test
class SetOnlineStatusBottomSheetIT : AbstractIT() {
@get:Rule
val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(Manifest.permission.WRITE_EXTERNAL_STORAGE)
val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.POST_NOTIFICATIONS
)
@Test
fun open() {
@@ -8,6 +8,7 @@
*/
package com.nextcloud.ui
import android.Manifest
import androidx.test.core.app.launchActivity
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
@@ -15,8 +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.test.Flaky
import com.nextcloud.test.GrantTestPermissionRule
import com.owncloud.android.AbstractIT
import com.owncloud.android.R
import com.owncloud.android.lib.resources.users.ClearAt
@@ -29,10 +28,12 @@ import org.junit.Test
class SetStatusMessageBottomSheetIT : AbstractIT() {
@get:Rule
val permissionRule: GrantPermissionRule = GrantTestPermissionRule.grantStorageAndNotification()
val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.POST_NOTIFICATIONS
)
@Test
@Flaky(reason = "Bottom sheet is occasionally not rendered before the assertions run")
fun open() {
launchActivity<FileDisplayActivity>().use { scenario ->
onView(isRoot()).check(matches(isDisplayed()))
@@ -8,7 +8,6 @@ package com.nextcloud.utils
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertTrue
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Before
import org.junit.Test
@@ -30,131 +29,176 @@ class FileHelperTest {
testDirectory.deleteRecursively()
}
private fun collectPages(directory: File?, pageSize: Int, fetchFolders: Boolean): List<List<File>> {
val pages = mutableListOf<List<File>>()
runBlocking {
FileHelper.forEachDirectoryPage(directory, pageSize, fetchFolders) { page ->
pages.add(page)
}
}
return pages
@Test
fun testListDirectoryEntriesWhenGivenNullDirectoryShouldReturnEmptyList() {
val result = FileHelper.listDirectoryEntries(null, 0, 10, false)
assertTrue(result.isEmpty())
}
@Test
fun testForEachDirectoryPageWhenGivenNullDirectoryShouldReportNoPage() {
assertTrue(collectPages(null, 10, false).isEmpty())
}
@Test
fun testForEachDirectoryPageWhenGivenNonExistentDirectoryShouldReportNoPage() {
fun testListDirectoryEntriesWhenGivenNonExistentDirectoryShouldReturnEmptyList() {
val nonExistent = File(testDirectory, "does_not_exist")
assertTrue(collectPages(nonExistent, 10, false).isEmpty())
val result = FileHelper.listDirectoryEntries(nonExistent, 0, 10, false)
assertTrue(result.isEmpty())
}
@Test
fun testForEachDirectoryPageWhenGivenFileInsteadOfDirectoryShouldReportNoPage() {
fun testListDirectoryEntriesWhenGivenFileInsteadOfDirectoryShouldReturnEmptyList() {
val file = File(testDirectory, "test.txt")
file.createNewFile()
assertTrue(collectPages(file, 10, false).isEmpty())
val result = FileHelper.listDirectoryEntries(file, 0, 10, false)
assertTrue(result.isEmpty())
}
@Test
fun testForEachDirectoryPageWhenGivenEmptyDirectoryShouldReportNoPage() {
assertTrue(collectPages(testDirectory, 10, false).isEmpty())
fun testListDirectoryEntriesWhenGivenEmptyDirectoryShouldReturnEmptyList() {
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 10, false)
assertTrue(result.isEmpty())
}
@Test
fun testForEachDirectoryPageWhenPageSizeIsZeroShouldReportNoPage() {
fun testListDirectoryEntriesWhenFetchingFoldersShouldReturnOnlyFolders() {
File(testDirectory, "folder1").mkdir()
File(testDirectory, "folder2").mkdir()
File(testDirectory, "file1.txt").createNewFile()
File(testDirectory, "file2.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 10, true)
assertEquals(2, result.size)
assertTrue(result.all { it.isDirectory })
}
@Test
fun testListDirectoryEntriesWhenFetchingFilesShouldReturnOnlyFiles() {
File(testDirectory, "folder1").mkdir()
File(testDirectory, "folder2").mkdir()
File(testDirectory, "file1.txt").createNewFile()
File(testDirectory, "file2.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 10, false)
assertEquals(2, result.size)
assertTrue(result.all { it.isFile })
}
@Test
fun testListDirectoryEntriesWhenStartIndexProvidedShouldSkipCorrectNumberOfItems() {
for (i in 1..5) File(testDirectory, "file$i.txt").createNewFile()
assertTrue(collectPages(testDirectory, 0, false).isEmpty())
val result = FileHelper.listDirectoryEntries(testDirectory, 2, 10, false)
assertEquals(3, result.size)
}
@Test
fun testForEachDirectoryPageWhenFetchingFoldersShouldReportOnlyFolders() {
File(testDirectory, "folder1").mkdir()
File(testDirectory, "folder2").mkdir()
File(testDirectory, "file1.txt").createNewFile()
File(testDirectory, "file2.txt").createNewFile()
val entries = collectPages(testDirectory, 10, true).flatten()
assertEquals(2, entries.size)
assertTrue(entries.all { it.isDirectory })
fun testListDirectoryEntriesWhenMaxItemsProvidedShouldLimitResults() {
for (i in 1..10) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 5, false)
assertEquals(5, result.size)
}
@Test
fun testForEachDirectoryPageWhenFetchingFilesShouldReportOnlyFiles() {
File(testDirectory, "folder1").mkdir()
File(testDirectory, "folder2").mkdir()
File(testDirectory, "file1.txt").createNewFile()
File(testDirectory, "file2.txt").createNewFile()
val entries = collectPages(testDirectory, 10, false).flatten()
assertEquals(2, entries.size)
assertTrue(entries.all { it.isFile })
fun testListDirectoryEntriesWhenGivenStartIndexAndMaxItemsShouldReturnCorrectSubset() {
for (i in 1..10) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 3, 4, false)
assertEquals(4, result.size)
}
@Test
fun testForEachDirectoryPageWhenGivenOnlyFoldersAndFetchingFilesShouldReportNoPage() {
fun testListDirectoryEntriesWhenStartIndexBeyondAvailableShouldReturnEmptyList() {
for (i in 1..3) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 10, 5, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenMaxItemsBeyondAvailableShouldReturnAllItems() {
for (i in 1..3) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 100, false)
assertEquals(3, result.size)
}
@Test
fun testListDirectoryEntriesWhenFetchingFoldersWithOffsetShouldSkipCorrectly() {
for (i in 1..5) File(testDirectory, "folder$i").mkdir()
assertTrue(collectPages(testDirectory, 10, false).isEmpty())
}
@Test
fun testForEachDirectoryPageWhenGivenOnlyFilesAndFetchingFoldersShouldReportNoPage() {
for (i in 1..5) File(testDirectory, "file$i.txt").createNewFile()
assertTrue(collectPages(testDirectory, 10, true).isEmpty())
}
@Test
fun testForEachDirectoryPageWhenPageSizeExceedsContentShouldReportSinglePage() {
for (i in 1..3) File(testDirectory, "file$i.txt").createNewFile()
val pages = collectPages(testDirectory, 100, false)
val result = FileHelper.listDirectoryEntries(testDirectory, 2, 10, true)
assertEquals(1, pages.size)
assertEquals(3, pages.first().size)
assertEquals(3, result.size)
assertTrue(result.all { it.isDirectory })
}
@Test
fun testForEachDirectoryPageWhenPaginatingFoldersShouldFillEveryPageButTheLast() {
for (i in 1..10) File(testDirectory, "folder$i").mkdir()
fun testListDirectoryEntriesWhenFetchingFilesWithOffsetShouldSkipCorrectly() {
for (i in 1..3) File(testDirectory, "folder$i").mkdir()
for (i in 1..5) File(testDirectory, "file$i.txt").createNewFile()
val pages = collectPages(testDirectory, 3, true)
val result = FileHelper.listDirectoryEntries(testDirectory, 2, 10, false)
assertEquals(listOf(3, 3, 3, 1), pages.map { it.size })
assertEquals(3, result.size)
assertTrue(result.all { it.isFile })
}
@Test
fun testForEachDirectoryPageWhenContentIsAMultipleOfPageSizeShouldNotReportAnEmptyPage() {
for (i in 1..9) File(testDirectory, "file$i.txt").createNewFile()
val pages = collectPages(testDirectory, 3, false)
assertEquals(listOf(3, 3, 3), pages.map { it.size })
fun testListDirectoryEntriesWhenGivenOnlyFoldersAndFetchingFilesShouldReturnEmptyList() {
for (i in 1..5) File(testDirectory, "folder$i").mkdir()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 10, false)
assertTrue(result.isEmpty())
}
@Test
fun testForEachDirectoryPageWhenGivenMixedContentShouldReportEveryEntryExactlyOnce() {
fun testListDirectoryEntriesWhenGivenOnlyFilesAndFetchingFoldersShouldReturnEmptyList() {
for (i in 1..5) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 10, true)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenMaxItemsIsZeroShouldReturnEmptyList() {
for (i in 1..5) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 0, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenGivenMixedContentShouldFilterCorrectly() {
for (i in 1..3) File(testDirectory, "folder$i").mkdir()
for (i in 1..7) File(testDirectory, "file$i.txt").createNewFile()
val folders = collectPages(testDirectory, 2, true).flatten()
val files = collectPages(testDirectory, 2, false).flatten()
val folders = FileHelper.listDirectoryEntries(testDirectory, 0, 10, true)
val files = FileHelper.listDirectoryEntries(testDirectory, 0, 10, false)
assertEquals(3, folders.size)
assertEquals(7, files.size)
assertEquals(folders.size, folders.distinct().size)
assertEquals(files.size, files.distinct().size)
assertTrue(folders.all { it.isDirectory })
assertTrue(files.all { it.isFile })
}
@Test
fun testListDirectoryEntriesWhenPaginatingFoldersShouldWorkCorrectly() {
for (i in 1..10) File(testDirectory, "folder$i").mkdir()
val page1 = FileHelper.listDirectoryEntries(testDirectory, 0, 3, true)
val page2 = FileHelper.listDirectoryEntries(testDirectory, 3, 3, true)
val page3 = FileHelper.listDirectoryEntries(testDirectory, 6, 3, true)
val page4 = FileHelper.listDirectoryEntries(testDirectory, 9, 3, true)
assertEquals(3, page1.size)
assertEquals(3, page2.size)
assertEquals(3, page3.size)
assertEquals(1, page4.size)
}
@Test
fun testListDirectoryEntriesWhenPaginatingFilesShouldWorkCorrectly() {
for (i in 1..10) File(testDirectory, "file$i.txt").createNewFile()
val page1 = FileHelper.listDirectoryEntries(testDirectory, 0, 4, false)
val page2 = FileHelper.listDirectoryEntries(testDirectory, 4, 4, false)
val page3 = FileHelper.listDirectoryEntries(testDirectory, 8, 4, false)
assertEquals(4, page1.size)
assertEquals(4, page2.size)
assertEquals(2, page3.size)
}
}
@@ -14,13 +14,16 @@ 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.date.DateFormatPattern
import com.owncloud.android.R
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.SimpleDateFormat
import java.util.Date
import java.util.Locale
class UploadDateTests {
@@ -94,12 +97,12 @@ class UploadDateTests {
@Test
fun getRelativeDateTimeStringReturnsFutureAsAbsoluteWhenShowFutureIsFalse() {
val time = System.currentTimeMillis() + ONE_MINUTE
val expected = java.text.DateFormat.getDateTimeInstance().format(Date(time))
val formatter = SimpleDateFormat("MMM d, yyyy h:mm:ss a", Locale.US)
val expected = formatter.format(Date(System.currentTimeMillis() + ONE_MINUTE))
val result = DisplayUtils.getRelativeDateTimeString(
context,
time,
System.currentTimeMillis() + ONE_MINUTE,
DateUtils.SECOND_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
0,
@@ -127,19 +130,8 @@ class UploadDateTests {
@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
}
val formatter = SimpleDateFormat(DateFormatPattern.MonthWithDate.pattern, Locale.US)
val expected = formatter.format(Date(time))
assertRelativeDateTimeString(time, expected)
}
@@ -147,19 +139,8 @@ class UploadDateTests {
@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
}
val formatter = SimpleDateFormat(DateFormatPattern.MonthWithDate.pattern, Locale.US)
val expected = formatter.format(Date(time))
assertRelativeDateTimeString(time, expected, DateUtils.SECOND_IN_MILLIS)
}
@@ -167,19 +148,8 @@ class UploadDateTests {
@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
}
val formatter = SimpleDateFormat("M/d/YYYY", Locale.US)
val expected = formatter.format(Date(time))
assertRelativeDateTimeString(time, expected, DateUtils.SECOND_IN_MILLIS)
}
@@ -224,19 +194,7 @@ class UploadDateTests {
assertEquals(expected, result)
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
}
expected = SimpleDateFormat(DateFormatPattern.MonthWithDate.pattern, Locale.US).format(testTimestamp)
result = DisplayUtils.getRelativeDateTimeString(
context,
testTimestamp,
@@ -6,12 +6,16 @@
*/
package com.nmc.android.ui
import android.view.View
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
import androidx.test.espresso.matcher.ViewMatchers.isCompletelyDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withEffectiveVisibility
import androidx.test.espresso.matcher.ViewMatchers.withId
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
@@ -20,21 +24,29 @@ 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)
launchActivity<LauncherActivity>().use { scenario ->
onView(withId(R.id.ivSplash)).check(matches(isCompletelyDisplayed()))
onView(
withId(R.id.splashScreenBold)
).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.GONE)))
onView(
withId(R.id.splashScreenNormal)
).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.GONE)))
}
}
@Test
fun testSplashScreenWithTitlesShouldShowTitles() {
launchActivity<LauncherActivity>().onActivity { activity ->
activity.setSplashTitles("Example", "Cloud")
launchActivity<LauncherActivity>().use { scenario ->
onView(withId(R.id.ivSplash)).check(matches(isCompletelyDisplayed()))
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)
scenario.onActivity {
it.setSplashTitles("Example", "Cloud")
}
val onePercentArea = ViewMatchers.isDisplayingAtLeast(1)
onView(withId(R.id.splashScreenBold)).check(matches(onePercentArea))
onView(withId(R.id.splashScreenNormal)).check(matches(onePercentArea))
}
}
}
@@ -6,6 +6,7 @@
*/
package com.owncloud.android;
import android.Manifest;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorException;
@@ -29,7 +30,7 @@ import com.nextcloud.client.account.UserAccountManagerImpl;
import com.nextcloud.client.device.BatteryStatus;
import com.nextcloud.client.device.PowerManagementService;
import com.nextcloud.client.jobs.upload.FileUploadWorker;
import com.nextcloud.client.network.ConnectivityManagerFactory;
import com.nextcloud.client.network.Connectivity;
import com.nextcloud.client.network.ConnectivityService;
import com.nextcloud.client.preferences.AppPreferencesImpl;
import com.nextcloud.client.preferences.DarkMode;
@@ -78,6 +79,7 @@ import androidx.fragment.app.DialogFragment;
import androidx.test.espresso.contrib.DrawerActions;
import androidx.test.espresso.intent.rule.IntentsTestRule;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.GrantPermissionRule;
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry;
import androidx.test.runner.lifecycle.Stage;
@@ -95,7 +97,8 @@ public abstract class AbstractIT {
@Rule
public final TestRule storagePermissionRule = GrantStoragePermissionRule.grant();
protected ConnectivityService connectivityServiceMock = ConnectivityManagerFactory.INSTANCE.getMock();
@Rule
public GrantPermissionRule notificationsPermissionRule = GrantPermissionRule.grant(Manifest.permission.POST_NOTIFICATIONS);
protected static OwnCloudClient client;
protected static NextcloudClient nextcloudClient;
@@ -215,7 +218,7 @@ public abstract class AbstractIT {
@Before
public void enableAccessibilityChecks() {
androidx.test.espresso.accessibility.AccessibilityChecks.enable().setRunChecksFromRootView(true);
androidx.test.espresso.accessibility.AccessibilityChecks.enable().setRunChecksFromRootView(false);
}
@After
@@ -367,12 +370,29 @@ public abstract class AbstractIT {
}
public void uploadOCUpload(OCUpload ocUpload) {
PowerManagementService powerManagementServiceMock = new PowerManagementService() {
ConnectivityService connectivityServiceMock = new ConnectivityService() {
@Override
public boolean isIgnoringOptimization() {
return true;
public void isNetworkAndServerAvailable(@NonNull GenericCallback<Boolean> callback) {
}
@Override
public boolean isConnected() {
return false;
}
@Override
public boolean isInternetWalled() {
return false;
}
@Override
public Connectivity getConnectivity() {
return Connectivity.CONNECTED_WIFI;
}
};
PowerManagementService powerManagementServiceMock = new PowerManagementService() {
@NonNull
@Override
public BatteryStatus getBattery() {
@@ -19,6 +19,8 @@ import com.nextcloud.client.account.UserAccountManagerImpl;
import com.nextcloud.client.device.BatteryStatus;
import com.nextcloud.client.device.PowerManagementService;
import com.nextcloud.client.jobs.upload.FileUploadWorker;
import com.nextcloud.client.network.Connectivity;
import com.nextcloud.client.network.ConnectivityService;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.datamodel.UploadsStorageManager;
import com.owncloud.android.db.OCUpload;
@@ -156,11 +158,6 @@ public abstract class AbstractOnServerIT extends AbstractIT {
assertTrue(operationResult);
}
if (remoteFile.getPermissions().contains("M")) {
// skip Teamfolders
continue;
}
boolean removeResult = false;
for (int i = 0; i < 5; i++) {
@@ -175,7 +172,7 @@ public abstract class AbstractOnServerIT extends AbstractIT {
shortSleep();
}
assertTrue("Remove of " + remoteFile.getRemotePath() + " failed", removeResult);
assertTrue(removeResult);
}
}
}
@@ -205,12 +202,29 @@ public abstract class AbstractOnServerIT extends AbstractIT {
}
public void uploadOCUpload(OCUpload ocUpload, int localBehaviour) {
PowerManagementService powerManagementServiceMock = new PowerManagementService() {
ConnectivityService connectivityServiceMock = new ConnectivityService() {
@Override
public boolean isIgnoringOptimization() {
return true;
public void isNetworkAndServerAvailable(@NonNull GenericCallback<Boolean> callback) {
}
@Override
public boolean isConnected() {
return false;
}
@Override
public boolean isInternetWalled() {
return false;
}
@Override
public Connectivity getConnectivity() {
return Connectivity.CONNECTED_WIFI;
}
};
PowerManagementService powerManagementServiceMock = new PowerManagementService() {
@NonNull
@Override
public BatteryStatus getBattery() {
@@ -234,7 +248,7 @@ public abstract class AbstractOnServerIT extends AbstractIT {
user,
null,
ocUpload,
NameCollisionPolicy.OVERWRITE,
NameCollisionPolicy.DEFAULT,
localBehaviour,
targetContext,
false,
@@ -0,0 +1,101 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2020 Tobias Kaminsky <tobias@kaminsky.me>
* SPDX-FileCopyrightText: 2020 Chris Narkiewicz <hello@ezaquarii.com>
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
*/
package com.owncloud.android;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.db.OCUpload;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.operations.DownloadFileOperation;
import com.owncloud.android.operations.RefreshFolderOperation;
import com.owncloud.android.operations.RemoveFileOperation;
import com.owncloud.android.utils.FileStorageUtils;
import org.junit.After;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
/**
* Tests related to file downloads.
*/
public class DownloadIT extends AbstractOnServerIT {
private static final String FOLDER = "/testUpload/";
@After
public void after() {
RemoteOperationResult result = new RefreshFolderOperation(getStorageManager().getFileByPath("/"),
System.currentTimeMillis() / 1000L,
false,
true,
getStorageManager(),
user,
targetContext)
.execute(client);
// cleanup only if folder exists
if (result.isSuccess() && getStorageManager().getFileByDecryptedRemotePath(FOLDER) != null) {
new RemoveFileOperation(getStorageManager().getFileByDecryptedRemotePath(FOLDER),
false,
user,
false,
targetContext,
getStorageManager())
.execute(client);
}
}
@Test
public void verifyDownload() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
FOLDER + "nonEmpty.txt",
account.name);
uploadOCUpload(ocUpload);
OCUpload ocUpload2 = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
FOLDER + "nonEmpty2.txt",
account.name);
uploadOCUpload(ocUpload2);
refreshFolder("/");
refreshFolder(FOLDER);
OCFile file1 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt");
OCFile file2 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty2.txt");
verifyDownload(file1, file2);
assertTrue(new DownloadFileOperation(user, file1, targetContext).execute(client).isSuccess());
assertTrue(new DownloadFileOperation(user, file2, targetContext).execute(client).isSuccess());
refreshFolder(FOLDER);
file1 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt");
file2 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty2.txt");
verifyDownload(file1, file2);
}
private void verifyDownload(OCFile file1, OCFile file2) {
assertNotNull(file1);
assertNotNull(file2);
assertNotSame(file1.getStoragePath(), file2.getStoragePath());
assertTrue(new File(file1.getStoragePath()).exists());
assertTrue(new File(file2.getStoragePath()).exists());
assertEquals(FileStorageUtils.getDefaultSavePathFor(account.name, file1), file1.getStoragePath());
assertEquals(FileStorageUtils.getDefaultSavePathFor(account.name, file2), file2.getStoragePath());
}
}
@@ -1,121 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2020 Tobias Kaminsky <tobias@kaminsky.me>
* SPDX-FileCopyrightText: 2020 Chris Narkiewicz <hello@ezaquarii.com>
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
*/
package com.owncloud.android
import android.net.Uri
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.db.OCUpload
import com.owncloud.android.operations.DownloadFileOperation
import com.owncloud.android.operations.RefreshFolderOperation
import com.owncloud.android.operations.RemoveFileOperation
import com.owncloud.android.utils.FileStorageUtils
import org.junit.After
import org.junit.Assert
import org.junit.Assert.fail
import org.junit.Test
import kotlin.io.path.Path
import kotlin.io.path.exists
class DownloadIT : AbstractOnServerIT() {
@After
override fun after() {
val result = RefreshFolderOperation(
storageManager.getFileByPath("/"),
System.currentTimeMillis() / 1000L,
false,
true,
storageManager,
user,
targetContext
)
.execute(client)
// cleanup only if folder exists
if (result.isSuccess && storageManager.getFileByDecryptedRemotePath(FOLDER) != null) {
RemoveFileOperation(
storageManager.getFileByDecryptedRemotePath(FOLDER)!!,
false,
user,
false,
targetContext,
storageManager
)
.execute(client)
}
}
@Test
fun verifyDownload() {
val ocUpload = OCUpload(
FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
FOLDER + "nonEmpty.txt",
account.name
)
uploadOCUpload(ocUpload)
val ocUpload2 = OCUpload(
FileStorageUtils.getTemporalPath(account.name) + "/nonEmpty.txt",
FOLDER + "nonEmpty2.txt",
account.name
)
uploadOCUpload(ocUpload2)
refreshFolder(FOLDER)
var file1 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt")
var file2 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty2.txt")
if (file1 == null) {
fail("file 1 cannot be null")
}
val operation1 = DownloadFileOperation(user, file1!!, targetContext)
val operation1Result = operation1.execute(client)
Assert.assertTrue(operation1Result.isSuccess)
if (file2 == null) {
fail("file 2 cannot be null")
}
val operation2 = DownloadFileOperation(user, file2!!, targetContext)
val operation2Result = operation2.execute(client)
Assert.assertTrue(operation2Result.isSuccess)
refreshFolder(FOLDER)
file1 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty.txt")
file2 = fileDataStorageManager.getFileByDecryptedRemotePath(FOLDER + "nonEmpty2.txt")
verifyDownload(file1, file2)
}
private fun verifyDownload(file1: OCFile?, file2: OCFile?) {
Assert.assertNotNull(file1)
Assert.assertNotNull(file2)
Assert.assertNotSame(file1!!.storagePath, file2!!.storagePath)
Assert.assertTrue(Path(file1.storagePath).exists())
Assert.assertTrue(Path(file2.storagePath).exists())
// test against hardcoded path to make sure that it is correct
Assert.assertEquals(
"/storage/emulated/0/Android/media/" + targetContext.packageName + "/nextcloud/" +
Uri.encode(account.name, "@") + "/testUpload/nonEmpty.txt",
file1.storagePath
)
Assert.assertEquals(
"/storage/emulated/0/Android/media/" + targetContext.packageName + "/nextcloud/" +
Uri.encode(account.name, "@") + "/testUpload/nonEmpty2.txt",
file2.storagePath
)
}
companion object {
private const val FOLDER = "/testUpload/"
}
}
@@ -107,7 +107,6 @@ public class FileIT extends AbstractOnServerIT {
folderPath,
user,
fileDataStorageManager,
false,
false)
.execute(targetContext)
.isSuccess());
@@ -1,148 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android
import com.nextcloud.client.account.UserAccountManagerImpl
import com.nextcloud.client.device.BatteryStatus
import com.nextcloud.client.device.PowerManagementService
import com.nextcloud.client.jobs.upload.FileUploadWorker
import com.owncloud.android.datamodel.UploadsStorageManager
import com.owncloud.android.db.OCUpload
import com.owncloud.android.files.services.NameCollisionPolicy
import com.owncloud.android.lib.common.operations.RemoteOperationResult
import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation
import com.owncloud.android.lib.resources.files.RemoveFileRemoteOperation
import com.owncloud.android.operations.UploadFileOperation
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import java.io.IOException
class GrantFolderExistenceTests : AbstractOnServerIT() {
private val root = "/autoupload/"
private val yearFolder = root + "2026/"
private val monthFolder = yearFolder + "07/"
private val uploadsStorageManager = UploadsStorageManager(
UserAccountManagerImpl.fromContext(targetContext),
targetContext.contentResolver
)
private val powerManagementServiceMock = object : PowerManagementService {
override val isPowerSavingEnabled = false
override val isIgnoringOptimization = true
override val battery = BatteryStatus(false, 0)
}
@Before
@Throws(IOException::class)
fun before() {
createDummyFiles()
}
@Test
fun testUploadFileThenDeleteYearFolderOnServerOnlyThenUploadAgainShouldRecreateMonthFolderAndReturnOk() {
uploadAndAssertSuccess("first.txt")
assertTrue("month folder should exist on server", existsOnServer(monthFolder))
assertNotNull("month folder should be cached locally", storageManager.getFileByDecryptedRemotePath(monthFolder))
removeYearFolderOnServerOnly()
assertFalse("month folder should be deleted", existsOnServer(monthFolder))
assertNotNull(
"app still has a cached entry for the removed folder",
storageManager.getFileByDecryptedRemotePath(monthFolder)
)
// attempting upload to the same folder
val result = upload("nonEmpty.txt", monthFolder + "nonEmpty.txt")
assertEquals(
"upload must not fail with a conflict, the missing folder has to be recreated",
RemoteOperationResult.ResultCode.OK,
result.code
)
assertTrue("month folder should be recreated on server", existsOnServer(monthFolder))
assertTrue("uploaded file should exist on server", existsOnServer(monthFolder + "nonEmpty.txt"))
}
@Test
fun testUploadFileThenDeleteRootOnServerOnlyThenUploadAgainShouldRecreateAllFolderLevelsAndReturnOk() {
uploadAndAssertSuccess("first.txt")
assertTrue(
"root folder should be removed",
RemoveFileRemoteOperation(root).execute(client).isSuccess
)
assertFalse(existsOnServer(root))
val result = upload("nonEmpty.txt", monthFolder + "nonEmpty.txt")
assertEquals(
"every missing folder level has to be recreated",
RemoteOperationResult.ResultCode.OK,
result.code
)
assertTrue(existsOnServer(yearFolder))
assertTrue(existsOnServer(monthFolder))
assertTrue(existsOnServer(monthFolder + "nonEmpty.txt"))
}
private fun uploadAndAssertSuccess(filename: String) {
val result = upload(filename, monthFolder + filename)
assertTrue(result.logMessage, result.isSuccess)
assertTrue("uploaded file should exist on server", existsOnServer(monthFolder + filename))
}
private fun removeYearFolderOnServerOnly() {
assertTrue(
"year folder should be removed",
RemoveFileRemoteOperation(yearFolder).execute(client).isSuccess
)
}
private fun existsOnServer(remotePath: String): Boolean =
ExistenceCheckRemoteOperation(remotePath, false).execute(client).isSuccess
private fun upload(localFileName: String, remotePath: String): RemoteOperationResult<*> {
val localFile = createFile(localFileName, FILE_LINE_COUNT)
assertTrue("local file must exist before uploading", localFile.exists())
val ocUpload = OCUpload(
localFile.absolutePath,
remotePath,
account.name
).apply {
isCreateRemoteFolder = true
createdBy = UploadFileOperation.CREATED_AS_INSTANT_PICTURE
}
return UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
user,
null,
ocUpload,
NameCollisionPolicy.ASK_USER,
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false,
storageManager
).execute(client)
}
companion object {
private const val FILE_LINE_COUNT = 100
}
}
@@ -37,7 +37,8 @@ class ScreenshotsIT : AbstractIT() {
@get:Rule
val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.POST_NOTIFICATIONS
)
@Test
@@ -12,7 +12,7 @@ import com.nextcloud.client.account.UserAccountManagerImpl;
import com.nextcloud.client.device.BatteryStatus;
import com.nextcloud.client.device.PowerManagementService;
import com.nextcloud.client.jobs.upload.FileUploadWorker;
import com.nextcloud.client.network.ConnectivityManagerFactory;
import com.nextcloud.client.network.Connectivity;
import com.nextcloud.client.network.ConnectivityService;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.datamodel.UploadsStorageManager;
@@ -55,12 +55,29 @@ public class UploadIT extends AbstractOnServerIT {
new UploadsStorageManager(UserAccountManagerImpl.fromContext(targetContext),
targetContext.getContentResolver());
private PowerManagementService powerManagementServiceMock = new PowerManagementService() {
private ConnectivityService connectivityServiceMock = new ConnectivityService() {
@Override
public boolean isIgnoringOptimization() {
return true;
public void isNetworkAndServerAvailable(@NonNull GenericCallback<Boolean> callback) {
}
@Override
public boolean isConnected() {
return false;
}
@Override
public boolean isInternetWalled() {
return false;
}
@Override
public Connectivity getConnectivity() {
return Connectivity.CONNECTED_WIFI;
}
};
private PowerManagementService powerManagementServiceMock = new PowerManagementService() {
@Override
public boolean isPowerSavingEnabled() {
return false;
@@ -209,11 +226,6 @@ public class UploadIT extends AbstractOnServerIT {
@Test
public void testUploadOnChargingOnlyAndCharging() {
PowerManagementService powerManagementServiceMock = new PowerManagementService() {
@Override
public boolean isIgnoringOptimization() {
return true;
}
@Override
public boolean isPowerSavingEnabled() {
return false;
@@ -255,7 +267,27 @@ public class UploadIT extends AbstractOnServerIT {
@Test
public void testUploadOnWifiOnlyButNoWifi() {
ConnectivityService connectivityServiceMock = ConnectivityManagerFactory.INSTANCE.getWifi();
ConnectivityService connectivityServiceMock = new ConnectivityService() {
@Override
public void isNetworkAndServerAvailable(@NonNull GenericCallback<Boolean> callback) {
}
@Override
public boolean isConnected() {
return false;
}
@Override
public boolean isInternetWalled() {
return false;
}
@Override
public Connectivity getConnectivity() {
return new Connectivity(true, false, false, true);
}
};
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
FOLDER + "noWifi.txt", account.name);
ocUpload.setUseWifiOnly(true);
@@ -324,7 +356,27 @@ public class UploadIT extends AbstractOnServerIT {
@Test
public void testUploadOnWifiOnlyButMeteredWifi() {
ConnectivityService connectivityServiceMock = ConnectivityManagerFactory.INSTANCE.getMetered();
ConnectivityService connectivityServiceMock = new ConnectivityService() {
@Override
public void isNetworkAndServerAvailable(@NonNull GenericCallback<Boolean> callback) {
}
@Override
public boolean isConnected() {
return false;
}
@Override
public boolean isInternetWalled() {
return false;
}
@Override
public Connectivity getConnectivity() {
return new Connectivity(true, true, true, true);
}
};
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
FOLDER + "noWifi.txt",
account.name);
@@ -12,6 +12,11 @@ package com.owncloud.android.datamodel
import android.accounts.Account
import android.accounts.AccountManager
import android.content.ActivityNotFoundException
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.nextcloud.client.account.CurrentAccountProvider
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.account.UserAccountManagerImpl
@@ -27,22 +32,42 @@ import com.owncloud.android.operations.UploadFileOperation
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.MockitoAnnotations
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.io.File
import java.util.Random
import java.util.UUID
import java.util.function.Supplier
/**
* Created by JARP on 6/7/17.
*/
@RunWith(AndroidJUnit4::class)
@SmallTest
class UploadStorageManagerTest : AbstractIT() {
@get:Rule
val mockitoRule: MockitoRule = MockitoJUnit.rule()
private lateinit var uploadsStorageManager: UploadsStorageManager
@Mock
private lateinit var currentAccountProvider: CurrentAccountProvider
private lateinit var userAccountManager: UserAccountManager
private lateinit var user2: User
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
val instrumentationCtx = ApplicationProvider.getApplicationContext<Context>()
val contentResolver = instrumentationCtx.contentResolver
uploadsStorageManager = UploadsStorageManager(currentAccountProvider, contentResolver)
userAccountManager = UserAccountManagerImpl.fromContext(targetContext)
val temp = Account("[email protected]", MainApp.getAccountType(targetContext))
if (!userAccountManager.exists(temp)) {
val platformAccountManager = AccountManager.get(targetContext)
@@ -56,13 +81,10 @@ class UploadStorageManagerTest : AbstractIT() {
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_BASE_URL, "test.com")
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_USER_ID, "test") // same as userId
}
val userAccountManager: UserAccountManager = UserAccountManagerImpl.fromContext(targetContext)
user2 = userAccountManager.getUser("[email protected]")
.orElseThrow(Supplier { ActivityNotFoundException() })
uploadsStorageManager =
UploadsStorageManager(
UserAccountManagerImpl.fromContext(targetContext),
targetContext.contentResolver
)
}
@Test
@@ -208,13 +230,16 @@ class UploadStorageManagerTest : AbstractIT() {
private fun deleteAllUploads() {
uploadsStorageManager.removeAllUploads()
Assert.assertEquals(0, uploadsStorageManager.getAllStoredUploads().size.toLong())
}
@After
fun tearDown() {
if (::user2.isInitialized) {
if (::uploadsStorageManager.isInitialized) {
deleteAllUploads()
}
if (::userAccountManager.isInitialized && ::user2.isInitialized) {
userAccountManager.removeUser(user2)
}
}
@@ -64,6 +64,7 @@ class FileMenuFilterIT : AbstractIT() {
MockKAnnotations.init(this)
every { mockFileUploaderBinder.isUploading(any(), any()) } returns false
every { mockComponentsGetter.fileUploaderHelper } returns mockFileUploaderBinder
every { mockFileDownloadProgressListener.isDownloading(any(), any()) } returns false
every { mockComponentsGetter.fileDownloadProgressListener } returns mockFileDownloadProgressListener
every { mockOperationsServiceBinder.isSynchronizing(any(), any()) } returns false
every { mockComponentsGetter.operationsServiceBinder } returns mockOperationsServiceBinder
@@ -330,39 +331,6 @@ class FileMenuFilterIT : AbstractIT() {
}
}
@Test
fun filter_openWithOnlyOffice_onlyForDownloadedFiles() {
every {
mockArbitraryDataProvider.getValue(any<User>(), ArbitraryDataProvider.DIRECT_EDITING)
} returns ONLYOFFICE_DIRECT_EDITING_JSON
configureCapability(OCCapability())
val downloadedFile = OCFile("/downloaded.docx").apply {
mimeType = OFFICE_MIMETYPE
storagePath = getDummyFile("downloaded.docx").absolutePath
}
val onlineOnlyFile = OCFile("/online.docx").apply {
mimeType = OFFICE_MIMETYPE
}
launchActivity<TestActivity>().use {
it.onActivity { activity ->
val filterFactory = FileMenuFilter.Factory(mockStorageManager, activity, editorUtils)
val downloadedToHide = filterFactory
.newInstance(downloadedFile, mockComponentsGetter, true, user)
.getToHide(false)
assertFalse(downloadedToHide.contains(R.id.action_open_in_web_editor))
val onlineToHide = filterFactory
.newInstance(onlineOnlyFile, mockComponentsGetter, true, user)
.getToHide(false)
assertTrue(onlineToHide.contains(R.id.action_open_in_web_editor))
}
}
}
private data class ExpectedLockVisibilities(val lockFile: Boolean, val unlockFile: Boolean)
private fun configureCapability(capability: OCCapability) {
@@ -396,25 +364,4 @@ class FileMenuFilterIT : AbstractIT() {
}
}
}
companion object {
private const val OFFICE_MIMETYPE =
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
private val ONLYOFFICE_DIRECT_EDITING_JSON =
"""
{
"editors": {
"onlyoffice": {
"id": "onlyoffice",
"name": "OnlyOffice",
"mimetypes": [],
"optionalMimetypes": ["$OFFICE_MIMETYPE"],
"secure": false
}
},
"creators": {}
}
""".trimIndent()
}
}
@@ -1,7 +1,6 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-FileCopyrightText: 2020 Tobias Kaminsky <tobias@kaminsky.me>
* SPDX-FileCopyrightText: 2020 Chris Narkiewicz <hello@ezaquarii.com>
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH
@@ -9,141 +8,483 @@
*/
package com.owncloud.android.files.services
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.account.UserAccountManagerImpl
import com.nextcloud.client.device.BatteryStatus
import com.nextcloud.client.device.PowerManagementService
import com.nextcloud.client.jobs.upload.FileUploadHelper
import com.nextcloud.client.jobs.upload.FileUploadWorker
import com.nextcloud.client.network.Connectivity
import com.nextcloud.client.network.ConnectivityService
import com.owncloud.android.AbstractOnServerIT
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.UploadsStorageManager
import com.owncloud.android.db.OCUpload
import com.owncloud.android.lib.common.operations.OperationCancelledException
import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation
import com.owncloud.android.lib.resources.files.model.RemoteFile
import com.owncloud.android.operations.UploadFileOperation
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import junit.framework.Assert.assertEquals
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import java.io.File
class FileUploaderIT : AbstractOnServerIT() {
abstract class FileUploaderIT : AbstractOnServerIT() {
private var uploadsStorageManager: UploadsStorageManager? = null
private lateinit var uploadsStorageManager: UploadsStorageManager
private val connectivityServiceMock: ConnectivityService = object : ConnectivityService {
override fun isNetworkAndServerAvailable(callback: ConnectivityService.GenericCallback<Boolean>) = Unit
private val powerManagementServiceMock = object : PowerManagementService {
override val isIgnoringOptimization = true
override val isPowerSavingEnabled = false
override val battery = BatteryStatus()
override fun isConnected(): Boolean = false
override fun isInternetWalled(): Boolean = false
override fun getConnectivity(): Connectivity = Connectivity.CONNECTED_WIFI
}
private val powerManagementServiceMock: PowerManagementService = object : PowerManagementService {
override val isPowerSavingEnabled: Boolean
get() = false
override val battery: BatteryStatus
get() = BatteryStatus()
}
@Before
fun setUp() {
val accountManager = UserAccountManagerImpl.fromContext(targetContext)
uploadsStorageManager = UploadsStorageManager(accountManager, targetContext.contentResolver)
val contentResolver = targetContext.contentResolver
val accountManager: UserAccountManager = UserAccountManagerImpl.fromContext(targetContext)
uploadsStorageManager = UploadsStorageManager(accountManager, contentResolver)
}
// /**
// * uploads a file, overwrites it with an empty one, check if overwritten
// */
// disabled, flaky test
// @Test
// fun testKeepLocalAndOverwriteRemote() {
// val file = getDummyFile("chunkedFile.txt")
// val ocUpload = OCUpload(file.absolutePath, "/testFile.txt", account.name)
//
// assertTrue(
// UploadFileOperation(
// uploadsStorageManager,
// connectivityServiceMock,
// powerManagementServiceMock,
// user,
// null,
// ocUpload,
// FileUploader.NameCollisionPolicy.DEFAULT,
// FileUploader.LOCAL_BEHAVIOUR_COPY,
// targetContext,
// false,
// false
// )
// .setRemoteFolderToBeCreated()
// .execute(client, storageManager)
// .isSuccess
// )
//
// val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
// assertTrue(result.isSuccess)
//
// assertEquals(file.length(), (result.data[0] as RemoteFile).length)
//
// val ocUpload2 = OCUpload(getDummyFile("empty.txt").absolutePath, "/testFile.txt", account.name)
//
// assertTrue(
// UploadFileOperation(
// uploadsStorageManager,
// connectivityServiceMock,
// powerManagementServiceMock,
// user,
// null,
// ocUpload2,
// FileUploader.NameCollisionPolicy.OVERWRITE,
// FileUploader.LOCAL_BEHAVIOUR_COPY,
// targetContext,
// false,
// false
// )
// .execute(client, storageManager)
// .isSuccess
// )
//
// val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
// assertTrue(result2.isSuccess)
//
// assertEquals(0, (result2.data[0] as RemoteFile).length)
// }
/**
* uploads a file, overwrites it with an empty one, check if overwritten
*/
@Test
fun uploadWithOverwritePolicyReplacesRemoteFile() {
val originalFile = getDummyFile(CHUNKED_FILE)
uploadOriginalFile(originalFile)
fun testKeepLocalAndOverwriteRemoteStatic() {
val file = getDummyFile("chunkedFile.txt")
val replacement = getDummyFile(EMPTY_FILE)
assertTrue(uploadOperation(replacement, NameCollisionPolicy.OVERWRITE).execute(client).isSuccess)
FileUploadHelper().uploadNewFiles(
user,
arrayOf(file.absolutePath),
arrayOf("/testFile.txt"),
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
true,
UploadFileOperation.CREATED_BY_USER,
false,
false,
NameCollisionPolicy.DEFAULT
)
assertRemoteFileLength(REMOTE_PATH, EMPTY_LENGTH)
}
longSleep()
@Test
fun uploadWithRenamePolicyKeepsBothFiles() {
val originalFile = getDummyFile(CHUNKED_FILE)
uploadOriginalFile(originalFile)
val renamedFile = getDummyFile(EMPTY_FILE)
var renameListenerTriggered = false
val operation = uploadOperation(renamedFile, NameCollisionPolicy.RENAME)
.addRenameUploadListener { renameListenerTriggered = true }
assertTrue(operation.execute(client).isSuccess)
assertRemoteFileLength(REMOTE_PATH, originalFile.length())
assertRemoteFileLength(REMOTE_PATH_RENAMED, renamedFile.length())
assertTrue(renameListenerTriggered)
}
@Test
fun uploadWithRenamePolicyKeepsBothFilesForNonEmptyOriginal() {
val originalFile = getDummyFile(NON_EMPTY_FILE)
uploadOriginalFile(originalFile)
val renamedFile = getDummyFile(EMPTY_FILE)
assertTrue(uploadOperation(renamedFile, NameCollisionPolicy.RENAME).execute(client).isSuccess)
assertRemoteFileLength(REMOTE_PATH, originalFile.length())
assertRemoteFileLength(REMOTE_PATH_RENAMED, renamedFile.length())
}
@Test
fun uploadWithSkipPolicyKeepsRemoteFileUnchanged() {
val originalFile = getDummyFile(CHUNKED_FILE)
uploadOriginalFile(originalFile)
val skippedFile = getDummyFile(EMPTY_FILE)
val operation = uploadOperation(skippedFile, NameCollisionPolicy.SKIP)
assertTrue(operation.execute(client).isSuccess)
assertTrue(operation.wasSkipped())
assertRemoteFileLength(REMOTE_PATH, originalFile.length())
}
@Test
fun uploadWithSkipPolicyUploadsWhenNoRemoteFileExists() {
val originalFile = getDummyFile(CHUNKED_FILE)
val operation = uploadOperation(originalFile, NameCollisionPolicy.SKIP).setRemoteFolderToBeCreated()
assertTrue(operation.execute(client).isSuccess)
assertFalse(operation.wasSkipped())
assertRemoteFileLength(REMOTE_PATH, originalFile.length())
val skippedFile = getDummyFile(EMPTY_FILE)
val skippedOperation = uploadOperation(skippedFile, NameCollisionPolicy.SKIP)
assertTrue(skippedOperation.execute(client).isSuccess)
assertTrue(skippedOperation.wasSkipped())
assertRemoteFileLength(REMOTE_PATH, originalFile.length())
}
private fun uploadOriginalFile(originalFile: File) {
val operation = uploadOperation(originalFile, NameCollisionPolicy.DEFAULT).setRemoteFolderToBeCreated()
assertTrue(operation.execute(client).isSuccess)
assertRemoteFileLength(REMOTE_PATH, originalFile.length())
}
private fun uploadOperation(localFile: File, nameCollisionPolicy: NameCollisionPolicy) = UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
user,
null,
OCUpload(localFile.absolutePath, REMOTE_PATH, account.name),
nameCollisionPolicy,
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false,
storageManager
)
private fun assertRemoteFileLength(remotePath: String, expectedLength: Long) {
val result = ReadFileRemoteOperation(remotePath).execute(client)
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result.isSuccess)
assertEquals(expectedLength, (result.data[0] as RemoteFile).length)
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocFile2 = OCFile("/testFile.txt")
ocFile2.storagePath = getDummyFile("empty.txt").absolutePath
FileUploadHelper().uploadUpdatedFile(
user,
arrayOf(ocFile2),
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
NameCollisionPolicy.OVERWRITE
)
shortSleep()
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result2.isSuccess)
assertEquals(0, (result2.data[0] as RemoteFile).length)
}
companion object {
private const val REMOTE_PATH = "/testFile.txt"
private const val REMOTE_PATH_RENAMED = "/testFile (2).txt"
private const val CHUNKED_FILE = "chunkedFile.txt"
private const val NON_EMPTY_FILE = "nonEmpty.txt"
private const val EMPTY_FILE = "empty.txt"
private const val EMPTY_LENGTH = 0L
/**
* uploads a file, uploads another one with automatically (2) added, check
*/
@Test
fun testKeepBoth() {
var renameListenerWasTriggered = false
val file = getDummyFile("chunkedFile.txt")
val ocUpload = OCUpload(file.absolutePath, "/testFile.txt", account.name)
assertTrue(
UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
user,
null,
ocUpload,
NameCollisionPolicy.DEFAULT,
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false,
storageManager
)
.setRemoteFolderToBeCreated()
.execute(client)
.isSuccess
)
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result.isSuccess)
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val file2 = getDummyFile("empty.txt")
val ocUpload2 = OCUpload(file2.absolutePath, "/testFile.txt", account.name)
assertTrue(
UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
user,
null,
ocUpload2,
NameCollisionPolicy.RENAME,
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false,
storageManager
)
.addRenameUploadListener {
renameListenerWasTriggered = true
}
.execute(client)
.isSuccess
)
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result2.isSuccess)
assertEquals(file.length(), (result2.data[0] as RemoteFile).length)
val result3 = ReadFileRemoteOperation("/testFile (2).txt").execute(client)
assertTrue(result3.isSuccess)
assertEquals(file2.length(), (result3.data[0] as RemoteFile).length)
assertTrue(renameListenerWasTriggered)
}
/**
* uploads a file, uploads another one with automatically (2) added, check
*/
@Test
fun testKeepBothStatic() {
val file = getDummyFile("nonEmpty.txt")
FileUploadHelper().uploadNewFiles(
user,
arrayOf(file.absolutePath),
arrayOf("/testFile.txt"),
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
true,
UploadFileOperation.CREATED_BY_USER,
false,
false,
NameCollisionPolicy.DEFAULT
)
longSleep()
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result.isSuccess)
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocFile2 = OCFile("/testFile.txt")
ocFile2.storagePath = getDummyFile("empty.txt").absolutePath
FileUploadHelper().uploadUpdatedFile(
user,
arrayOf(ocFile2),
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
NameCollisionPolicy.RENAME
)
shortSleep()
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result2.isSuccess)
assertEquals(file.length(), (result2.data[0] as RemoteFile).length)
val result3 = ReadFileRemoteOperation("/testFile (2).txt").execute(client)
assertTrue(result3.isSuccess)
assertEquals(ocFile2.fileLength, (result3.data[0] as RemoteFile).length)
}
/**
* uploads a file with "keep server" option set, so do nothing
*/
@Test
fun testKeepServer() {
val file = getDummyFile("chunkedFile.txt")
val ocUpload = OCUpload(file.absolutePath, "/testFile.txt", account.name)
assertTrue(
UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
user,
null,
ocUpload,
NameCollisionPolicy.DEFAULT,
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false,
storageManager
)
.setRemoteFolderToBeCreated()
.execute(client)
.isSuccess
)
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result.isSuccess)
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocUpload2 = OCUpload(getDummyFile("empty.txt").absolutePath, "/testFile.txt", account.name)
assertFalse(
UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
user,
null,
ocUpload2,
NameCollisionPolicy.SKIP,
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false,
storageManager
)
.execute(client).isSuccess
)
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result2.isSuccess)
assertEquals(file.length(), (result2.data[0] as RemoteFile).length)
}
/**
* uploads a file with "keep server" option set, so do nothing
*/
@Test
fun testKeepServerStatic() {
val file = getDummyFile("chunkedFile.txt")
FileUploadHelper().uploadNewFiles(
user,
arrayOf(file.absolutePath),
arrayOf("/testFile.txt"),
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
true,
UploadFileOperation.CREATED_BY_USER,
false,
false,
NameCollisionPolicy.DEFAULT
)
longSleep()
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result.isSuccess)
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocFile2 = OCFile("/testFile.txt")
ocFile2.storagePath = getDummyFile("empty.txt").absolutePath
FileUploadHelper().uploadUpdatedFile(
user,
arrayOf(ocFile2),
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
NameCollisionPolicy.SKIP
)
shortSleep()
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result2.isSuccess)
assertEquals(file.length(), (result2.data[0] as RemoteFile).length)
}
/**
* uploads a file with "skip if exists" option set, so do nothing if file exists
*/
@Test
fun testCancelServer() {
val file = getDummyFile("chunkedFile.txt")
val ocUpload = OCUpload(file.absolutePath, "/testFile.txt", account.name)
assertTrue(
UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
user,
null,
ocUpload,
NameCollisionPolicy.SKIP,
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false,
storageManager
)
.setRemoteFolderToBeCreated()
.execute(client)
.isSuccess
)
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result.isSuccess)
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocUpload2 = OCUpload(getDummyFile("empty.txt").absolutePath, "/testFile.txt", account.name)
val uploadResult = UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
user,
null,
ocUpload2,
NameCollisionPolicy.SKIP,
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false,
storageManager
)
.execute(client)
assertFalse(uploadResult.isSuccess)
assertTrue(uploadResult.exception is OperationCancelledException)
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result2.isSuccess)
assertEquals(file.length(), (result2.data[0] as RemoteFile).length)
}
/**
* uploads a file with "skip if exists" option set, so do nothing if file exists
*/
@Test
fun testKeepCancelStatic() {
val file = getDummyFile("chunkedFile.txt")
FileUploadHelper().uploadNewFiles(
user,
arrayOf(file.absolutePath),
arrayOf("/testFile.txt"),
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
true,
UploadFileOperation.CREATED_BY_USER,
false,
false,
NameCollisionPolicy.DEFAULT
)
longSleep()
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result.isSuccess)
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocFile2 = OCFile("/testFile.txt")
ocFile2.storagePath = getDummyFile("empty.txt").absolutePath
FileUploadHelper().uploadUpdatedFile(
user,
arrayOf(ocFile2),
FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
NameCollisionPolicy.SKIP
)
shortSleep()
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result2.isSuccess)
assertEquals(file.length(), (result2.data[0] as RemoteFile).length)
}
}
@@ -1,63 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.operations
import com.owncloud.android.AbstractOnServerIT
import com.owncloud.android.lib.resources.e2ee.DeleteEncryptedFilesRemoteOperation
import com.owncloud.android.lib.resources.users.DeletePrivateKeyRemoteOperation
import com.owncloud.android.lib.resources.users.DeletePublicKeyRemoteOperation
import com.owncloud.android.lib.resources.users.GetPrivateKeyRemoteOperation
import com.owncloud.android.lib.resources.users.GetPublicKeyRemoteOperation
import com.owncloud.android.lib.resources.users.StorePrivateKeyRemoteOperation
import com.owncloud.android.utils.EncryptionUtils
import com.owncloud.android.utils.crypto.CryptoHelper
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class DeleteE2ERemoteOperationIT : AbstractOnServerIT() {
@Test
fun testDeleteEncryptedFiles() {
val sut = DeleteEncryptedFilesRemoteOperation()
val result = sut.execute(nextcloudClient)
assertTrue(result.isSuccess)
}
@Test
fun testDeletePrivateKey() {
val keyPair = EncryptionUtils.generateKeyPair()
val privateKey = keyPair.private
val keyPhrase = "moreovertelevisionfactorytendencyindependenceinternationalintellectualimpress" +
"interestvolunteer"
val privatePemKeyString = EncryptionUtils.privateKeyToPEM(privateKey)
val encryptedPrivateKey = CryptoHelper.encryptPrivateKey(
privatePemKeyString,
keyPhrase
)
StorePrivateKeyRemoteOperation(encryptedPrivateKey).execute(nextcloudClient)
val sut = DeletePrivateKeyRemoteOperation()
val result = sut.execute(nextcloudClient)
assertTrue(result.isSuccess)
val getResult = GetPrivateKeyRemoteOperation().execute(nextcloudClient)
assertFalse(getResult.isSuccess)
}
@Test
fun testDeletePublicKey() {
val sut = DeletePublicKeyRemoteOperation()
val result = sut.execute(nextcloudClient)
assertTrue(result.isSuccess)
val getResult = GetPublicKeyRemoteOperation().execute(nextcloudClient)
assertFalse(getResult.isSuccess)
}
}
@@ -28,7 +28,6 @@ import com.owncloud.android.authentication.AuthenticatorActivity
import org.junit.AfterClass
import org.junit.Assert
import org.junit.Before
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
@@ -54,7 +53,6 @@ class LoginIT : AbstractIT() {
@Throws(InterruptedException::class)
@Suppress("MagicNumber", "SwallowedException")
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.Q)
@Ignore("Login no longer uses an in-app WebView, so espresso-web (Espresso.onWebView) cannot drive it. ")
fun login() {
val arguments = InstrumentationRegistry.getArguments()
val baseUrl = arguments.getString("TEST_SERVER_URL")!!
@@ -8,6 +8,7 @@
*/
package com.owncloud.android.ui.activity
import android.Manifest
import android.accounts.Account
import android.accounts.AccountManager
import android.net.Uri
@@ -20,8 +21,6 @@ import androidx.test.rule.GrantPermissionRule
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.account.UserAccountManagerImpl
import com.nextcloud.test.Flaky
import com.nextcloud.test.GrantTestPermissionRule
import com.nextcloud.test.RetryTestRule
import com.owncloud.android.AbstractIT
import com.owncloud.android.MainApp
@@ -40,37 +39,36 @@ class DrawerActivityIT : AbstractIT() {
val retryTestRule = RetryTestRule()
@get:Rule
val permissionRule: GrantPermissionRule = GrantTestPermissionRule.grantStorageAndNotification()
val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.POST_NOTIFICATIONS
)
@Test
@Flaky(reason = "Account switch relaunches FileDisplayActivity, which races with the drawer assertions")
fun switchAccountViaAccountList() {
// Switching accounts finishes and relaunches FileDisplayActivity (see
// FileDisplayActivity.handleRestartIntent). That self-relaunch is incompatible with
// ActivityScenario#close(), which cannot drive its tracked instance to DESTROYED, so the
// scenario is launched without auto-closing.
val scenario = launchActivity<FileDisplayActivity>()
lateinit var sut: FileDisplayActivity
scenario.onActivity { activity ->
sut = activity
}
launchActivity<FileDisplayActivity>().use { scenario ->
var sut: FileDisplayActivity? = null
scenario.onActivity { activity ->
sut = activity
}
Assert.assertEquals(account1, sut.user.get().toPlatformAccount())
Assert.assertEquals(account1, sut!!.user.get().toPlatformAccount())
onView(ViewMatchers.withId(R.id.switch_account_button)).perform(ViewActions.click())
onView(
Matchers.anyOf(
ViewMatchers.withText(account2Name),
ViewMatchers.withText(
account2DisplayName
onView(ViewMatchers.withId(R.id.switch_account_button)).perform(ViewActions.click())
onView(
Matchers.anyOf(
ViewMatchers.withText(account2Name),
ViewMatchers.withText(
account2DisplayName
)
)
)
).perform(ViewActions.click())
).perform(ViewActions.click())
Assert.assertEquals(account2, sut.user.get().toPlatformAccount())
Assert.assertEquals(account2, sut.user.get().toPlatformAccount())
onView(ViewMatchers.withId(R.id.switch_account_button)).perform(ViewActions.click())
onView(ViewMatchers.withText(account1?.name)).perform(ViewActions.click())
onView(ViewMatchers.withId(R.id.switch_account_button)).perform(ViewActions.click())
onView(ViewMatchers.withText(account1?.name)).perform(ViewActions.click())
}
}
companion object {
@@ -12,7 +12,6 @@ package com.owncloud.android.ui.activity
import android.content.Intent
import android.net.Uri
import android.view.KeyEvent
import android.view.View
import androidx.test.core.app.launchActivity
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
@@ -25,7 +24,6 @@ import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import com.facebook.testing.screenshot.internal.TestNameDetector
import com.nextcloud.client.preferences.AppPreferencesImpl
import com.nextcloud.test.Flaky
import com.nextcloud.test.GrantStoragePermissionRule
import com.nextcloud.test.withSelectedText
import com.nextcloud.utils.extensions.removeFileExtension
@@ -34,8 +32,6 @@ import com.owncloud.android.R
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.utils.ScreenshotTest
import org.hamcrest.Matchers.not
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@@ -105,7 +101,6 @@ class ReceiveExternalFilesActivityIT : AbstractIT() {
}
@Test
@Flaky(reason = "Rename dialog text selection is not settled when the assertions run")
fun renameSingleFileUpload() {
val imageFile = getDummyFile("image.jpg")
val intent = createSendIntent(imageFile)
@@ -234,22 +229,18 @@ class ReceiveExternalFilesActivityIT : AbstractIT() {
val preferences = AppPreferencesImpl.fromContext(targetContext)
preferences.setLastUploadPath(mainFolder.remotePath)
// In the multi-upload case the rename field is hidden and no view requests focus, so the
// activity window never gains focus on the CI emulator and Espresso's onView(...) fails with
// RootViewWithoutFocusException. The view state is therefore asserted directly via
// onActivity, which does not depend on window focus.
launchActivity<ReceiveExternalFilesActivity>(intent).use { scenario ->
scenario.onActivity { sut ->
// Verify that the test starts in the expected folder. If this fails, change the setup calls above
val expectedMainFolderTitle = sut.getActionBarTitle(mainFolder, false)
assertEquals(expectedMainFolderTitle, sut.supportActionBar?.title?.toString())
launchActivity<ReceiveExternalFilesActivity>(intent).use {
val expectedMainFolderTitle = (getCurrentActivity() as ToolbarActivity).getActionBarTitle(mainFolder, false)
// Verify that the test starts in the expected folder. If this fails, change the setup calls above
onView(withId(R.id.toolbar))
.check(matches(hasDescendant(withText(expectedMainFolderTitle))))
val uploadButton = sut.findViewById<View>(R.id.uploader_choose_folder)
assertEquals(View.VISIBLE, uploadButton.visibility)
assertTrue(uploadButton.isEnabled)
onView(withText(R.string.uploader_btn_upload_text))
.check(matches(isDisplayed()))
.check(matches(isEnabled()))
assertEquals(View.GONE, sut.findViewById<View>(R.id.user_input).visibility)
}
onView(withId(R.id.user_input))
.check(matches(not(isDisplayed())))
}
}
}
@@ -15,19 +15,16 @@ import com.nextcloud.client.preferences.AppPreferences
import com.nextcloud.client.preferences.AppPreferencesImpl
import com.owncloud.android.AbstractIT
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.SyncedFolderProvider
import com.owncloud.android.lib.common.SearchResultEntry
import com.owncloud.android.ui.activity.FileDisplayActivity
import com.owncloud.android.ui.interfaces.UnifiedSearchCurrentDirItemAction
import com.owncloud.android.ui.interfaces.UnifiedSearchListInterface
import com.owncloud.android.ui.unifiedsearch.ProviderID
import com.owncloud.android.ui.unifiedsearch.UnifiedSearchSection
import com.owncloud.android.ui.unifiedsearch.toUnifiedSearchEntry
import com.owncloud.android.utils.MimeType
import com.owncloud.android.utils.ScreenshotTest
import com.nextcloud.utils.thumbnail.FileThumbnailGenerator
import com.nextcloud.utils.thumbnail.FolderThumbnailGenerator
import com.nextcloud.utils.thumbnail.ThumbnailGenerator
import javax.inject.Provider
import com.owncloud.android.utils.overlay.OverlayManager
import org.junit.Before
import org.junit.Test
@@ -36,7 +33,7 @@ class UnifiedSearchListAdapterIT : AbstractIT() {
private val testClassName = "com.owncloud.android.ui.adapter.UnifiedSearchListAdapterIT"
private lateinit var thumbnailGenerator: ThumbnailGenerator
private lateinit var overlayManager: OverlayManager
private lateinit var preferences: AppPreferences
@Suppress("DEPRECATION")
@@ -102,7 +99,7 @@ class UnifiedSearchListAdapterIT : AbstractIT() {
UnifiedSearchSection(
providerID = name.lowercase().replace(" ", "_"),
name = name,
entries = entries.map { it.toUnifiedSearchEntry(storageManager) },
entries = entries,
hasMoreResults = false
)
}
@@ -112,7 +109,7 @@ class UnifiedSearchListAdapterIT : AbstractIT() {
UnifiedSearchSection(
providerID = name.lowercase().replace(" ", "_"),
name = name,
entries = entries.map { it.toUnifiedSearchEntry(storageManager) },
entries = entries,
hasMoreResults = true
)
}
@@ -136,22 +133,20 @@ class UnifiedSearchListAdapterIT : AbstractIT() {
currentDirItems: List<OCFile> = emptyList(),
supportsCalendarContacts: Boolean = false
): UnifiedSearchListAdapter {
val syncedFolderProvider = SyncedFolderProvider(
targetContext.contentResolver,
preferences,
sut.clock
)
val accountManager = UserAccountManagerImpl.fromContext(targetContext)
thumbnailGenerator = ThumbnailGenerator(
fileThumbnailGenerator = FileThumbnailGenerator(
storageManager = Provider { sut.storageManager },
preferences = preferences,
viewThemeUtils = sut.viewThemeUtils,
context = targetContext,
accountManager = accountManager
),
folderThumbnailGenerator = FolderThumbnailGenerator(
preferences = preferences,
viewThemeUtils = sut.viewThemeUtils,
context = targetContext,
accountManager = accountManager
)
overlayManager = OverlayManager(
syncedFolderProvider = syncedFolderProvider,
preferences = preferences,
viewThemeUtils = sut.viewThemeUtils,
context = targetContext,
accountManager = accountManager
)
val adapter = UnifiedSearchListAdapter(
@@ -165,11 +160,12 @@ class UnifiedSearchListAdapterIT : AbstractIT() {
onClientReady: (com.nextcloud.common.NextcloudClient) -> Unit
) = Unit
},
user = sut.user.get(),
context = sut,
viewThemeUtils = sut.viewThemeUtils,
appPreferences = preferences,
currentDirItemAction = noopCurrentDirAction,
thumbnailGenerator = thumbnailGenerator,
user = sut.user.get()
overlayManager = overlayManager
)
adapter.shouldShowFooters(true)
@@ -85,7 +85,8 @@ class DialogFragmentIT : AbstractIT() {
@get:Rule
val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.POST_NOTIFICATIONS
)
@After
@@ -6,13 +6,13 @@
*/
package com.owncloud.android.ui.dialog
import android.Manifest
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 androidx.test.rule.GrantPermissionRule
import com.nextcloud.test.GrantTestPermissionRule
import com.owncloud.android.AbstractIT
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.ui.activity.FileDisplayActivity
@@ -25,7 +25,10 @@ class SyncFileNotEnoughSpaceDialogFragmentTest : AbstractIT() {
private val testClassName = "com.owncloud.android.ui.dialog.SyncFileNotEnoughSpaceDialogFragmentTest"
@get:Rule
val permissionRule: GrantPermissionRule = GrantTestPermissionRule.grantStorageAndNotification()
val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.POST_NOTIFICATIONS
)
@Test
@ScreenshotTest
@@ -1,34 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.ui.fragment
import com.nextcloud.client.account.User
import com.nextcloud.utils.extensions.getParcelableArgument
import com.owncloud.android.AbstractIT
import com.owncloud.android.datamodel.OCFile
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Test
class FileDetailActivitiesFragmentIT : AbstractIT() {
@Test
fun newInstanceStoresFileAndUserInArguments() {
val file = OCFile("/test.txt").apply { fileId = 12 }
val fragment = FileDetailActivitiesFragment.newInstance(file, user)
val arguments = fragment.arguments
assertNotNull(arguments)
val storedFile = arguments.getParcelableArgument("FILE", OCFile::class.java)
val storedUser = arguments.getParcelableArgument("USER", User::class.java)
assertEquals(file.fileId, storedFile?.fileId)
assertEquals(user.accountName, storedUser?.accountName)
}
}
@@ -15,7 +15,7 @@ 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.TestActivity
import com.nextcloud.ui.fileInfo.FileInfoFragment
import com.nextcloud.ui.ImageDetailFragment
import com.owncloud.android.AbstractIT
import com.owncloud.android.R
import com.owncloud.android.datamodel.OCFile
@@ -79,7 +79,7 @@ class FileDetailFragmentStaticServerIT : AbstractIT() {
var activity: TestActivity? = null
scenario.onActivity { sut ->
activity = sut
val fragment = FileInfoFragment.newInstance(oCFile, user).apply {
val fragment = ImageDetailFragment.newInstance(oCFile, user).apply {
hideMap()
}
sut.addFragment(fragment)
@@ -1,7 +1,6 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-FileCopyrightText: 2020 Tobias Kaminsky <tobias@kaminsky.me>
* SPDX-FileCopyrightText: 2020 Chris Narkiewicz <hello@ezaquarii.com>
* SPDX-FileCopyrightText: 2021 TSI-mc
@@ -10,13 +9,11 @@
package com.owncloud.android.ui.fragment
import android.view.View
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.launchActivity
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.accessibility.AccessibilityChecks
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers.isDialog
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.espresso.matcher.ViewMatchers.isChecked
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
@@ -27,7 +24,6 @@ import com.google.android.apps.common.testing.accessibility.framework.Accessibil
import com.google.android.apps.common.testing.accessibility.framework.AccessibilityCheckResultUtils.matchesViews
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.nextcloud.android.lib.resources.files.FileDownloadLimit
import com.nextcloud.test.Flaky
import com.nextcloud.test.RetryTestRule
import com.nextcloud.test.TestActivity
import com.owncloud.android.AbstractIT
@@ -42,8 +38,6 @@ import com.owncloud.android.lib.resources.shares.OCShare.Companion.NO_PERMISSION
import com.owncloud.android.lib.resources.shares.OCShare.Companion.READ_PERMISSION_FLAG
import com.owncloud.android.lib.resources.shares.OCShare.Companion.SHARE_PERMISSION_FLAG
import com.owncloud.android.lib.resources.shares.ShareType
import com.owncloud.android.lib.resources.status.CapabilityBooleanType
import com.owncloud.android.lib.resources.status.OCCapability
import com.owncloud.android.ui.activity.FileDisplayActivity
import com.owncloud.android.ui.fragment.util.SharePermissionManager
import com.owncloud.android.utils.ScreenshotTest
@@ -52,8 +46,6 @@ import org.hamcrest.CoreMatchers.anyOf
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.not
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@@ -90,14 +82,12 @@ class FileDetailSharingFragmentIT : AbstractIT() {
@Test
@ScreenshotTest
@Flaky("not stable")
fun listSharesFileNone() {
show(file)
}
@Test
@ScreenshotTest
@Flaky("not stable")
fun listSharesFileResharingNotAllowed() {
file.permissions = ""
@@ -106,7 +96,6 @@ class FileDetailSharingFragmentIT : AbstractIT() {
@Test
@ScreenshotTest
@Flaky("not stable")
fun listSharesDownloadLimit() {
launchActivity<TestActivity>().use { scenario ->
scenario.onActivity { activity ->
@@ -160,7 +149,6 @@ class FileDetailSharingFragmentIT : AbstractIT() {
@Test
@ScreenshotTest
@Suppress("MagicNumber")
@Flaky("not stable")
fun listSharesFileAllShareTypes() {
launchActivity<TestActivity>().use { scenario ->
scenario.onActivity { activity ->
@@ -291,30 +279,36 @@ class FileDetailSharingFragmentIT : AbstractIT() {
// for advanced permissions
@Test
@Suppress("MagicNumber")
@Flaky("not stable")
fun publicLinkOptionMenuFolderAdvancePermission() {
launchActivity<TestActivity>().use { scenario ->
lateinit var sut: FileDetailSharingFragment
scenario.onActivity { activity ->
sut = addSharingFragment(activity)
var sut: FileDetailSharingFragment? = null
var activity: TestActivity? = null
scenario.onActivity { testActivity ->
activity = testActivity
sut = FileDetailSharingFragment.newInstance(file, user)
activity.addFragment(sut)
activity.supportFragmentManager.executePendingTransactions()
}
setupSecondaryFragment()
sut!!.refreshCapabilitiesFromDB()
val publicShare = OCShare().apply {
isFolder = true
shareType = ShareType.PUBLIC_LINK
permissions = 17
}
scenario.onActivity { sut.showSharingMenuActionSheet(publicShare) }
activity!!.runOnUiThread { sut.showSharingMenuActionSheet(publicShare) }
// check if items are visible
onMenuItem(R.id.menu_share_advanced_permissions).check(matches(isDisplayed()))
onMenuItem(R.id.menu_share_send_new_email).check(matches(isDisplayed()))
onMenuItem(R.id.menu_share_send_link).check(matches(isDisplayed()))
onMenuItem(R.id.menu_share_unshare).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_advanced_permissions)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_send_new_email)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_send_link)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_unshare)).check(matches(isDisplayed()))
// click event
onMenuItem(R.id.menu_share_advanced_permissions).perform(ViewActions.click())
onView(ViewMatchers.withId(R.id.menu_share_advanced_permissions)).perform(ViewActions.click())
// validate view shown on screen
onView(ViewMatchers.withId(R.id.view_only_radio_button)).check(matches(isDisplayed()))
@@ -328,57 +322,57 @@ class FileDetailSharingFragmentIT : AbstractIT() {
onView(ViewMatchers.withId(R.id.view_only_radio_button)).check(matches(isChecked()))
onView(ViewMatchers.withId(R.id.can_edit_radio_button)).check(matches(isNotChecked()))
onView(ViewMatchers.withId(R.id.file_request_radio_button)).check(matches(isNotChecked()))
goBack(scenario)
goBack()
// upload and editing
publicShare.permissions = MAXIMUM_PERMISSIONS_FOR_FOLDER
openAdvancedPermissions(scenario, sut, publicShare)
openAdvancedPermissions(sut, publicShare)
onView(ViewMatchers.withId(R.id.view_only_radio_button)).check(matches(isNotChecked()))
onView(ViewMatchers.withId(R.id.can_edit_radio_button)).check(matches(isChecked()))
onView(ViewMatchers.withId(R.id.file_request_radio_button)).check(matches(isNotChecked()))
goBack(scenario)
goBack()
// file request
publicShare.permissions = 4
openAdvancedPermissions(scenario, sut, publicShare)
openAdvancedPermissions(sut, publicShare)
onView(ViewMatchers.withId(R.id.view_only_radio_button)).check(matches(isNotChecked()))
onView(ViewMatchers.withId(R.id.can_edit_radio_button)).check(matches(isNotChecked()))
onView(ViewMatchers.withId(R.id.file_request_radio_button)).check(matches(isChecked()))
goBack(scenario)
goBack()
// password protection
publicShare.shareWith = "someValue"
openAdvancedPermissions(scenario, sut, publicShare)
openAdvancedPermissions(sut, publicShare)
onView(ViewMatchers.withId(R.id.share_process_set_password_switch)).check(matches(isChecked()))
goBack(scenario)
goBack()
publicShare.shareWith = ""
openAdvancedPermissions(scenario, sut, publicShare)
openAdvancedPermissions(sut, publicShare)
onView(ViewMatchers.withId(R.id.share_process_set_password_switch)).check(matches(isNotChecked()))
goBack(scenario)
goBack()
// hide download
publicShare.isHideFileDownload = true
publicShare.permissions = MAXIMUM_PERMISSIONS_FOR_FOLDER
openAdvancedPermissions(scenario, sut, publicShare)
openAdvancedPermissions(sut, publicShare)
onView(ViewMatchers.withId(R.id.share_process_hide_download_checkbox)).check(matches(isChecked()))
goBack(scenario)
goBack()
publicShare.isHideFileDownload = false
openAdvancedPermissions(scenario, sut, publicShare)
openAdvancedPermissions(sut, publicShare)
onView(
ViewMatchers.withId(R.id.share_process_hide_download_checkbox)
).check(matches(isNotChecked()))
goBack(scenario)
goBack()
publicShare.expirationDate = 1582019340000
openAdvancedPermissions(scenario, sut, publicShare)
openAdvancedPermissions(sut, publicShare)
onView(ViewMatchers.withId(R.id.share_process_set_exp_date_switch)).check(matches(isChecked()))
onView(ViewMatchers.withId(R.id.share_process_select_exp_date)).check(matches(not(withText(""))))
goBack(scenario)
goBack()
publicShare.expirationDate = 0
openAdvancedPermissions(scenario, sut, publicShare)
openAdvancedPermissions(sut, publicShare)
onView(ViewMatchers.withId(R.id.share_process_set_exp_date_switch)).check(matches(isNotChecked()))
onView(ViewMatchers.withId(R.id.share_process_select_exp_date)).check(matches(withText("")))
}
@@ -388,76 +382,76 @@ class FileDetailSharingFragmentIT : AbstractIT() {
// for send new email
@Test
@Suppress("MagicNumber")
@Flaky("not stable")
fun publicLinkOptionMenuFolderSendNewEmail() {
launchActivity<TestActivity>().use { scenario ->
lateinit var sut: FileDetailSharingFragment
var sut: FileDetailSharingFragment? = null
scenario.onActivity { activity ->
sut = addSharingFragment(activity)
sut = FileDetailSharingFragment.newInstance(file, user)
activity.addFragment(sut)
sut.refreshCapabilitiesFromDB()
}
setupSecondaryFragment()
val publicShare = OCShare().apply {
isFolder = true
shareType = ShareType.PUBLIC_LINK
permissions = 17
}
verifySendNewEmail(scenario, sut, publicShare)
verifySendNewEmail(sut!!, publicShare)
}
}
private fun addSharingFragment(activity: TestActivity): FileDetailSharingFragment {
val fragment = FileDetailSharingFragment.newInstance(file, user)
activity.addFragment(fragment)
fragment.refreshCapabilitiesFromDB()
setupSecondaryFragment(activity)
activity.supportFragmentManager.executePendingTransactions()
return fragment
}
// the sharing action sheet is a BottomSheetDialog, so its items must be matched in the dialog window
private fun onMenuItem(id: Int) = onView(ViewMatchers.withId(id)).inRoot(isDialog())
private fun setupSecondaryFragment(activity: TestActivity) {
val parentFolder = OCFile("/")
val secondary = FileDetailFragment.newInstance(file, parentFolder, user)
activity.addSecondaryFragment(secondary, FileDisplayActivity.TAG_LIST_OF_FILES)
activity.addView(
FloatingActionButton(activity).apply {
// needed for some reason
visibility = View.GONE
id = R.id.fab_main
private fun setupSecondaryFragment() {
launchActivity<TestActivity>().use { scenario ->
scenario.onActivity { activity ->
val parentFolder = OCFile("/")
val secondary = FileDetailFragment.newInstance(file, parentFolder, user)
activity.addSecondaryFragment(secondary, FileDisplayActivity.TAG_LIST_OF_FILES)
activity.addView(
FloatingActionButton(activity).apply {
// needed for some reason
visibility = View.GONE
id = R.id.fab_main
}
)
}
)
}
}
// public link and email are handled the same way
// for advanced permissions
@Test
@Suppress("MagicNumber")
@Flaky("not stable")
fun publicLinkOptionMenuFileAdvancePermission() {
launchActivity<TestActivity>().use { scenario ->
lateinit var sut: FileDetailSharingFragment
scenario.onActivity { activity ->
sut = addSharingFragment(activity)
var sut: FileDetailSharingFragment? = null
var activity: TestActivity? = null
scenario.onActivity { testActivity ->
activity = testActivity
sut = FileDetailSharingFragment.newInstance(file, user)
activity.addFragment(sut)
sut.refreshCapabilitiesFromDB()
}
setupSecondaryFragment()
val publicShare = OCShare().apply {
isFolder = false
shareType = ShareType.PUBLIC_LINK
permissions = 17
}
scenario.onActivity { sut.showSharingMenuActionSheet(publicShare) }
activity!!.handler.post { sut!!.showSharingMenuActionSheet(publicShare) }
// check if items are visible
onMenuItem(R.id.menu_share_advanced_permissions).check(matches(isDisplayed()))
onMenuItem(R.id.menu_share_send_new_email).check(matches(isDisplayed()))
onMenuItem(R.id.menu_share_send_link).check(matches(isDisplayed()))
onMenuItem(R.id.menu_share_unshare).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_advanced_permissions)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_send_new_email)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_send_link)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_unshare)).check(matches(isDisplayed()))
// click event
onMenuItem(R.id.menu_share_advanced_permissions).perform(ViewActions.click())
onView(ViewMatchers.withId(R.id.menu_share_advanced_permissions)).perform(ViewActions.click())
// validate view shown on screen
onView(ViewMatchers.withId(R.id.view_only_radio_button)).check(matches(isDisplayed()))
@@ -473,50 +467,50 @@ class FileDetailSharingFragmentIT : AbstractIT() {
publicShare.permissions = 17 // from server
onView(ViewMatchers.withId(R.id.view_only_radio_button)).check(matches(isChecked()))
onView(ViewMatchers.withId(R.id.can_edit_radio_button)).check(matches(isNotChecked()))
goBack(scenario)
goBack()
// editing
publicShare.permissions = MAXIMUM_PERMISSIONS_FOR_FILE // from server
openAdvancedPermissions(scenario, sut, publicShare)
openAdvancedPermissions(sut!!, publicShare)
onView(ViewMatchers.withId(R.id.view_only_radio_button)).check(matches(isNotChecked()))
onView(ViewMatchers.withId(R.id.can_edit_radio_button)).check(matches(isChecked()))
goBack(scenario)
goBack()
// hide download
publicShare.isHideFileDownload = true
openAdvancedPermissions(scenario, sut, publicShare)
openAdvancedPermissions(sut, publicShare)
onView(ViewMatchers.withId(R.id.share_process_hide_download_checkbox)).check(matches(isChecked()))
goBack(scenario)
goBack()
publicShare.isHideFileDownload = false
openAdvancedPermissions(scenario, sut, publicShare)
openAdvancedPermissions(sut, publicShare)
onView(
ViewMatchers.withId(R.id.share_process_hide_download_checkbox)
).check(matches(isNotChecked()))
goBack(scenario)
goBack()
// password protection
publicShare.isPasswordProtected = true
publicShare.shareWith = "someValue"
openAdvancedPermissions(scenario, sut, publicShare)
openAdvancedPermissions(sut, publicShare)
onView(ViewMatchers.withId(R.id.share_process_set_password_switch)).check(matches(isChecked()))
goBack(scenario)
goBack()
publicShare.isPasswordProtected = false
publicShare.shareWith = ""
openAdvancedPermissions(scenario, sut, publicShare)
openAdvancedPermissions(sut, publicShare)
onView(ViewMatchers.withId(R.id.share_process_set_password_switch)).check(matches(isNotChecked()))
goBack(scenario)
goBack()
// expires
publicShare.expirationDate = 1582019340
openAdvancedPermissions(scenario, sut, publicShare)
openAdvancedPermissions(sut, publicShare)
onView(ViewMatchers.withId(R.id.share_process_set_exp_date_switch)).check(matches(isChecked()))
onView(ViewMatchers.withId(R.id.share_process_select_exp_date)).check(matches(not(withText(""))))
goBack(scenario)
goBack()
publicShare.expirationDate = 0
openAdvancedPermissions(scenario, sut, publicShare)
openAdvancedPermissions(sut, publicShare)
onView(ViewMatchers.withId(R.id.share_process_set_exp_date_switch)).check(matches(isNotChecked()))
onView(ViewMatchers.withId(R.id.share_process_select_exp_date)).check(matches(withText("")))
}
@@ -526,21 +520,25 @@ class FileDetailSharingFragmentIT : AbstractIT() {
// for send new email
@Test
@Suppress("MagicNumber")
@Flaky("not stable")
fun publicLinkOptionMenuFileSendNewEmail() {
launchActivity<TestActivity>().use { scenario ->
lateinit var sut: FileDetailSharingFragment
var sut: FileDetailSharingFragment? = null
scenario.onActivity { activity ->
sut = addSharingFragment(activity)
sut = FileDetailSharingFragment.newInstance(file, user)
activity.addFragment(sut)
sut.refreshCapabilitiesFromDB()
}
setupSecondaryFragment()
val publicShare = OCShare().apply {
isFolder = false
shareType = ShareType.PUBLIC_LINK
permissions = 17
}
verifySendNewEmail(scenario, sut, publicShare)
verifySendNewEmail(sut!!, publicShare)
}
}
@@ -552,31 +550,36 @@ class FileDetailSharingFragmentIT : AbstractIT() {
// for advanced permissions
@Test
@Suppress("MagicNumber")
@Flaky("not stable")
fun userOptionMenuFileAdvancePermission() {
launchActivity<TestActivity>().use { scenario ->
lateinit var sut: FileDetailSharingFragment
scenario.onActivity { activity ->
var activity: TestActivity? = null
var sut: FileDetailSharingFragment? = null
scenario.onActivity { testActivity ->
activity = testActivity
sut = FileDetailSharingFragment.newInstance(file, user)
suppressFDFAccessibilityChecks()
sut = addSharingFragment(activity)
activity.addFragment(sut)
sut.refreshCapabilitiesFromDB()
}
setupSecondaryFragment()
val userShare = OCShare().apply {
isFolder = false
shareType = ShareType.USER
permissions = 17
}
scenario.onActivity { sut.showSharingMenuActionSheet(userShare) }
activity!!.runOnUiThread { sut!!.showSharingMenuActionSheet(userShare) }
// check if items are visible
onMenuItem(R.id.menu_share_advanced_permissions).check(matches(isDisplayed()))
onMenuItem(R.id.menu_share_send_new_email).check(matches(isDisplayed()))
onMenuItem(R.id.menu_share_send_link).check(matches(not(isDisplayed())))
onMenuItem(R.id.menu_share_unshare).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_advanced_permissions)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_send_new_email)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_send_link)).check(matches(not(isDisplayed())))
onView(ViewMatchers.withId(R.id.menu_share_unshare)).check(matches(isDisplayed()))
// click event
onMenuItem(R.id.menu_share_advanced_permissions).perform(ViewActions.click())
onView(ViewMatchers.withId(R.id.menu_share_advanced_permissions)).perform(ViewActions.click())
// validate view shown on screen
onView(ViewMatchers.withId(R.id.view_only_radio_button)).check(matches(isDisplayed()))
@@ -598,24 +601,24 @@ class FileDetailSharingFragmentIT : AbstractIT() {
userShare.permissions = 17 // from server
onView(ViewMatchers.withId(R.id.view_only_radio_button)).check(matches(isChecked()))
onView(ViewMatchers.withId(R.id.can_edit_radio_button)).check(matches(isNotChecked()))
goBack(scenario)
goBack()
// editing
userShare.permissions = MAXIMUM_PERMISSIONS_FOR_FILE // from server
openAdvancedPermissions(scenario, sut, userShare)
openAdvancedPermissions(sut!!, userShare)
onView(ViewMatchers.withId(R.id.view_only_radio_button)).check(matches(isNotChecked()))
onView(ViewMatchers.withId(R.id.can_edit_radio_button)).check(matches(isChecked()))
goBack(scenario)
goBack()
// set expiration date
userShare.expirationDate = 1582019340000
openAdvancedPermissions(scenario, sut, userShare)
openAdvancedPermissions(sut, userShare)
onView(ViewMatchers.withId(R.id.share_process_set_exp_date_switch)).check(matches(isChecked()))
onView(ViewMatchers.withId(R.id.share_process_select_exp_date)).check(matches(not(withText(""))))
goBack(scenario)
goBack()
userShare.expirationDate = 0
openAdvancedPermissions(scenario, sut, userShare)
openAdvancedPermissions(sut, userShare)
onView(ViewMatchers.withId(R.id.share_process_set_exp_date_switch)).check(matches(isNotChecked()))
onView(ViewMatchers.withId(R.id.share_process_select_exp_date)).check(matches(withText("")))
}
@@ -646,14 +649,17 @@ class FileDetailSharingFragmentIT : AbstractIT() {
// for send new email
@Test
@Suppress("MagicNumber")
@Flaky("not stable")
fun userOptionMenuFileSendNewEmail() {
launchActivity<TestActivity>().use { scenario ->
lateinit var sut: FileDetailSharingFragment
var sut: FileDetailSharingFragment? = null
scenario.onActivity { activity ->
sut = addSharingFragment(activity)
sut = FileDetailSharingFragment.newInstance(file, user)
activity.addFragment(sut)
sut.refreshCapabilitiesFromDB()
}
setupSecondaryFragment()
val userShare = OCShare().apply {
remoteId = 1001L
isFolder = false
@@ -661,7 +667,7 @@ class FileDetailSharingFragmentIT : AbstractIT() {
permissions = 17
}
verifySendNewEmail(scenario, sut, userShare)
verifySendNewEmail(sut!!, userShare)
}
}
@@ -673,37 +679,41 @@ class FileDetailSharingFragmentIT : AbstractIT() {
// for advanced permissions
@Test
@Suppress("MagicNumber")
@Flaky("not stable")
fun userOptionMenuFolderAdvancePermission() {
launchActivity<TestActivity>().use { scenario ->
lateinit var sut: FileDetailSharingFragment
scenario.onActivity { activity ->
var activity: TestActivity? = null
var sut: FileDetailSharingFragment? = null
scenario.onActivity { testActivity ->
activity = testActivity
sut = FileDetailSharingFragment.newInstance(file, user)
activity.addFragment(sut)
suppressFDFAccessibilityChecks()
sut = addSharingFragment(activity)
sut.refreshCapabilitiesFromDB()
}
setupSecondaryFragment()
val userShare = OCShare().apply {
isFolder = true
shareType = ShareType.USER
permissions = 17
}
scenario.onActivity { sut.showSharingMenuActionSheet(userShare) }
activity!!.runOnUiThread { sut!!.showSharingMenuActionSheet(userShare) }
// check if items are visible
onMenuItem(R.id.menu_share_advanced_permissions).check(matches(isDisplayed()))
onMenuItem(R.id.menu_share_send_new_email).check(matches(isDisplayed()))
onMenuItem(R.id.menu_share_send_link).check(matches(not(isDisplayed())))
onMenuItem(R.id.menu_share_unshare).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_advanced_permissions)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_send_new_email)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.menu_share_send_link)).check(matches(not(isDisplayed())))
onView(ViewMatchers.withId(R.id.menu_share_unshare)).check(matches(isDisplayed()))
// click event
onMenuItem(R.id.menu_share_advanced_permissions).perform(ViewActions.click())
onView(ViewMatchers.withId(R.id.menu_share_advanced_permissions)).perform(ViewActions.click())
// validate view shown on screen
// file request is only offered for public link and email shares, not for user shares
onView(ViewMatchers.withId(R.id.view_only_radio_button)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.can_edit_radio_button)).check(matches(isDisplayed()))
onView(ViewMatchers.withId(R.id.file_request_radio_button)).check(matches(not(isDisplayed())))
onView(ViewMatchers.withId(R.id.file_request_radio_button)).check(matches(isDisplayed()))
onView(
ViewMatchers.withId(R.id.share_process_hide_download_checkbox)
).check(matches(not(isDisplayed())))
@@ -718,46 +728,63 @@ class FileDetailSharingFragmentIT : AbstractIT() {
userShare.permissions = 17 // from server
onView(ViewMatchers.withId(R.id.view_only_radio_button)).check(matches(isChecked()))
onView(ViewMatchers.withId(R.id.can_edit_radio_button)).check(matches(isNotChecked()))
goBack(scenario)
onView(ViewMatchers.withId(R.id.file_request_radio_button)).check(matches(isNotChecked()))
goBack()
// allow upload & editing
userShare.permissions = MAXIMUM_PERMISSIONS_FOR_FOLDER // from server
openAdvancedPermissions(scenario, sut, userShare)
openAdvancedPermissions(sut!!, userShare)
onView(ViewMatchers.withId(R.id.view_only_radio_button)).check(matches(isNotChecked()))
onView(ViewMatchers.withId(R.id.can_edit_radio_button)).check(matches(isChecked()))
goBack(scenario)
onView(ViewMatchers.withId(R.id.file_request_radio_button)).check(matches(isNotChecked()))
goBack()
// file request
userShare.permissions = 4
openAdvancedPermissions(sut, userShare)
onView(ViewMatchers.withId(R.id.view_only_radio_button)).check(matches(isNotChecked()))
onView(ViewMatchers.withId(R.id.can_edit_radio_button)).check(matches(isNotChecked()))
onView(ViewMatchers.withId(R.id.file_request_radio_button)).check(matches(isChecked()))
goBack()
// set expiration date
userShare.expirationDate = 1582019340000
openAdvancedPermissions(scenario, sut, userShare)
openAdvancedPermissions(sut, userShare)
onView(ViewMatchers.withId(R.id.share_process_set_exp_date_switch)).check(matches(isChecked()))
onView(ViewMatchers.withId(R.id.share_process_select_exp_date)).check(matches(not(withText(""))))
goBack(scenario)
goBack()
userShare.expirationDate = 0
openAdvancedPermissions(scenario, sut, userShare)
openAdvancedPermissions(sut, userShare)
onView(ViewMatchers.withId(R.id.share_process_set_exp_date_switch)).check(matches(isNotChecked()))
onView(ViewMatchers.withId(R.id.share_process_select_exp_date)).check(matches(withText("")))
}
}
// open bottom sheet with actions
private fun openAdvancedPermissions(
scenario: ActivityScenario<TestActivity>,
sut: FileDetailSharingFragment,
userShare: OCShare
) {
scenario.onActivity { sut.showSharingMenuActionSheet(userShare) }
onMenuItem(R.id.menu_share_advanced_permissions).perform(ViewActions.click())
private fun openAdvancedPermissions(sut: FileDetailSharingFragment, userShare: OCShare) {
launchActivity<TestActivity>().use { scenario ->
scenario.onActivity { activity ->
activity.handler.post {
sut.showSharingMenuActionSheet(userShare)
}
}
onView(ViewMatchers.withId(R.id.menu_share_advanced_permissions)).perform(ViewActions.click())
}
}
// remove the fragment shown
private fun goBack(scenario: ActivityScenario<TestActivity>) {
scenario.onActivity { activity ->
val processFragment =
activity.supportFragmentManager.findFragmentByTag(FileDetailsSharingProcessFragment.TAG) as
FileDetailsSharingProcessFragment
processFragment.onBackPressed()
private fun goBack() {
launchActivity<TestActivity>().use { scenario ->
scenario.onActivity { activity ->
activity.handler.post {
val processFragment =
activity.supportFragmentManager.findFragmentByTag(FileDetailsSharingProcessFragment.TAG) as
FileDetailsSharingProcessFragment
processFragment.activity?.onBackPressedDispatcher?.onBackPressed()
}
}
}
}
@@ -769,43 +796,45 @@ class FileDetailSharingFragmentIT : AbstractIT() {
// for send new email
@Test
@Suppress("MagicNumber")
@Flaky(reason = "Share option menu occasionally does not open before the assertions run")
fun userOptionMenuFolderSendNewEmail() {
launchActivity<TestActivity>().use { scenario ->
lateinit var sut: FileDetailSharingFragment
var sut: FileDetailSharingFragment? = null
scenario.onActivity { activity ->
sut = addSharingFragment(activity)
sut = FileDetailSharingFragment.newInstance(file, user)
activity.addFragment(sut)
sut.refreshCapabilitiesFromDB()
}
setupSecondaryFragment()
val userShare = OCShare().apply {
isFolder = true
shareType = ShareType.USER
permissions = 17
}
verifySendNewEmail(scenario, sut, userShare)
verifySendNewEmail(sut!!, userShare)
}
}
/**
* verify send new email note text
*/
private fun verifySendNewEmail(
scenario: ActivityScenario<TestActivity>,
sut: FileDetailSharingFragment,
userShare: OCShare
) {
scenario.onActivity { sut.showSharingMenuActionSheet(userShare) }
private fun verifySendNewEmail(sut: FileDetailSharingFragment, userShare: OCShare) {
launchActivity<TestActivity>().use { scenario ->
scenario.onActivity { activity ->
activity.runOnUiThread { sut.showSharingMenuActionSheet(userShare) }
}
// click event
onMenuItem(R.id.menu_share_send_new_email).perform(ViewActions.click())
// click event
onView(ViewMatchers.withId(R.id.menu_share_send_new_email)).perform(ViewActions.click())
// validate view shown on screen
onView(ViewMatchers.withId(R.id.note_text)).check(matches(isDisplayed()))
// validate view shown on screen
onView(ViewMatchers.withId(R.id.note_text)).check(matches(isDisplayed()))
}
}
@Test
@Flaky("not stable")
fun testUploadAndEditingSharePermissions() {
val testCases = mapOf(
MAXIMUM_PERMISSIONS_FOR_FOLDER to true,
@@ -824,7 +853,6 @@ class FileDetailSharingFragmentIT : AbstractIT() {
}
@Test
@Flaky("not stable")
fun testReadOnlySharePermissions() {
val testCases = mapOf(
READ_PERMISSION_FLAG to true,
@@ -844,7 +872,6 @@ class FileDetailSharingFragmentIT : AbstractIT() {
}
@Test
@Flaky("not stable")
fun testFileRequestSharePermission() {
val testCases = mapOf(
CREATE_PERMISSION_FLAG to true,
@@ -865,58 +892,4 @@ class FileDetailSharingFragmentIT : AbstractIT() {
assertEquals("Failed for permission: $permission", expected, SharePermissionManager.isFileRequest(share))
}
}
@Test
@Flaky("not stable")
fun internalLinkUsesPrettyPathWhenModRewriteWorking() {
launchActivity<TestActivity>().use { scenario ->
var sut: FileDetailSharingFragment? = null
scenario.onActivity { activity ->
sut = FileDetailSharingFragment.newInstance(file, user)
activity.addFragment(sut)
activity.supportFragmentManager.executePendingTransactions()
}
val capabilities = OCCapability().apply { modRewriteWorking = CapabilityBooleanType.TRUE }
val link = sut!!.createInternalLink(user, file, capabilities)
assertTrue(link.endsWith("/f/" + file.localId))
assertFalse(link.contains("/index.php/"))
}
}
@Test
@Flaky("not stable")
fun internalLinkUsesDefaultPathWhenModRewriteNotWorking() {
launchActivity<TestActivity>().use { scenario ->
var sut: FileDetailSharingFragment? = null
scenario.onActivity { activity ->
sut = FileDetailSharingFragment.newInstance(file, user)
activity.addFragment(sut)
activity.supportFragmentManager.executePendingTransactions()
}
val capabilities = OCCapability().apply { modRewriteWorking = CapabilityBooleanType.FALSE }
val link = sut!!.createInternalLink(user, file, capabilities)
assertTrue(link.endsWith("/index.php/f/" + file.localId))
}
}
@Test
@Flaky("not stable")
fun internalLinkFallsBackToDefaultPathWhenCapabilitiesNull() {
launchActivity<TestActivity>().use { scenario ->
var sut: FileDetailSharingFragment? = null
scenario.onActivity { activity ->
sut = FileDetailSharingFragment.newInstance(file, user)
activity.addFragment(sut)
activity.supportFragmentManager.executePendingTransactions()
}
val link = sut!!.createInternalLink(user, file, null)
assertTrue(link.endsWith("/index.php/f/" + file.localId))
}
}
}
@@ -27,14 +27,12 @@ import androidx.test.espresso.contrib.RecyclerViewActions.actionOnItemAtPosition
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.isRoot
import androidx.test.espresso.matcher.ViewMatchers.withId
import com.nextcloud.test.Flaky
import com.nextcloud.test.TestActivity
import com.nextcloud.utils.extensions.getBigThumbnail
import com.nextcloud.utils.extensions.getBigThumbnailKey
import com.owncloud.android.AbstractIT
import com.owncloud.android.R
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.ThumbnailsCacheManager
import com.owncloud.android.datamodel.ThumbnailsCacheManager.PREFIX_RESIZED_IMAGE
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.lib.resources.files.model.ImageDimension
import com.owncloud.android.ui.adapter.GalleryRowHolder
@@ -102,7 +100,6 @@ class GalleryFragmentIT : AbstractIT() {
}
@Test
@Flaky(reason = "Gallery sections are occasionally not laid out before the multi select assertions run")
fun multiSelect() {
val imageCount = 100
for (num in 1..imageCount) {
@@ -222,9 +219,9 @@ class GalleryFragmentIT : AbstractIT() {
drawRGB(random.nextInt(256), random.nextInt(256), random.nextInt(256))
drawCircle(w / 2f, h / 2f, w.coerceAtMost(h) / 2f, Paint().apply { color = Color.BLACK })
}
ThumbnailsCacheManager.addBitmapToCache(file.getBigThumbnailKey(), bitmap)
ThumbnailsCacheManager.addBitmapToCache(PREFIX_RESIZED_IMAGE + file.remoteId, bitmap)
assertNotNull(file.getBigThumbnail())
assertNotNull(ThumbnailsCacheManager.getBitmapFromDiskCache(PREFIX_RESIZED_IMAGE + file.remoteId))
Log_OC.d("Gallery_thumbnail", "created $id with ${bitmap.width} x ${bitmap.height}")
}
@@ -22,7 +22,6 @@ import androidx.test.espresso.matcher.ViewMatchers.isEnabled
import androidx.test.espresso.matcher.ViewMatchers.isRoot
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import com.nextcloud.test.Flaky
import com.nextcloud.test.GrantStoragePermissionRule.Companion.grant
import com.nextcloud.test.TestActivity
import com.owncloud.android.AbstractIT
@@ -37,7 +36,6 @@ import com.owncloud.android.utils.MimeType
import com.owncloud.android.utils.ScreenshotTest
import org.hamcrest.Matchers.allOf
import org.hamcrest.Matchers.not
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
@@ -55,11 +53,6 @@ class OCFileListFragmentStaticServerIT : AbstractIT() {
Intents.init()
}
@After
fun releaseIntentRecording() {
Intents.release()
}
@Test
@ScreenshotTest
@Suppress("MagicNumber")
@@ -424,7 +417,6 @@ class OCFileListFragmentStaticServerIT : AbstractIT() {
}
@Test
@Flaky(reason = "Folder picker activity is occasionally not started before the intent assertions run")
fun shouldStartMoveInParentFolder() {
launchActivity<TestActivity>().use { scenario ->
val fragment = OCFileListFragment()
@@ -13,13 +13,11 @@ 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.Flaky
import com.nextcloud.test.TestActivity
import com.owncloud.android.AbstractIT
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.lib.common.SearchResultEntry
import com.owncloud.android.ui.unifiedsearch.UnifiedSearchSection
import com.owncloud.android.ui.unifiedsearch.toUnifiedSearchEntry
import com.owncloud.android.ui.unifiedsearch.UnifiedSearchViewModel
import org.junit.Test
import java.io.File
@@ -27,7 +25,6 @@ import java.io.File
class UnifiedSearchFragmentIT : AbstractIT() {
@Test
@Flaky(reason = "Search result list is occasionally not rendered before the assertions run")
fun showSearchResult() {
launchActivity<TestActivity>().use { scenario ->
@@ -48,7 +45,7 @@ class UnifiedSearchFragmentIT : AbstractIT() {
"http://localhost/nc/index.php/apps/files/?dir=/Files&scrollto=Test",
"icon",
false
).toUnifiedSearchEntry(storageManager)
)
),
hasMoreResults = false
)
@@ -61,7 +58,6 @@ class UnifiedSearchFragmentIT : AbstractIT() {
}
@Test
@Flaky(reason = "Search runs asynchronously and does not always complete before the assertions run")
fun search() {
launchActivity<TestActivity>().use { scenario ->
scenario.onActivity { activity ->
@@ -21,8 +21,8 @@ import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.isRoot
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import com.nextcloud.test.ConnectivityServiceOfflineMock
import com.nextcloud.test.FileRemovedIdlingResource
import com.nextcloud.test.Flaky
import com.nextcloud.test.LoopFailureHandler
import com.owncloud.android.AbstractOnServerIT
import com.owncloud.android.R
@@ -30,7 +30,6 @@ import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.db.OCUpload
import com.owncloud.android.files.services.NameCollisionPolicy
import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation
import com.owncloud.android.utils.FileStorageUtils
import org.hamcrest.Matchers.allOf
import org.junit.After
import org.junit.Assert.assertFalse
@@ -51,20 +50,29 @@ class PreviewImageActivityIT : AbstractOnServerIT() {
private fun createLocalMockedImageFiles(count: Int): List<OCFile> {
val srcPngFile = getFile("imageFile.png")
return (0 until count).map { i ->
OCFile("/image$i.png").apply {
val pngFile = File(srcPngFile.parent ?: ".", "image$i.png")
srcPngFile.copyTo(pngFile, overwrite = true)
OCFile("/${pngFile.name}").apply {
storagePath = pngFile.absolutePath
mimeType = "image/png"
modificationTimestamp = 1000000
permissions = OCFile.PERMISSION_CAN_DELETE_OR_LEAVE_SHARE
val localCopy = File(FileStorageUtils.getDefaultSavePathFor(user.accountName, this))
localCopy.parentFile?.mkdirs()
srcPngFile.copyTo(localCopy, overwrite = true)
storagePath = localCopy.absolutePath
permissions = "D" // OCFile.PERMISSION_CAN_DELETE_OR_LEAVE_SHARE. Required for deletion button to show
}.also {
storageManager.saveNewFile(it)
}
}
}
/**
* Create image files and upload them to the connected server.
*
* This function relies on the images not existing beforehand, as AbstractOnServerIT#deleteAllFilesOnServer()
* should clean up. If it does fail, likely because that clean up didn't work and there are leftovers from
* a previous run
* @param count Number of files to create
* @param folder Parent folder to which to upload. Must start and end with a slash
*/
private fun createAndUploadImageFiles(count: Int, folder: String = REMOTE_FOLDER): List<OCFile> {
val srcPngFile = getFile("imageFile.png")
return (0 until count).map { i ->
@@ -156,7 +164,7 @@ class PreviewImageActivityIT : AbstractOnServerIT() {
launchActivity<PreviewImageActivity>(intent).use { scenario ->
if (offline) {
scenario.onActivity { activity ->
activity.connectivityService = connectivityServiceMock
activity.connectivityService = ConnectivityServiceOfflineMock()
}
}
onView(isRoot()).check(matches(isDisplayed()))
@@ -193,19 +201,16 @@ class PreviewImageActivityIT : AbstractOnServerIT() {
}
@Test
@Flaky(reason = "Slideshow pager does not always settle on the next image before the assertions run")
fun deleteFromSlideshow_localOnly_online() {
testDeleteFromSlideshow_impl(localOnly = true, offline = false)
}
@Test
@Flaky(reason = "Slideshow pager does not always settle on the next image before the assertions run")
fun deleteFromSlideshow_localOnly_offline() {
testDeleteFromSlideshow_impl(localOnly = true, offline = true)
}
@Test
@Flaky(reason = "Remote delete races with the slideshow pager update, so the assertions run too early")
fun deleteFromSlideshow_remote_online() {
testDeleteFromSlideshow_impl(localOnly = false, offline = false)
}
@@ -6,13 +6,13 @@
*/
package com.owncloud.android.ui.preview
import android.Manifest
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 androidx.test.rule.GrantPermissionRule
import com.nextcloud.test.GrantTestPermissionRule
import com.owncloud.android.AbstractIT
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.ui.activity.FileDisplayActivity
@@ -26,7 +26,10 @@ class PreviewTextFileFragmentTest : AbstractIT() {
private val testClassName = "com.owncloud.android.ui.preview.PreviewTextFileFragmentTest"
@get:Rule
val permissionRule: GrantPermissionRule = GrantTestPermissionRule.grantStorageAndNotification()
val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.POST_NOTIFICATIONS
)
@Test
@ScreenshotTest
@@ -1,102 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.utils
import com.owncloud.android.datamodel.e2e.v2.encrypted.EncryptedFolderMetadataFile
import com.owncloud.android.datamodel.e2e.v2.encrypted.EncryptedMetadata
import com.owncloud.android.datamodel.e2e.v2.encrypted.EncryptedUser
import org.junit.Assert.assertTrue
import org.junit.Test
class EncryptionUtilsMetadataVerificationTests {
private val sut = EncryptionUtilsV2()
@Test
fun testVerifyMetadataWhenGivenValidInputsShouldReturnTrue() {
val metadata = EncryptedFolderMetadataFile(
metadata =
EncryptedMetadata(
authenticationTag = "xkVxj0NbQEXIEMlulYZJgg==",
nonce = "HzRiseUfoFJ5lqUi",
ciphertext = "EOnzuyVn9R8qDUBY4yeuJbhQdkOHBMy3nyRGwY0y/+oWctV17XvE0RIbOhH7+smKV3orJKatu5fG6iIZN+" +
"HZUQASTCdQ0mdFVPJmdk20UH5nFZ/ilQIyyXAFhLHdYwWA/M7wKYoh5W9fDXNX9cZvHgjWPdT9Pq99PUv37atYxj7Je" +
"25GenbtxkVxj0NbQEXIEMlulYZJgg=="
),
users = listOf(
EncryptedUser(
userId = "admin",
certificate = "-----BEGIN CERTIFICATE-----\nMIIC7jCCAdagAwIBAgIBADANBgkqhkiG9w0BAQUFADAQMQ4wDAYD" +
"VQQDEwVhZG1p\nbjAeFw0yNjA0MjcwNzI5NDdaFw00NjA0MjIwNzI5NDdaMBAxDjAMBgNVBAMTBWFk\nbWluMIIBIjAN" +
"BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwE513/kdkIp+Z5pI\n7rq1UKV5LBiB6dl4Wh46nI3mhVacOA1dJJWIU" +
"xRkkrUNWJewe8eJ7QWmhSpeBauA\n06PrAOTd1ZA4gSUWKpsYJqKm5Nxjp+BUMK1nHGQCkNQWjRllhyKTJeG/9PPc0Z" +
"rJ\nh4V27bCXC9iX5l/ve35fp99VR4tQ947HWObe07EdPIEFNYfT/IurPwMySZ1WH1gy\nDTw7IxMXcPVg+GUlfBoSV" +
"gQ1UdCkvgHc9pE1LuFmyBguAzGLbXDfspUuTs85RLGX\nGYdv2vZU/R2kJEs3ePMtaGXw6DVSx82RkPFVaLDCdShX24" +
"yk6gLNEv9oTUXY40i3\nn8njRQIDAQABo1MwUTAdBgNVHQ4EFgQUDE381mprCEvSLaFeOwZRliBSJnwwHwYD\nVR0j" +
"BBgwFoAUDE381mprCEvSLaFeOwZRliBSJnwwDwYDVR0TAQH/BAUwAwEB/zAN\nBgkqhkiG9w0BAQUFAAOCAQEAgU0o8" +
"Qp5wn3vkcQLYao2heWKsbYYl8wqkztRVVKb\n+qMe2m/FOOMK1Rxv/anEVHHN+SnTc481fHd8z3w6II28LxJ5M+Ixzo" +
"AFTj6gCv8+\nrL1R9kE91401d1+ulAiJR92ykOcB1h8bk5yoCZSRLIXwViCGUrbC3iu2NLWQDYk4\nvjxwqCSJOWUQh" +
"+qaYGCjB6mgkBMAnXGJCN2fV7sAR7N8Hy7Yh5jvuQOgY574FSoS\nuKCMGJZ6ecJlw+rB5pqanlLS9+HNnQ655/gTYg" +
"VBJClFClh4nwdPHtpyTySwgx1V\nr3VDvglfnZM+gD/D2d9nTLIlT3MZqhGOIkxKvpVVkdJKzg" +
"==\n-----END CERTIFICATE-----",
encryptedMetadataKey = "coawvmhMoAl3iL5okD7K4a4au0Jt0SqUXp6pHP8WD1YTOemFVPsz+ts7TD5kB7ha6Ja3tLdG" +
"Mq76LP/d2/pbHUiKBd6rytUo6ioHsNmmlTGHAlk9VTDY9fcvtVgkNzy7qyXvsdsUn0gBQ18l526J/bt1uRlClYNKva" +
"EnIh2l3B8X58pzNZqhAKNI7z7WRDbXOVskr4rnqWr2ExBeaZgFwo5nNi9yiqpckICb1S2qwuZJbItqZ8VR2bOG+WpC" +
"MwrgcE5UJ6ZvaKLREfmR+qoYYB1oyUuy78eA+sDa3rO5bSgs/9I/cli1b3lZ8JFfgHXRiUYUmBcxZOmUE2IfRSHFTA=="
)
),
version = "2.0",
filedrop = mutableMapOf()
)
val message = EncryptionUtils.serializeJSON(metadata, true)
val cert = """
-----BEGIN CERTIFICATE-----
MIIC7jCCAdagAwIBAgIBADANBgkqhkiG9w0BAQUFADAQMQ4wDAYDVQQDEwVhZG1p
bjAeFw0yNjA0MjcwNzI5NDdaFw00NjA0MjIwNzI5NDdaMBAxDjAMBgNVBAMTBWFk
bWluMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwE513/kdkIp+Z5pI
7rq1UKV5LBiB6dl4Wh46nI3mhVacOA1dJJWIUxRkkrUNWJewe8eJ7QWmhSpeBauA
06PrAOTd1ZA4gSUWKpsYJqKm5Nxjp+BUMK1nHGQCkNQWjRllhyKTJeG/9PPc0ZrJ
h4V27bCXC9iX5l/ve35fp99VR4tQ947HWObe07EdPIEFNYfT/IurPwMySZ1WH1gy
DTw7IxMXcPVg+GUlfBoSVgQ1UdCkvgHc9pE1LuFmyBguAzGLbXDfspUuTs85RLGX
GYdv2vZU/R2kJEs3ePMtaGXw6DVSx82RkPFVaLDCdShX24yk6gLNEv9oTUXY40i3
n8njRQIDAQABo1MwUTAdBgNVHQ4EFgQUDE381mprCEvSLaFeOwZRliBSJnwwHwYD
VR0jBBgwFoAUDE381mprCEvSLaFeOwZRliBSJnwwDwYDVR0TAQH/BAUwAwEB/zAN
BgkqhkiG9w0BAQUFAAOCAQEAgU0o8Qp5wn3vkcQLYao2heWKsbYYl8wqkztRVVKb
+qMe2m/FOOMK1Rxv/anEVHHN+SnTc481fHd8z3w6II28LxJ5M+IxzoAFTj6gCv8+
rL1R9kE91401d1+ulAiJR92ykOcB1h8bk5yoCZSRLIXwViCGUrbC3iu2NLWQDYk4
vjxwqCSJOWUQh+qaYGCjB6mgkBMAnXGJCN2fV7sAR7N8Hy7Yh5jvuQOgY574FSoS
uKCMGJZ6ecJlw+rB5pqanlLS9+HNnQ655/gTYgVBJClFClh4nwdPHtpyTySwgx1V
r3VDvglfnZM+gD/D2d9nTLIlT3MZqhGOIkxKvpVVkdJKzg==
-----END CERTIFICATE-----
""".trimIndent()
val certs = listOf(EncryptionUtils.convertCertFromString(cert))
val signature = """
MIIE1wYJKoZIhvcNAQcCoIIEyDCCBMQCAQExDzANBglghkgBZQMEAgEFADALBgkqhkiG9w0BBwGgggLyMIIC7jCCAdagAwIBAgIB
ADANBgkqhkiG9w0BAQUFADAQMQ4wDAYDVQQDEwVhZG1pbjAeFw0yNjA0MjcwNzI5NDdaFw00NjA0MjIwNzI5NDdaMBAxDjAMBgNV
BAMTBWFkbWluMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwE513/kdkIp+Z5pI7rq1UKV5LBiB6dl4Wh46nI3mhVa
cOA1dJJWIUxRkkrUNWJewe8eJ7QWmhSpeBauA06PrAOTd1ZA4gSUWKpsYJqKm5Nxjp+BUMK1nHGQCkNQWjRllhyKTJeG/9PPc0Zr
Jh4V27bCXC9iX5l/ve35fp99VR4tQ947HWObe07EdPIEFNYfT/IurPwMySZ1WH1gyDTw7IxMXcPVg+GUlfBoSVgQ1UdCkvgHc9p
E1LuFmyBguAzGLbXDfspUuTs85RLGXGYdv2vZU/R2kJEs3ePMtaGXw6DVSx82RkPFVaLDCdShX24yk6gLNEv9oTUXY40i3n8nj
RQIDAQABo1MwUTAdBgNVHQ4EFgQUDE381mprCEvSLaFeOwZRliBSJnwwHwYDVR0jBBgwFoAUDE381mprCEvSLaFeOwZRliBSJnww
DwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAgU0o8Qp5wn3vkcQLYao2heWKsbYYl8wqkztRVVKb+qMe2m/FOOMK
1Rxv/anEVHHN+SnTc481fHd8z3w6II28LxJ5M+IxzoAFTj6gCv8+rL1R9kE91401d1+ulAiJR92ykOcB1h8bk5yoCZSRLIXwViCG
UrbC3iu2NLWQDYk4vjxwqCSJOWUQh+qaYGCjB6mgkBMAnXGJCN2fV7sAR7N8Hy7Yh5jvuQOgY574FSoSuKCMGJZ6ecJlw+rB5pqa
nlLS9+HNnQ655/gTYgVBJClFClh4nwdPHtpyTySwgx1Vr3VDvglfnZM+gD/D2d9nTLIlT3MZqhGOIkxKvpVVkdJKzjGCAakwggGl
AgEAMBUwEDEOMAwGA1UEAxMFYWRtaW4CAQAwDQYJYIZIAWUDBAIBBQCgaTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMC8GCSqG
SIb3DQEJBDEiBCDJDYSA3+VA0KfGQbP7BQsnL/s24W/WIb99zb+4uQ8KLjAcBgkqhkiG9w0BCQUxDxcNMjYwNDI3MDczMDAyWjAL
BgkqhkiG9w0BAQsEggEAYgDB02/z+KaLvieL1hMMA9IZN8KKc4igvilBoS5W7isiArP8D/GIxghMZkrC0Tzqs+/VRlfFREUgf4aBd
9GVzd86Qfrhcrzrdd8hoDQvOw/X3UGftqbgJQmOjZUDpI3TiupyQvOU/zqlIjOq5BiZN6RNti2BTcbNyjaTeVh6u1tcqVVSp/Z0ke
Ub+CnJFtIk6WhFepJMWI0vN84OyegNsjzIMSU2WjiN3i0jmYc62MpxUN0ZzmNgdZ7y6exe1Sb8EYUYL83BehQUPKO5EwEjEwX+ScYz
iWK0atXZioZYI2XLejVbQm1/czPTlA3frywKyM1dnkiufzmRpB49QN4o3g==
""".trimIndent()
val signedData = sut.getSignedData(signature, message)
val result = sut.verifySignedData(signedData, certs)
assertTrue(result)
}
}
@@ -1,7 +1,6 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-FileCopyrightText: 2023 Tobias Kaminsky <tobias@kaminsky.me>
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
@@ -23,7 +22,6 @@ import com.owncloud.android.datamodel.e2e.v2.decrypted.DecryptedUser
import com.owncloud.android.datamodel.e2e.v2.encrypted.EncryptedFiledrop
import com.owncloud.android.datamodel.e2e.v2.encrypted.EncryptedFiledropUser
import com.owncloud.android.datamodel.e2e.v2.encrypted.EncryptedFolderMetadataFile
import com.owncloud.android.lib.resources.status.E2EVersion
import com.owncloud.android.operations.RefreshFolderOperation
import com.owncloud.android.util.EncryptionTestIT
import junit.framework.TestCase.assertEquals
@@ -140,13 +138,6 @@ class EncryptionUtilsV2IT : EncryptionIT() {
2J9mW5WvAAaG+j28Q/GKSuE=
""".trimIndent()
// Decryption derives the metadata version from the stored server capability, so align it with the fixture.
private fun setE2EECapabilityVersion(version: E2EVersion) {
val capability = storageManager.getCapability(account.name)
capability.endToEndEncryptionApiVersion = version
storageManager.saveCapabilities(capability)
}
@Test
fun testEncryptDecryptMetadata() {
val metadataKey = EncryptionUtils.generateKey()
@@ -255,7 +246,6 @@ class EncryptionUtilsV2IT : EncryptionIT() {
}
val metadataFile = generateDecryptedFolderMetadataFile(enc1, enc1Cert)
setE2EECapabilityVersion(E2EVersion.fromValue(metadataFile.version))
val encrypted = encryptionUtilsV2.encryptFolderMetadataFile(
metadataFile,
@@ -309,7 +299,8 @@ class EncryptionUtilsV2IT : EncryptionIT() {
// random string, not real tag
EncryptionUtils.generateUid(),
EncryptionUtils.generateKey(),
metadataFile
metadataFile,
storageManager
)
assertEquals(3, updatedMetadata.metadata.files.size)
@@ -349,6 +340,7 @@ class EncryptionUtilsV2IT : EncryptionIT() {
@Test
fun addFolder() {
val folder = OCFile("/e/")
val enc1 = MockUser("enc1", "Nextcloud")
val metadataFile = generateDecryptedFolderMetadataFile(enc1, enc1Cert)
assertEquals(2, metadataFile.metadata.files.size)
@@ -357,7 +349,9 @@ class EncryptionUtilsV2IT : EncryptionIT() {
val updatedMetadata = encryptionUtilsV2.addFolderToMetadata(
EncryptionUtils.generateUid(),
"new subfolder",
metadataFile
metadataFile,
folder,
storageManager
)
assertEquals(2, updatedMetadata.metadata.files.size)
@@ -366,6 +360,7 @@ class EncryptionUtilsV2IT : EncryptionIT() {
@Test
fun removeFolder() {
val folder = OCFile("/e/")
val enc1 = MockUser("enc1", "Nextcloud")
val metadataFile = generateDecryptedFolderMetadataFile(enc1, enc1Cert)
assertEquals(2, metadataFile.metadata.files.size)
@@ -375,7 +370,9 @@ class EncryptionUtilsV2IT : EncryptionIT() {
var updatedMetadata = encryptionUtilsV2.addFolderToMetadata(
encryptedFileName,
"new subfolder",
metadataFile
metadataFile,
folder,
storageManager
)
assertEquals(2, updatedMetadata.metadata.files.size)
@@ -472,7 +469,6 @@ class EncryptionUtilsV2IT : EncryptionIT() {
val v2 = encryptionUtilsV2.migrateV1ToV2(
v1,
enc1UserId,
storageManager.user,
enc1Cert,
folder,
storageManager
@@ -605,7 +601,7 @@ class EncryptionUtilsV2IT : EncryptionIT() {
metadata.keyChecksums.add(encryptionUtilsV2.hashMetadataKey(metadata.metadataKey))
return DecryptedFolderMetadataFile(metadata, users, mutableMapOf(), E2EVersion.V2_1.value)
return DecryptedFolderMetadataFile(metadata, users, mutableMapOf())
}
@Test
@@ -812,7 +808,6 @@ class EncryptionUtilsV2IT : EncryptionIT() {
fun encryptionMetadataV2() {
val decryptedFolderMetadata1: DecryptedFolderMetadataFile =
EncryptionTestUtils().generateFolderMetadataV2(client.userId, EncryptionTestIT.publicKey)
setE2EECapabilityVersion(E2EVersion.fromValue(decryptedFolderMetadata1.version))
val root = OCFile("/")
storageManager.saveFile(root)
@@ -7,32 +7,15 @@
*/
package com.owncloud.android.utils
import android.os.Environment
import android.provider.MediaStore
import com.owncloud.android.AbstractIT
import com.owncloud.android.datamodel.OCFile
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import java.io.File
class FileExportUtilsIT : AbstractIT() {
@Before
fun clearExistingDownload() {
val fileName = "export.txt"
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
targetContext.contentResolver.delete(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
"${MediaStore.MediaColumns.DISPLAY_NAME} = ?",
arrayOf(fileName)
)
} else {
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName).delete()
}
}
@Test
fun exportFile() {
val file = createFile("export.txt", 10)
@@ -40,7 +23,7 @@ class FileExportUtilsIT : AbstractIT() {
val sut = FileExportUtils()
val expectedFile = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
File("/sdcard/Download/export.txt")
File("/sdcard/Downloads/export.txt")
} else {
File("/storage/emulated/0/Download/export.txt")
}
@@ -64,7 +47,7 @@ class FileExportUtilsIT : AbstractIT() {
val sut = FileExportUtils()
val expectedFile = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
File("/sdcard/Download/export.txt")
File("/sdcard/Downloads/export.txt")
} else {
File("/storage/emulated/0/Download/export.txt")
}
@@ -19,11 +19,8 @@ import com.owncloud.android.files.services.NameCollisionPolicy
import com.owncloud.android.lib.resources.status.OCCapability
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import io.mockk.spyk
import io.mockk.unmockkStatic
import io.mockk.verify
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
@@ -46,7 +43,9 @@ class FileUploadHelperTest {
val mockFileStorageManager = mockk<com.owncloud.android.datamodel.FileDataStorageManager>(relaxed = true)
every { mockFileStorageManager.getCapability(any<com.nextcloud.client.account.User>()) } returns mockCapability
fileUploadHelper.fileStorageManager = mockFileStorageManager
val field = FileUploadHelper::class.java.getDeclaredField("fileStorageManager")
field.isAccessible = true
field.set(fileUploadHelper, mockFileStorageManager)
}
@Suppress("LongParameterList")
@@ -105,25 +104,19 @@ class FileUploadHelperTest {
@Before
fun setUp() {
mockkStatic("com.nextcloud.utils.extensions.OCCapabilityExtensionsKt")
uploadDao = mockk(relaxed = true)
val uploadsStorageManager = mockk<com.owncloud.android.datamodel.UploadsStorageManager>(relaxed = true)
every { uploadsStorageManager.uploadDao } returns uploadDao
val accountManager = mockk<com.nextcloud.client.account.UserAccountManager>(relaxed = true)
fileUploadHelper = spyk(FileUploadHelper(), recordPrivateCalls = true)
fileUploadHelper.uploadsStorageManager = uploadsStorageManager
fileUploadHelper.accountManager = accountManager
val uploadsStorageManager = mockk<com.owncloud.android.datamodel.UploadsStorageManager>(relaxed = true)
toggleWCFRestrictions(false)
}
val daoField = com.owncloud.android.datamodel.UploadsStorageManager::class.java
.declaredFields
.first { it.type == UploadDao::class.java }
daoField.isAccessible = true
daoField.set(uploadsStorageManager, uploadDao)
@After
fun tearDown() {
unmockkStatic("com.nextcloud.utils.extensions.OCCapabilityExtensionsKt")
val field = FileUploadHelper::class.java.getDeclaredField("uploadsStorageManager")
field.isAccessible = true
field.set(fileUploadHelper, uploadsStorageManager)
}
@Test
@@ -0,0 +1,142 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.utils
import android.app.Activity
import android.app.Instrumentation
import android.content.Intent
import androidx.annotation.StringRes
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.test.core.app.launchActivity
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.Intents.intending
import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withText
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.nextcloud.client.onboarding.FirstRunActivity
import com.nextcloud.test.TestActivity
import com.owncloud.android.R
import com.owncloud.android.authentication.AuthenticatorActivity
import org.hamcrest.Matchers.anyOf
import org.junit.After
import org.junit.Before
import org.junit.Test
class SnackbarTests {
class NormalTestFragment : Fragment()
class DialogTestFragment : DialogFragment()
class BottomSheetTestFragment : BottomSheetDialogFragment()
@Before
fun setUp() {
Intents.init()
val cancelledResult = Instrumentation.ActivityResult(Activity.RESULT_CANCELED, Intent())
intending(
anyOf(
hasComponent(AuthenticatorActivity::class.java.name),
hasComponent(FirstRunActivity::class.java.name)
)
).respondWith(cancelledResult)
}
@After
fun tearDown() {
Intents.release()
}
private fun assertSnackbarVisible(msg: String) {
onView(withText(msg)).check(matches(isDisplayed()))
}
private fun assertSnackbarVisible(@StringRes msgRes: Int) {
onView(withText(msgRes)).check(matches(isDisplayed()))
}
private fun testFragmentSnackbar(fragment: Fragment, @StringRes msgRes: Int) {
launchActivity<TestActivity>().use { scenario ->
scenario.onActivity { sut ->
sut.addFragment(fragment)
}
scenario.onActivity {
DisplayUtils.showSnackMessage(fragment, msgRes)
}
assertSnackbarVisible(msgRes)
}
}
@Test
fun testNormalFragmentSnackbar() {
testFragmentSnackbar(NormalTestFragment(), R.string.app_name)
}
@Test
fun testDialogFragmentSnackbar() {
testFragmentSnackbar(DialogTestFragment(), R.string.app_name)
}
@Test
fun testBottomSheetFragmentSnackbar() {
testFragmentSnackbar(BottomSheetTestFragment(), R.string.app_name)
}
@Test
fun testNullFragmentSnackbarShouldNotCrash() {
DisplayUtils.showSnackMessage(null as Fragment?, R.string.app_name)
}
@Test
fun testActivityStringResSnackbar() {
launchActivity<TestActivity>().use { scenario ->
scenario.onActivity { sut ->
DisplayUtils.showSnackMessage(sut, R.string.app_name)
}
assertSnackbarVisible(R.string.app_name)
}
}
@Test
fun testActivityStringSnackbar() {
launchActivity<TestActivity>().use { scenario ->
var message = ""
scenario.onActivity { sut ->
message = sut.getString(R.string.app_name)
DisplayUtils.showSnackMessage(sut, message)
}
assertSnackbarVisible(message)
}
}
@Test
fun testViewStringResSnackbar() {
launchActivity<TestActivity>().use { scenario ->
scenario.onActivity { sut ->
val contentView = sut.findViewById<android.view.View>(android.R.id.content)
DisplayUtils.showSnackMessage(contentView, R.string.app_name)
}
assertSnackbarVisible(R.string.app_name)
}
}
@Test
fun testViewStringSnackbar() {
launchActivity<TestActivity>().use { scenario ->
var message = ""
scenario.onActivity { sut ->
message = sut.getString(R.string.app_name)
val contentView = sut.findViewById<android.view.View>(android.R.id.content)
DisplayUtils.showSnackMessage(contentView, message)
}
assertSnackbarVisible(message)
}
}
}
@@ -18,7 +18,7 @@ class CapabilityUtilsIT : AbstractIT() {
@Test
fun checkOutdatedWarning() {
assertFalse(test(NextcloudVersion.nextcloud_31))
assertTrue(test(NextcloudVersion.nextcloud_30))
assertFalse(test(NextcloudVersion.nextcloud_30))
assertTrue(test(NextcloudVersion.nextcloud_29))
assertTrue(test(NextcloudVersion.nextcloud_28))
@@ -35,7 +35,7 @@ class CapabilityUtilsIT : AbstractIT() {
@Test
fun checkOutdatedWarningWithSubscription() {
assertFalse(test(NextcloudVersion.nextcloud_31))
assertTrue(test(NextcloudVersion.nextcloud_30))
assertFalse(test(NextcloudVersion.nextcloud_30))
assertFalse(test(OwnCloudVersion.nextcloud_20, true))
}
@@ -14,7 +14,8 @@ import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.nextcloud.client.database.NextcloudDatabase
import com.nextcloud.client.jobs.download.FileDownloadWorker
import com.nextcloud.client.jobs.upload.FileUploadHelper
import com.nextcloud.client.network.ConnectivityManagerFactory
import com.nextcloud.client.network.Connectivity
import com.nextcloud.client.network.ConnectivityService
import com.nextcloud.utils.EditorUtils
import com.owncloud.android.R
import com.owncloud.android.databinding.TestLayoutBinding
@@ -41,7 +42,15 @@ class TestActivity :
private lateinit var fileOperation: FileOperationsHelper
private lateinit var binding: TestLayoutBinding
val connectivityServiceMock = ConnectivityManagerFactory.mock
val connectivityServiceMock: ConnectivityService = object : ConnectivityService {
override fun isNetworkAndServerAvailable(callback: ConnectivityService.GenericCallback<Boolean>) = Unit
override fun isConnected(): Boolean = false
override fun isInternetWalled(): Boolean = false
override fun getConnectivity(): Connectivity = Connectivity.CONNECTED_WIFI
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
-6
View File
@@ -15,12 +15,6 @@
<uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED" />
<!-- Used for document scanning, but lib declares it as required, which it's not -->
<uses-feature
android:name="android.hardware.camera2"
android:required="false"
tools:node="replace" />
<application
android:name=".MainApp"
android:icon="@mipmap/ic_launcher"
@@ -28,9 +28,6 @@ import javax.inject.Inject;
import androidx.annotation.NonNull;
import dagger.android.AndroidInjection;
/**
* Works only with gplay variant and Google Play Services installed devices.
*/
public class NCFirebaseMessagingService extends FirebaseMessagingService {
@Inject AppPreferences preferences;
@Inject UserAccountManager accountManager;
-6
View File
@@ -9,12 +9,6 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!-- Used for document scanning, but lib declares it as required, which it's not -->
<uses-feature
android:name="android.hardware.camera2"
android:required="false"
tools:node="replace" />
<application
android:name=".MainApp"
android:fullBackupContent="@xml/backup_config"
+9 -4
View File
@@ -11,9 +11,13 @@
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<!--
WRITE_EXTERNAL_STORAGE may be enabled or disabled by the user after installation in
<uses-permission android:name="android.permission.WRITE_CALENDAR" /> <!-- Used for document scanning, but lib declares it as required, which it's not -->
<uses-feature
android:name="android.hardware.camera2"
android:required="false"
tools:node="replace" />
<!--
WRITE_EXTERNAL_STORAGE may be enabled or disabled by the user after installation in
API >= 23; the app needs to handle this
-->
<uses-permission
@@ -631,7 +635,8 @@
android:exported="false"
android:label="@string/share_dialog_title"
android:launchMode="singleTop"
android:theme="@style/Theme.ownCloud.ShareDialog">
android:theme="@style/Theme.ownCloud.Dialog.NoTitle"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
-24
View File
@@ -1,24 +0,0 @@
# Nextcloud - Android Client
#
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
# SPDX-License-Identifier: AGPL-3.0-or-later
cmake_minimum_required(VERSION 3.10.2)
project(cms_verifier VERSION 1.0)
find_package(openssl REQUIRED CONFIG)
add_library(
cms_verifier
SHARED
cms_verifier.cpp
)
target_link_libraries(
cms_verifier
openssl::ssl
openssl::crypto
android
log
)
-100
View File
@@ -1,100 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#include <jni.h>
#include <android/log.h>
#include <openssl/bio.h>
#include <openssl/cms.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <cstring>
#define LOG_TAG "CmsVerifier"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
extern "C" JNIEXPORT jboolean JNICALL
Java_com_nextcloud_utils_CmsSignatureVerifier_verifySignedData(
JNIEnv* env,
jobject /* thiz */,
jbyteArray cmsDataArray,
jbyteArray messageDataArray,
jobjectArray certPemArray
) {
jsize cmsLen = env->GetArrayLength(cmsDataArray);
jbyte* cmsBytes = env->GetByteArrayElements(cmsDataArray, nullptr);
BIO* cmsBio = BIO_new_mem_buf(cmsBytes, static_cast<int>(cmsLen));
jsize msgLen = env->GetArrayLength(messageDataArray);
jbyte* msgBytes = env->GetByteArrayElements(messageDataArray, nullptr);
BIO* dataBio = BIO_new_mem_buf(msgBytes, static_cast<int>(msgLen));
CMS_ContentInfo* contentInfo = d2i_CMS_bio(cmsBio, nullptr);
BIO_free(cmsBio);
env->ReleaseByteArrayElements(cmsDataArray, cmsBytes, JNI_ABORT);
if (contentInfo == nullptr) {
LOGE("Failed to parse CMS content info");
BIO_free(dataBio);
env->ReleaseByteArrayElements(messageDataArray, msgBytes, JNI_ABORT);
return JNI_FALSE;
}
int verifyResult = CMS_verify(
contentInfo,
nullptr,
nullptr,
dataBio,
nullptr,
CMS_DETACHED | CMS_NO_SIGNER_CERT_VERIFY
);
BIO_free(dataBio);
env->ReleaseByteArrayElements(messageDataArray, msgBytes, JNI_ABORT);
if (verifyResult != 1) {
LOGE("CMS_verify failed");
CMS_ContentInfo_free(contentInfo);
return JNI_FALSE;
}
STACK_OF(CMS_SignerInfo)* signerInfos = CMS_get0_SignerInfos(contentInfo);
int numSigners = sk_CMS_SignerInfo_num(signerInfos);
jsize numCerts = env->GetArrayLength(certPemArray);
jboolean matched = JNI_FALSE;
for (jsize i = 0; i < numCerts && !matched; ++i) {
auto certPem = reinterpret_cast<jstring>(env->GetObjectArrayElement(certPemArray, i));
const char* pemChars = env->GetStringUTFChars(certPem, nullptr);
BIO* certBio = BIO_new(BIO_s_mem());
BIO_write(certBio, pemChars, static_cast<int>(strlen(pemChars)));
X509* certX509 = PEM_read_bio_X509(certBio, nullptr, nullptr, nullptr);
BIO_free(certBio);
env->ReleaseStringUTFChars(certPem, pemChars);
env->DeleteLocalRef(certPem);
if (certX509 == nullptr) {
LOGE("Failed to parse PEM certificate at index %d", i);
continue;
}
for (int j = 0; j < numSigners; ++j) {
CMS_SignerInfo* signerInfo = sk_CMS_SignerInfo_value(signerInfos, j);
if (CMS_SignerInfo_cert_cmp(signerInfo, certX509) == 0) {
matched = JNI_TRUE;
break;
}
}
X509_free(certX509);
}
CMS_ContentInfo_free(contentInfo);
return matched;
}
@@ -9,7 +9,6 @@ package com.nextcloud.client.account;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import com.owncloud.android.MainApp;
@@ -31,9 +30,6 @@ public interface UserAccountManager extends CurrentAccountProvider {
String ACCOUNT_USES_STANDARD_PASSWORD = "ACCOUNT_USES_STANDARD_PASSWORD";
String PENDING_FOR_REMOVAL = "PENDING_FOR_REMOVAL";
@Nullable
Context getContext();
@Nullable
OwnCloudAccount getCurrentOwnCloudAccount();
@@ -55,7 +55,7 @@ public class UserAccountManagerImpl implements UserAccountManager {
private static final String TAG = UserAccountManagerImpl.class.getSimpleName();
private static final String PREF_SELECT_OC_ACCOUNT = "select_oc_account";
private final Context context;
private Context context;
private final AccountManager accountManager;
public static UserAccountManagerImpl fromContext(Context context) {
@@ -305,12 +305,6 @@ public class UserAccountManagerImpl implements UserAccountManager {
return AnonymousUser.fromContext(context);
}
@Nullable
@Override
public Context getContext() {
return context;
}
@Override
@Nullable
public OwnCloudAccount getCurrentOwnCloudAccount() {
@@ -9,7 +9,6 @@
package com.nextcloud.client.assistant.chat
import android.content.ClipData
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
@@ -18,7 +17,6 @@ import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -38,8 +36,6 @@ import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
@@ -47,17 +43,11 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalClipboard
import androidx.compose.ui.platform.toClipEntry
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
@@ -70,7 +60,6 @@ import com.nextcloud.utils.TimeConstants
import com.nextcloud.utils.extensions.time
import com.owncloud.android.R
import com.owncloud.android.lib.resources.assistant.chat.model.ChatMessage
import kotlinx.coroutines.launch
import java.time.Instant
private val MIN_CHAT_HEIGHT = 60.dp
@@ -351,32 +340,6 @@ private fun TypingAnimation() {
}
}
@Composable
private fun CopyableMessageBubble(text: String, modifier: Modifier = Modifier, content: @Composable () -> Unit) {
var showMenu by remember { mutableStateOf(false) }
val clipboard = LocalClipboard.current
val scope = rememberCoroutineScope()
Box(
modifier = modifier
.combinedClickable(onClick = {}, onLongClick = { showMenu = true })
) {
content()
DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) {
DropdownMenuItem(
text = { Text(stringResource(R.string.common_copy)) },
onClick = {
scope.launch {
val plainText = ClipData.newPlainText(null, text).toClipEntry()
clipboard.setClipEntry(plainText)
}
showMenu = false
}
)
}
}
}
@Composable
private fun AssistantMessageItem(message: ChatMessage) {
Box(
@@ -400,8 +363,7 @@ private fun AssistantMessageItem(message: ChatMessage) {
alignment = Alignment.Center
)
}
CopyableMessageBubble(
text = message.content,
Box(
modifier = Modifier
.padding(start = 8.dp, end = 16.dp)
.defaultMinSize(minHeight = MIN_CHAT_HEIGHT)
@@ -428,8 +390,7 @@ private fun UserMessageItem(message: ChatMessage) {
.fillMaxWidth(),
contentAlignment = Alignment.CenterEnd
) {
CopyableMessageBubble(
text = message.content,
Box(
modifier = Modifier
.padding(start = 16.dp, end = 8.dp)
.defaultMinSize(minHeight = MIN_CHAT_HEIGHT)
Loaded 100 of 607 files, more files were not shown because too many files have changed in this diff. Show more