Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
155ddbfd25 | ||
|
|
d502bbf5ce | ||
|
|
9f30fd1c12 | ||
|
|
42aa0103e7 | ||
|
|
d68cf195cc | ||
|
|
184cf38893 | ||
|
|
1c3279e11b | ||
|
|
f9ee48286a | ||
|
|
b9fe0d16bb | ||
|
|
bf7f47ed0e | ||
|
|
540777ece5 | ||
|
|
bd9e1ff40e | ||
|
|
bb593bb65e | ||
|
|
394a7dc02b | ||
|
|
0a4e82bb3c | ||
|
|
c5b43ef115 | ||
|
|
980f5ef781 | ||
|
|
48d27f2ca9 | ||
|
|
7b62932aad | ||
|
|
aa294ec9fe | ||
|
|
7568e344bd | ||
|
|
4c4e643b76 | ||
|
|
f338e5512b | ||
|
|
4353b63a91 | ||
|
|
faf9617904 | ||
|
|
869ffa6a23 | ||
|
|
b1672c9c81 | ||
|
|
0b9c7598fa | ||
|
|
a2d8a5d4e5 | ||
|
|
216746ae6e | ||
|
|
f3bcf3040d | ||
|
|
47e46f3afa | ||
|
|
841d44ea08 | ||
|
|
c00dd78508 | ||
|
|
09b30d4126 | ||
|
|
43f57df908 | ||
|
|
87c0cd23e1 | ||
|
|
ee54ca3e47 | ||
|
|
d5f40266cc | ||
|
|
7583433c84 | ||
|
|
cd6956d249 | ||
|
|
b7853ed4b0 | ||
|
|
21982966d8 | ||
|
|
7d82fefdc9 | ||
|
|
482768aa42 | ||
|
|
c50342357a | ||
|
|
38478cc391 | ||
|
|
7771089208 | ||
|
|
7ab5ebf959 | ||
|
|
fb61bb6b17 | ||
|
|
dc21188f3f | ||
|
|
93a12027ed | ||
|
|
0d8b15c584 | ||
|
|
dc214c4c92 | ||
|
|
5f992a8f1e | ||
|
|
2bdd62a456 | ||
|
|
1b90414067 | ||
|
|
3ebda4f3b4 | ||
|
|
4ac2f0d797 | ||
|
|
b600a93d5e | ||
|
|
50adca3c5b | ||
|
|
961ff24106 | ||
|
|
8bca689e83 | ||
|
|
4da4984f3d | ||
|
|
5a968289d3 | ||
|
|
d9c4441238 | ||
|
|
ac9c9ce929 | ||
|
|
6007ae4d8f | ||
|
|
af2290e976 | ||
|
|
f42ff9e948 | ||
|
|
9214ee60a7 | ||
|
|
8d6b1c27bd | ||
|
|
d37940ccd6 | ||
|
|
8e29fc8742 | ||
|
|
f7b129a37b | ||
|
|
b49c8c86ec | ||
|
|
d638f548c3 | ||
|
|
5867b5ac79 | ||
|
|
3173216543 | ||
|
|
0fa1215209 | ||
|
|
cc26ea5a5b | ||
|
|
1d8269785e | ||
|
|
7968c4c842 | ||
|
|
bd58e2f17e | ||
|
|
d7e48d66e5 | ||
|
|
a157232cf3 | ||
|
|
6ddcd59efd | ||
|
|
b2f5ad8233 | ||
|
|
00fe5b2800 | ||
|
|
e7af075dfd | ||
|
|
d9d464c6af | ||
|
|
5a8712fa41 | ||
|
|
b76944837b | ||
|
|
273eefd0bb | ||
|
|
91dda27c89 | ||
|
|
0b3b16b62c | ||
|
|
32411824bb | ||
|
|
6854da3512 | ||
|
|
26f21f2bdd | ||
|
|
cf76d5857f | ||
|
|
72fd5b2f8a | ||
|
|
fc2030645c | ||
|
|
c7659ccf41 | ||
|
|
7f9a72463d | ||
|
|
e0a3570121 | ||
|
|
1a6d1cc7b2 | ||
|
|
768a5e85ec | ||
|
|
e2f957e154 | ||
|
|
baa093448a | ||
|
|
8127cd09c7 | ||
|
|
6529c80910 | ||
|
|
72a55aa649 | ||
|
|
3ce6ec15fa | ||
|
|
abc071d9ae | ||
|
|
2cab822119 | ||
|
|
d8eee77999 | ||
|
|
9f6af63061 | ||
|
|
2014d05ddb | ||
|
|
9667516785 | ||
|
|
0dda1e7deb | ||
|
|
68fbd5ad46 | ||
|
|
6751b40335 | ||
|
|
967ec6abf3 | ||
|
|
254bc9a161 | ||
|
|
e0310eefd4 | ||
|
|
bb430c09f3 | ||
|
|
611deecd1b | ||
|
|
505fd86d0a | ||
|
|
e3d7309775 | ||
|
|
c4754aba1a | ||
|
|
669b597d9d | ||
|
|
d28f26a31c | ||
|
|
a0f21d1758 | ||
|
|
6a1788ffb0 | ||
|
|
d9dac6830e | ||
|
|
651a0ff71a | ||
|
|
c3f6f86b7c | ||
|
|
fa0044b06d | ||
|
|
93917f8bbf | ||
|
|
e069c25d32 | ||
|
|
1893cbfd2a | ||
|
|
de054206b4 | ||
|
|
123788d359 | ||
|
|
8684364a18 | ||
|
|
d525436057 | ||
|
|
1ba9017c3c | ||
|
|
032606d86f | ||
|
|
7f6440faca | ||
|
|
e6cd4cab42 | ||
|
|
cc8cc2fb6b | ||
|
|
6ad9ed4c66 | ||
|
|
01d96f773f | ||
|
|
3567d1e191 | ||
|
|
75ba75ef28 | ||
|
|
4d76004c34 | ||
|
|
c340d1f82f | ||
|
|
f8b6b59bc7 | ||
|
|
b4a90c02b9 | ||
|
|
235f099bee | ||
|
|
272673eedd | ||
|
|
915250cbd5 | ||
|
|
6703774102 | ||
|
|
19ee2b7b10 | ||
|
|
6fea58356f | ||
|
|
a52f0c144c | ||
|
|
2234a80b95 | ||
|
|
b30092d225 | ||
|
|
d05b8a0e4c | ||
|
|
718ef0a3aa | ||
|
|
aeb789c098 | ||
|
|
bc288cdbf6 | ||
|
|
cb6383bb20 | ||
|
|
3eeb8d0b9f | ||
|
|
101eb27d4a | ||
|
|
9de4faa4d6 | ||
|
|
a366842996 | ||
|
|
2f2e98329b | ||
|
|
27f51026ee | ||
|
|
b32e8e7dac | ||
|
|
cea7d7f2d6 | ||
|
|
182c63dcfc | ||
|
|
c0736d8bcc | ||
|
|
9f84fd42b5 | ||
|
|
cf67ba022e | ||
|
|
80630cb8fa | ||
|
|
6ad82521be | ||
|
|
9168fc498d | ||
|
|
3add9520ad | ||
|
|
d94bf597b1 | ||
|
|
694286a41e | ||
|
|
e1b905018c | ||
|
|
ae9b60e750 | ||
|
|
b6f4c0e9fd | ||
|
|
28c5d85ea0 | ||
|
|
2c1ac993db | ||
|
|
d3127ecf97 | ||
|
|
723a79e426 | ||
|
|
fa8d9446c1 | ||
|
|
a2d3014e71 | ||
|
|
fc53dcd052 | ||
|
|
c33b076f42 | ||
|
|
903eb1ea78 | ||
|
|
7124eabe17 | ||
|
|
4b83071390 | ||
|
|
09206cd8b6 | ||
|
|
ea4be8d4a7 | ||
|
|
b873487b66 | ||
|
|
2b63aedddf | ||
|
|
0c46437294 | ||
|
|
61cd561cb1 | ||
|
|
c512b0507c | ||
|
|
3c0ef18505 | ||
|
|
5cbc4fab9b | ||
|
|
0c49ab7239 | ||
|
|
945f1f7556 | ||
|
|
813bab13ba | ||
|
|
f2af31ec7e | ||
|
|
5bfe6ce671 | ||
|
|
8fec657ed8 | ||
|
|
c83905f48b | ||
|
|
8104883d62 | ||
|
|
68e28f4d32 | ||
|
|
1a60516706 | ||
|
|
11f5ee22cf | ||
|
|
e270ba89db | ||
|
|
95b54c4a93 | ||
|
|
2c118c7b7a | ||
|
|
204f9e23b1 | ||
|
|
be77b87304 | ||
|
|
535993571b | ||
|
|
07841f297a | ||
|
|
65143c3e51 | ||
|
|
1995d9e425 | ||
|
|
d98ed21691 | ||
|
|
bbff6d2b6a | ||
|
|
eeb5692d4f | ||
|
|
542ce2e641 | ||
|
|
0f24168711 | ||
|
|
42a4bc290a | ||
|
|
43bbc46bd7 | ||
|
|
4c05872f2f | ||
|
|
f48455af66 | ||
|
|
38fdc7a99e | ||
|
|
abaf4975f8 | ||
|
|
2f2fc1015a | ||
|
|
f2437c35e5 | ||
|
|
c830f06212 | ||
|
|
e377d52077 | ||
|
|
8121c9e6e6 | ||
|
|
e22b4a41d0 | ||
|
|
3b5e2b90e0 | ||
|
|
c1f26f28d2 | ||
|
|
9d07282403 | ||
|
|
704cc79cc3 | ||
|
|
b7f8234832 | ||
|
|
5d423fcdab | ||
|
|
ce29f3d227 | ||
|
|
9a3f72871f | ||
|
|
6f0315759e | ||
|
|
1fc7bf16da | ||
|
|
831f1b4842 | ||
|
|
9131291bdb | ||
|
|
703f6238c8 | ||
|
|
0d5f7fe6ad | ||
|
|
278319c39d | ||
|
|
5028977cc8 | ||
|
|
b2974669b0 | ||
|
|
3a997b480e | ||
|
|
5cc53050ea | ||
|
|
16bbdca67e | ||
|
|
045429fd38 | ||
|
|
d48b8418fc | ||
|
|
7aa5ac583f | ||
|
|
b4332c7cc7 | ||
|
|
c85e7a63dc | ||
|
|
82634b52d6 | ||
|
|
f0a250beeb | ||
|
|
d307ab5b2a | ||
|
|
ec55b04c5a | ||
|
|
be88ad96e1 | ||
|
|
4c4be4f57e | ||
|
|
2f8f20297f | ||
|
|
0ddc684537 | ||
|
|
dc9db57529 | ||
|
|
a7fa2a3097 | ||
|
|
5da3a1c527 | ||
|
|
c7bdc4d4aa | ||
|
|
caff81156d | ||
|
|
12c76849b8 | ||
|
|
eb2711a569 | ||
|
|
d34c02a5f4 | ||
|
|
2e47a09845 | ||
|
|
933b7ec44c | ||
|
|
f92fd7e521 | ||
|
|
fe710979d9 | ||
|
|
12e0e52d7b | ||
|
|
a05730a547 | ||
|
|
bd6f12cfad | ||
|
|
63172442b5 | ||
|
|
f384e2961a | ||
|
|
2b7e64a861 | ||
|
|
e8e2b43af0 | ||
|
|
5342b2f871 | ||
|
|
4d544a59a3 | ||
|
|
fa7ca6b719 | ||
|
|
653c5b97e5 | ||
|
|
d17d2d2a3e | ||
|
|
5e0f19171b | ||
|
|
ecf0fd92ad | ||
|
|
8c665a4fbd | ||
|
|
0a82d58279 | ||
|
|
309f2c511d | ||
|
|
641b82cbc2 | ||
|
|
0798a10d66 | ||
|
|
159dd3b074 | ||
|
|
5013aa0587 | ||
|
|
1e74f7a8b1 | ||
|
|
be8621ca27 | ||
|
|
271999ec08 | ||
|
|
7e53fffff2 | ||
|
|
a44c07004e | ||
|
|
c009702ced | ||
|
|
abeaa0bea2 | ||
|
|
aaae403c46 | ||
|
|
07e68c0cb4 | ||
|
|
9246e70820 | ||
|
|
9ca02722ef | ||
|
|
be626864b1 | ||
|
|
1a42c12abc | ||
|
|
26d517e0cb | ||
|
|
96676a00cb | ||
|
|
ab96482dca | ||
|
|
b159dd9aff | ||
|
|
8bf4f70481 | ||
|
|
e7aac49d4b | ||
|
|
963ba65aaa | ||
|
|
7bcd4d2e8c | ||
|
|
d53569bea3 | ||
|
|
0933747068 | ||
|
|
9304f1b1f4 | ||
|
|
e770287f8a | ||
|
|
892fe1de6d | ||
|
|
ca4cc0a308 | ||
|
|
4b35496fcf | ||
|
|
7955f412e1 | ||
|
|
303a431118 | ||
|
|
7fe29ea822 | ||
|
|
3e54ebbcb0 | ||
|
|
821f1b6c5a | ||
|
|
b93034677e | ||
|
|
b58cc428cf | ||
|
|
28b35ed556 | ||
|
|
1a958730df | ||
|
|
53682a6d81 | ||
|
|
ec5bf46318 | ||
|
|
f2c3986498 | ||
|
|
00c3dc0ab7 | ||
|
|
6f36ce7737 | ||
|
|
4a040f9e03 | ||
|
|
fdd93ca520 | ||
|
|
e99bb65703 | ||
|
|
774be28b22 | ||
|
|
f1a1481351 | ||
|
|
53e0adea34 | ||
|
|
4dafa55cb6 | ||
|
|
4d55f77f5e | ||
|
|
2af165bed1 | ||
|
|
198a2f0b32 | ||
|
|
0800900271 | ||
|
|
e7477225c1 | ||
|
|
96337feb27 | ||
|
|
fc2642a432 | ||
|
|
f4aec3c690 | ||
|
|
c71874eb30 | ||
|
|
73cb67a763 | ||
|
|
e9103a1b3b | ||
|
|
c31f400a49 | ||
|
|
6bc597dbbf | ||
|
|
ba55ce8e4e | ||
|
|
0cce33aedd | ||
|
|
857a75d4af | ||
|
|
d1df066ff3 | ||
|
|
641ef49407 | ||
|
|
3fe3a8d143 | ||
|
|
fb01b1e74b | ||
|
|
dba02f5db9 | ||
|
|
0f98682f46 | ||
|
|
19c1c03c2c | ||
|
|
91dd8753af | ||
|
|
78cb027065 | ||
|
|
2b30f0bbd6 | ||
|
|
bde1361e0d | ||
|
|
fea04392ef | ||
|
|
416dda67b0 | ||
|
|
2dc375c71c | ||
|
|
5c715fe263 | ||
|
|
c03755b672 | ||
|
|
47d168dc9a | ||
|
|
5079c17d56 | ||
|
|
94638b6e4a | ||
|
|
6ad9fb0655 | ||
|
|
ac069c0002 | ||
|
|
22dea5430a | ||
|
|
e9358fba93 | ||
|
|
913084ac91 | ||
|
|
3b3fb17f18 | ||
|
|
9c64a7e976 | ||
|
|
da5da2713c | ||
|
|
8c0689bfa9 | ||
|
|
a751848f7e | ||
|
|
1b043dca33 | ||
|
|
eeac608cfc | ||
|
|
105667b1b2 | ||
|
|
86157201af | ||
|
|
1f1ba2efc5 | ||
|
|
647525919b | ||
|
|
48c8db13dc | ||
|
|
fa73f5d521 | ||
|
|
dbeda64e38 | ||
|
|
390d898806 | ||
|
|
fef419abac | ||
|
|
03caa6211f | ||
|
|
cb7e4b95dc | ||
|
|
bcac98a989 | ||
|
|
1407ecec9e | ||
|
|
7b7f1d6650 | ||
|
|
397f4f73da | ||
|
|
9e1a450e20 | ||
|
|
d1c8ab07ea | ||
|
|
0a5c5a234c | ||
|
|
abf4353d0c | ||
|
|
274954334e | ||
|
|
5f298c5c13 | ||
|
|
ccbbe2257e | ||
|
|
03e5f5f516 | ||
|
|
5213ea092e | ||
|
|
e3147733dd | ||
|
|
18e8fac47f |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
# Default owner for all files in the repository.
|
||||
* @marinofaggiana @mpivchev
|
||||
@@ -0,0 +1,42 @@
|
||||
# SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
# SPDX-FileCopyrightText: 2026 Milen Pivchev
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
# SPM packages declared in Nextcloud.xcodeproj (NextcloudKit, Realm, Firebase, …)
|
||||
- package-ecosystem: "swift"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
groups:
|
||||
swift-packages:
|
||||
patterns:
|
||||
- "*"
|
||||
# These deps are ignored, since they are internal Firebase and Realm libs.
|
||||
# They have their own version limits that may not be the latest version, which forces XCode to reverse a version change.
|
||||
# Since these are ignored, the only way they update is through an Xcode package build, which will happen naturally.
|
||||
ignore:
|
||||
- dependency-name: "github.com/google/*"
|
||||
- dependency-name: "github.com/googleads/*"
|
||||
- dependency-name: "github.com/firebase/nanopb"
|
||||
- dependency-name: "github.com/firebase/leveldb"
|
||||
- dependency-name: "github.com/realm/realm-core"
|
||||
labels:
|
||||
- "dependencies"
|
||||
commit-message:
|
||||
prefix: "fix(deps)"
|
||||
|
||||
# Keep the GitHub Actions used by our workflows up to date
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
groups:
|
||||
github-actions:
|
||||
patterns:
|
||||
- "*"
|
||||
labels:
|
||||
- "dependencies"
|
||||
commit-message:
|
||||
prefix: "ci"
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
# SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
# SPDX-FileCopyrightText: 2026 Milen Pivchev
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
name: github-actions-failure-debugging
|
||||
description: Debug and fix failing GitHub Actions workflows (CI) in this repo — failing PR checks, xcodebuild/simulator/runner-image errors, SwiftLint failures. Use when asked to review, debug, or fix CI or a failing workflow run.
|
||||
---
|
||||
|
||||
# Debugging failing GitHub Actions workflows
|
||||
|
||||
Workflows live in `.github/workflows/`:
|
||||
|
||||
- `xcode.yml` — builds the `Nextcloud` scheme for testing, then runs tests on a simulator against a locally installed Nextcloud server. Version pins are env vars at the top: `XCODE_VERSION`, `DESTINATION`, plus the `runs-on` labels and the `simctl boot` device name further down.
|
||||
- `additional-targets.yml` — builds the extension schemes (Share, File Provider, Notification Service, Widget, WidgetDashboardIntentHandler). Keep its image/Xcode/destination consistent with `xcode.yml`.
|
||||
- `lint.yml` — SwiftLint on ubuntu.
|
||||
|
||||
## 1. Get the failure
|
||||
|
||||
Use the `gh` CLI (if a GitHub MCP server is connected, its equivalents like `list_workflow_runs` / `get_job_logs` work too):
|
||||
|
||||
- `gh pr checks <pr>` or `gh run list --branch <branch> --limit 10` — find failing runs
|
||||
- `gh run view <run-id>` — see which jobs and steps failed
|
||||
- `gh run view <run-id> --log-failed | grep -iE "error:|failed" | head -60` — never dump full logs into context; grep/tail them, or have a subagent read them and report only the failing step and error lines.
|
||||
|
||||
## 2. Classify before fixing
|
||||
|
||||
- `cannot find type '…' in scope` for Apple APIs → SDK mismatch: the code uses APIs newer than the SDK of the Xcode selected on the runner. Confirm the API's introduction version by grepping the local SDK, e.g.
|
||||
`grep -rn -B4 "TypeName" /Applications/Xcode-*.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/System/Library/Frameworks/<Framework>.framework/Modules/*.swiftmodule/*.swiftinterface`
|
||||
and look for `@available(iOS X.0, …)`.
|
||||
- "Unable to find a destination" or simulator boot errors → the pinned `DESTINATION` OS/device or the `simctl boot` device name doesn't exist on the runner image.
|
||||
- Job queued forever or tooling missing → invalid or stale `runs-on` label.
|
||||
- Test-job failures around PHP/occ → the Nextcloud server setup steps; these shell steps can be reproduced locally.
|
||||
- SwiftLint failures → run `swiftlint` locally.
|
||||
|
||||
## 3. Check runner-image compatibility
|
||||
|
||||
Before changing any pin, check https://github.com/actions/runner-images:
|
||||
|
||||
- The README's Available Images table has the valid `runs-on` labels, including preview images (e.g. `xcode-27`) and deprecation notices.
|
||||
- Each macOS image readme (`images/macos/<image>-arm64-Readme.md`) lists installed Xcode versions, iOS simulator runtimes, and device types.
|
||||
|
||||
The chosen combination must exist together on one image: `runs-on` label ↔ `XCODE_VERSION` ↔ `DESTINATION` OS + device ↔ `simctl boot` device name. New Xcode majors appear first on a dedicated preview image before reaching the GA `macos-NN` image.
|
||||
|
||||
## 4. Reproduce and fix
|
||||
|
||||
- Do **not** run `xcodebuild` locally to reproduce — builds take too long (repo rule). Reproduce only cheap failures (SwiftLint, YAML, shell steps); for compile/SDK failures, reason from the logs plus the SDK check above.
|
||||
- Apply the fix to every workflow sharing the stale value.
|
||||
- Validate edited YAML: `ruby -ryaml -e 'YAML.load_file(".github/workflows/xcode.yml")'`
|
||||
- If you reproduced a failure locally, verify the fix locally before committing. Otherwise say plainly that verification needs a CI run; after pushing, watch it with `gh pr checks --watch` or `gh run watch`.
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
name: Build additional targets
|
||||
|
||||
on:
|
||||
@@ -18,17 +21,20 @@ concurrency:
|
||||
jobs:
|
||||
build-and-test:
|
||||
name: Build and Test
|
||||
runs-on: macos-14
|
||||
runs-on: xcode-27
|
||||
if: github.event.pull_request.draft == false
|
||||
env:
|
||||
PROJECT: Nextcloud.xcodeproj
|
||||
DESTINATION: platform=iOS Simulator,name=iPhone 15
|
||||
DESTINATION: platform=iOS Simulator,name=iPhone 17,OS=27.0
|
||||
XCODE_VERSION: '27.1'
|
||||
steps:
|
||||
- name: Set env var
|
||||
run: echo "DEVELOPER_DIR=$(xcode-select --print-path)" >> $GITHUB_ENV
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v7
|
||||
- name: Download GoogleService-Info.plist
|
||||
run: wget "https://raw.githubusercontent.com/firebase/quickstart-ios/master/mock-GoogleService-Info.plist" -O GoogleService-Info.plist
|
||||
- name: Setup Xcode
|
||||
uses: maxim-lobanov/setup-xcode@ed7a3b1fda3918c0306d1b724322adc0b8cc0a90 # v1.7.0
|
||||
with:
|
||||
xcode-version: ${{ env.XCODE_VERSION }}
|
||||
- name: Build iOS Share
|
||||
run: |
|
||||
xcodebuild build -project $PROJECT -scheme "$SCHEME" -destination "$DESTINATION" | xcbeautify --quieter
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
|
||||
# Lints the project using SwiftLint
|
||||
|
||||
@@ -24,7 +27,7 @@ jobs:
|
||||
if: github.event.pull_request.draft == false
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: GitHub Action for SwiftLint
|
||||
uses: norio-nomura/[email protected]
|
||||
@@ -0,0 +1,27 @@
|
||||
# This workflow is provided via the organization template repository
|
||||
#
|
||||
# https://github.com/nextcloud/.github
|
||||
# https://docs.github.com/en/actions/learn-github-actions/sharing-workflows-with-your-organization
|
||||
|
||||
# SPDX-FileCopyrightText: 2022 Free Software Foundation Europe e.V. <https://fsfe.org>
|
||||
#
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
name: REUSE Compliance Check
|
||||
|
||||
on: [pull_request]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
reuse-compliance-check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: REUSE Compliance Check
|
||||
uses: fsfe/reuse-action@676e2d560c9a403aa252096d99fcab3e1132b0f5 # v6.0.0
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
name: Build and test main target
|
||||
|
||||
on:
|
||||
@@ -17,26 +20,26 @@ on:
|
||||
|
||||
env:
|
||||
PROJECT: Nextcloud.xcodeproj
|
||||
DESTINATION: platform=iOS Simulator,name=iPhone 16,OS=18.5
|
||||
DESTINATION: platform=iOS Simulator,name=iPhone 17,OS=27.0
|
||||
SCHEME: Nextcloud
|
||||
XCODE_VERSION: '26.0.1'
|
||||
XCODE_VERSION: '27.1'
|
||||
SERVER_BRANCH: stable30
|
||||
PHP_VERSION: 8.3
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: macos-15
|
||||
runs-on: xcode-27
|
||||
if: github.event.pull_request.draft == false
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Download GoogleService-Info.plist
|
||||
run: wget "https://raw.githubusercontent.com/firebase/quickstart-ios/master/mock-GoogleService-Info.plist" -O GoogleService-Info.plist
|
||||
|
||||
- name: Setup Xcode
|
||||
uses: maxim-lobanov/setup-xcode@60606e260d2fc5762a71e64e74b2174e8ea3c8bd # v1.6.0
|
||||
uses: maxim-lobanov/setup-xcode@ed7a3b1fda3918c0306d1b724322adc0b8cc0a90 # v1.7.0
|
||||
with:
|
||||
xcode-version: ${{ env.XCODE_VERSION }}
|
||||
|
||||
@@ -50,7 +53,7 @@ jobs:
|
||||
| xcbeautify --quieter
|
||||
|
||||
- name: Upload Build Products
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: Nextcloud for iOS
|
||||
path: DerivedData/Build/Products
|
||||
@@ -58,16 +61,53 @@ jobs:
|
||||
|
||||
test:
|
||||
name: Run Tests
|
||||
runs-on: macos-15
|
||||
runs-on: xcode-27
|
||||
timeout-minutes: 40
|
||||
needs: [build]
|
||||
|
||||
if: github.event.pull_request.draft == false
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Detect passcode changes
|
||||
id: passcode_changes
|
||||
shell: bash
|
||||
env:
|
||||
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
PUSH_BEFORE_SHA: ${{ github.event.before }}
|
||||
run: |
|
||||
run_passcode_tests=false
|
||||
if [ "$GITHUB_EVENT_NAME" = "pull_request" ]; then
|
||||
compare_base=$(git merge-base "$PR_BASE_SHA" "$PR_HEAD_SHA")
|
||||
compare_head="$PR_HEAD_SHA"
|
||||
else
|
||||
compare_base="$PUSH_BEFORE_SHA"
|
||||
compare_head="$GITHUB_SHA"
|
||||
fi
|
||||
|
||||
if [ -z "$compare_base" ] || [ "$compare_base" = "0000000000000000000000000000000000000000" ]; then
|
||||
run_passcode_tests=true
|
||||
else
|
||||
git diff --name-only -z "$compare_base" "$compare_head" > "$RUNNER_TEMP/passcode-changed-files"
|
||||
while IFS= read -r -d '' changed_file; do
|
||||
case "$changed_file" in
|
||||
iOSClient/Utility/Passcode/* | \
|
||||
Tests/NextcloudUITests/PasscodeUITests.swift)
|
||||
run_passcode_tests=true
|
||||
break
|
||||
;;
|
||||
esac
|
||||
done < "$RUNNER_TEMP/passcode-changed-files"
|
||||
fi
|
||||
echo "run=$run_passcode_tests" >> "$GITHUB_OUTPUT"
|
||||
echo "Run passcode UI tests: $run_passcode_tests"
|
||||
|
||||
- name: Setup Xcode
|
||||
uses: maxim-lobanov/setup-xcode@60606e260d2fc5762a71e64e74b2174e8ea3c8bd # v1.6.0
|
||||
uses: maxim-lobanov/setup-xcode@ed7a3b1fda3918c0306d1b724322adc0b8cc0a90 # v1.7.0
|
||||
with:
|
||||
xcode-version: ${{ env.XCODE_VERSION }}
|
||||
|
||||
@@ -82,7 +122,7 @@ jobs:
|
||||
ini-values: apc.enable_cli=on, disable_functions=
|
||||
|
||||
- name: Checkout Nextcloud Server
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: true
|
||||
repository: nextcloud/server
|
||||
@@ -90,7 +130,7 @@ jobs:
|
||||
ref: ${{ env.SERVER_BRANCH }}
|
||||
|
||||
- name: Checkout Download Limits App
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
repository: nextcloud/files_downloadlimit
|
||||
path: server/apps/files_downloadlimit
|
||||
@@ -100,27 +140,31 @@ jobs:
|
||||
run: |
|
||||
mkdir server/data
|
||||
./server/occ maintenance:install --verbose --database=sqlite --database-name=nextcloud --database-host=127.0.0.1 --database-user=root --database-pass=rootpassword --admin-user admin --admin-pass admin
|
||||
./server/occ config:system:set force_language --value=en
|
||||
./server/occ config:system:set hashing_default_password --value=true --type=boolean
|
||||
./server/occ config:system:set auth.bruteforce.protection.enabled --value false --type bool
|
||||
./server/occ config:system:set ratelimit.protection.enabled --value false --type bool
|
||||
./server/occ config:system:set memcache.local --value="\\OC\\Memcache\\APCu"
|
||||
./server/occ config:system:set memcache.distributed --value="\\OC\\Memcache\\APCu"
|
||||
./server/occ app:enable files_downloadlimit
|
||||
./server/occ background:cron
|
||||
PHP_CLI_SERVER_WORKERS=5 php -S localhost:8080 -t server/ &
|
||||
|
||||
- name: Download Build
|
||||
uses: actions/download-artifact@v4
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: Nextcloud for iOS
|
||||
|
||||
- name: Assert Nextcloud Server Status
|
||||
run: curl -s --retry 5 --retry-delay 60 --retry-all-errors http://localhost:8080/status.php || true
|
||||
run: curl --fail --show-error --silent --max-time 5 --retry 5 --retry-delay 2 --retry-max-time 30 --retry-all-errors http://localhost:8080/status.php
|
||||
|
||||
- name: Boot iOS Simulator
|
||||
run: |
|
||||
xcrun simctl boot "iPhone 16"
|
||||
xcrun simctl bootstatus "iPhone 16" || echo "Simulator booted"
|
||||
xcrun simctl boot "iPhone 17"
|
||||
xcrun simctl bootstatus "iPhone 17" -b
|
||||
xcrun simctl spawn "iPhone 17" defaults write NSGlobalDomain AppleLanguages -array en
|
||||
xcrun simctl spawn "iPhone 17" defaults write NSGlobalDomain AppleLocale -string en_US
|
||||
xcrun simctl shutdown "iPhone 17"
|
||||
xcrun simctl boot "iPhone 17"
|
||||
xcrun simctl bootstatus "iPhone 17" -b
|
||||
|
||||
- name: Check if Safari is installed
|
||||
run: |
|
||||
@@ -132,19 +176,31 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Run Xcode Test
|
||||
timeout-minutes: 25
|
||||
shell: bash
|
||||
env:
|
||||
RUN_PASSCODE_TESTS: ${{ steps.passcode_changes.outputs.run }}
|
||||
run: |
|
||||
set -o pipefail && \
|
||||
set -o pipefail
|
||||
test_selection=()
|
||||
if [ "$RUN_PASSCODE_TESTS" != "true" ]; then
|
||||
test_selection+=(-skip-testing:NextcloudUITests/PasscodeUITests)
|
||||
fi
|
||||
xcodebuild test-without-building \
|
||||
-xctestrun $(find . -type f -name "*.xctestrun") \
|
||||
-destination "${{ env.DESTINATION }}" \
|
||||
-derivedDataPath "DerivedData" \
|
||||
"${test_selection[@]}" \
|
||||
-test-iterations 3 \
|
||||
-retry-tests-on-failure \
|
||||
-test-timeouts-enabled YES \
|
||||
-default-test-execution-time-allowance 600 \
|
||||
-maximum-test-execution-time-allowance 600 \
|
||||
-resultBundlePath "TestResult.xcresult"
|
||||
|
||||
- name: Upload Xcode Test Results
|
||||
uses: actions/upload-artifact@v4
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@v7
|
||||
if: ${{ always() }}
|
||||
with:
|
||||
name: TestResult.xcresult
|
||||
path: "TestResult.xcresult"
|
||||
@@ -35,12 +35,9 @@ DerivedData
|
||||
*.hmap
|
||||
*.xccheckout
|
||||
|
||||
## Package
|
||||
Carthage/
|
||||
|
||||
### SwiftPackageManager ###
|
||||
.swiftpm
|
||||
Package.resolved
|
||||
# Don't ignore Package.resolved: Dependabot needs it committed to update Xcode packages.
|
||||
|
||||
*.generated.swift
|
||||
/.env-vars
|
||||
## Claude Code
|
||||
.claude/
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
opt_in_rules: # some rules are turned off by default, so you need to opt-in
|
||||
- empty_collection_literal
|
||||
- empty_string
|
||||
@@ -10,7 +13,7 @@ line_length:
|
||||
error: 5000
|
||||
|
||||
function_body_length:
|
||||
warning: 400
|
||||
warning: 500
|
||||
|
||||
type_body_length:
|
||||
warning: 2000
|
||||
@@ -45,7 +48,7 @@ excluded:
|
||||
- Tests
|
||||
- Brand/NCBrand.swift
|
||||
- iOSClient/NCGlobal.swift
|
||||
- iOSClient/Utility/NCLivePhoto.swift
|
||||
- DerivedData
|
||||
- .claude
|
||||
|
||||
reporter: "xcode"
|
||||
@@ -1,14 +1,13 @@
|
||||
<!--
|
||||
- SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
- SPDX-License-Identifier: GPL-2.0-or-later
|
||||
- SPDX-License-Identifier: GPL-3.0-or-later
|
||||
-->
|
||||
|
||||
# AGENTS.md
|
||||
|
||||
You are an experienced engineer specialized in Swift and familiar with the platform-specific details of iOS.
|
||||
|
||||
## Your Role
|
||||
|
||||
- You are an experienced engineer specialized in Swift and familiar with the platform-specific details of iOS.
|
||||
- You implement features and fix bugs.
|
||||
- Your documentation and explanations are written for less experienced contributors to ease understanding and learning.
|
||||
- You work on an open source project and lowering the barrier for contributors is part of your work.
|
||||
@@ -17,43 +16,56 @@ You are an experienced engineer specialized in Swift and familiar with the platf
|
||||
|
||||
The Nextcloud iOS Client is a tool to access and synchronize files from Nextcloud Server on your iPhone or iPad.
|
||||
Swift, UIKit and SwiftUI are the key technologies used for building the app on iOS.
|
||||
Beyond that, there is shared code in the form of the NextcloudKit library for use in macOS and iOS.
|
||||
Server communication is handled by the NextcloudKit library — a separate repository (https://github.com/nextcloud/NextcloudKit) consumed as a Swift Package pinned to an exact version in `Nextcloud.xcodeproj`. Prefer its APIs over hand-rolled networking code; server API changes belong in that repo.
|
||||
Other key dependencies (all Swift Packages): Realm (local database), Alamofire (HTTP), Firebase (crash reporting), OpenSSL (end-to-end encryption), VLCKit (media playback). Prefer existing dependencies over adding new ones.
|
||||
Other platforms like Android are irrelevant for this project.
|
||||
|
||||
## Project Structure: AI Agent Handling Guidelines
|
||||
|
||||
| Directory | Description | Agent Action |
|
||||
|-----------------|-----------------------------------------------------|----------------------|
|
||||
| `.github` | GitHub CI workflows. | Try to add unit tests for new features, where applicable and makes sense. Do not overcomplicate unit tests. |
|
||||
| `.github` | GitHub CI workflows (build & test, SwiftLint, extension-target builds) and issue templates. | Keep all three checks green: `xcode.yml` (builds the `Nextcloud` scheme and runs its tests against a Nextcloud server provisioned in CI), `lint.yml` (SwiftLint), `additional-targets.yml` (build-checks the extension schemes). CI skips draft PRs. |
|
||||
| `iOSClient` | Main iOS client source code. | — |
|
||||
| `iOSClient/SupportingFiles` | Translation files from Transifex. | Only add new strings in `en.lproj`. The rest you should ignore. |
|
||||
| `iOSClient/Utility/Passcode` | Shared SwiftUI passcode UI and authentication model for the app and Share Extension; the mandatory app lock uses a dedicated window per scene. | Preserve existing credentials, lockout rules and app/extension reset behavior. |
|
||||
| `iOSClient/Supporting Files` | Translation files synced with Transifex (see `iOSClient/.tx/config`). | Only add new strings to `en.lproj` (`Localizable.strings`, plurals in `Localizable.stringsdict`); never edit the other `*.lproj` dirs — Transifex overwrites them. |
|
||||
| `Brand` | Branding layer: `NCBrand.swift` (app constants, colors), `Database.swift` (Realm database name and schema version), Info.plists and entitlements for all targets, launch screen and intro screens. | Bump `databaseSchemaVersion` in `Brand/Database.swift` when changing Realm models. |
|
||||
| `File Provider Extension` | Contains business logic for the iOS File Provider extension. | — |
|
||||
| `File Provider Extension UI` | Contains UI logic for the iOS File Provider extension. | — |
|
||||
| `Share` | Contains code for the iOS Share extension. | — |
|
||||
| `Widget` | Contains code for iOS Widgets. | — |
|
||||
| `WidgetDashboardIntentHandler` | Contains the intent handler for the dashboard widget. | — |
|
||||
| `Notification Service Extension` | Contains the push notification service extension. | — |
|
||||
| `Tests` | Contains unit and UI tests. | — |
|
||||
| `Action Assistant` | iOS Action extension that receives shared text from other apps and forwards it to the in-app Nextcloud Assistant. | — |
|
||||
| `AppIcon.icon` | Icon Composer app-icon bundle. | Do not edit by hand; use Icon Composer. |
|
||||
| `Tests` | Unit tests (`NextcloudUnitTests`), UI tests (`NextcloudUITests`) and integration tests (`NextcloudIntegrationTests`), plus `TestConstants.swift` and the `Server.sh` test-server script. | Prefer `NextcloudUnitTests` for new tests. Try to add unit tests for new features, where applicable and makes sense; do not overcomplicate them. |
|
||||
|
||||
Keep this table up to date: when a change adds, removes or repurposes a directory listed here, update the table in the same PR.
|
||||
|
||||
## General Guidance
|
||||
|
||||
Every new file needs to get a SPDX header in the first rows according to this template.
|
||||
The year in the first line must be replaced with the year when the file is created (for example, 2026 for files first added in 2026).
|
||||
The project is licensed under GPL-3.0-or-later (`LICENSE.txt`) with an Apple App Store exception (`COPYING.iOS`).
|
||||
|
||||
Every new file needs to get a SPDX header in the first rows according to this template.
|
||||
Replace `<YEAR>` with the year the file is created and `<Author Name>` with the contributing author (Nextcloud has no CLA; copyright stays with the individual contributors).
|
||||
The commenting signs need to be used depending on the file type.
|
||||
|
||||
```plaintext
|
||||
SPDX-FileCopyrightText: <YEAR> Nextcloud GmbH and Nextcloud contributors
|
||||
SPDX-License-Identifier: GPL-2.0-or-later
|
||||
SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
SPDX-FileCopyrightText: <YEAR> <Author Name>
|
||||
SPDX-License-Identifier: GPL-3.0-or-later
|
||||
```
|
||||
|
||||
Some older files still carry legacy “Created by … All rights reserved” Xcode headers — do not copy that style into new files. The `REUSE Compliance Check` workflow enforces this on every pull request; files that cannot carry a comment (assets, translations, project files) are covered by `REUSE.toml` instead.
|
||||
|
||||
Avoid creating source files that implement multiple types; instead, place each type in its own dedicated source file.
|
||||
|
||||
## Commit and Pull Request Guidelines
|
||||
|
||||
- **DCO sign-off (required)**: All commits must comply with the Developer Certificate of Origin (DCO) as described in `README.md` and include a `Signed-off-by: …` line in the commit message.
|
||||
- **DCO sign-off (required)**: All commits must comply with the Developer Certificate of Origin (DCO) as described in `README.md` and include a `Signed-off-by: …` line in the commit message. Sign off with `git commit -s`; the DCO status check blocks PRs otherwise.
|
||||
- **Commits**: In addition to the DCO sign-off, follow the Conventional Commits format for the subject line where reasonable. Use `feat: ...`, `fix: ...`, or `refactor: ...` as appropriate in the commit message prefix.
|
||||
- Include a short summary of what changed. *Example:* `fix: prevent crash on empty todo title`.
|
||||
- **Pull Request**: When the agent creates a PR, it should include a description summarizing the changes and why they were made. If a GitHub issue exists, reference it (e.g., “Closes #123”). If there is any discrepancy between this section and the contribution guidance in `README.md`, the rules in `README.md` take precedence.
|
||||
- Include a short summary of what changed. *Example:* `fix: prevent crash on empty file name`.
|
||||
- **Pull Request**: When the agent creates a PR, it should include a description summarizing the changes and why they were made. If a GitHub issue exists, reference it (e.g., “Closes #123”). Target `master` (the default branch); `stable-XX.Y.Z` branches are only for backports. Note that `README.md` still mentions a `develop` branch — it no longer exists.
|
||||
- **AI-assisted changes**: Declare AI tool use in the PR description (the org-level PR template includes an AI checkbox) and add an `Assisted-by: AGENT_NAME:MODEL_VERSION` trailer to each affected commit, per the org-wide policy in `nextcloud/.github`.
|
||||
|
||||
## iOS Specifics
|
||||
|
||||
@@ -61,16 +73,24 @@ The following details are important when working on the iOS client.
|
||||
|
||||
### Requirements
|
||||
|
||||
- Latest stable Xcode available is required to be installed in the development environment.
|
||||
- Use at least the Xcode version pinned in `.github/workflows/xcode.yml` — that is what CI builds and tests with.
|
||||
- A `GoogleService-Info.plist` must exist at the repo root to build; CI downloads Firebase's mock plist (see `xcode.yml`).
|
||||
|
||||
### Code Style
|
||||
|
||||
- When writing code in Swift, respect strict concurrency rules and Swift 6 compatibility.
|
||||
- Write new code to be Swift 6-compatible and strict-concurrency-friendly (proper actor isolation, `Sendable` types). Note that the project currently builds in Swift 5 language mode without strict concurrency checking, so the compiler will not enforce this.
|
||||
- CI runs SwiftLint on every non-draft PR using the root `.swiftlint.yml`; `Tests/`, `Brand/NCBrand.swift` and `iOSClient/NCGlobal.swift` are excluded from linting.
|
||||
|
||||
### Tests
|
||||
|
||||
- When implementing new test suites, prefer Swift Testing over XCTest for implementation.
|
||||
- Do not run builds or tests locally. The user performs all Xcode build and test verification manually.
|
||||
|
||||
- When implementing new test suites, prefer Swift Testing over XCTest for implementation. UI tests are the exception — XCUITest requires XCTest, so new UI tests are XCTest classes subclassing `BaseUIXCTestCase` in `Tests/NextcloudUITests`.
|
||||
- New unit tests go in `Tests/NextcloudUnitTests` as Swift Testing `@Suite` structs with `@testable import Nextcloud`; they need no server.
|
||||
- When implementing test cases using Swift Testing, do not prefix test method names with "test".
|
||||
- If the implementation of mock types is inevitable, implement them in dedicated source code files and in a generic way, so they can be reused across all tests in a test target.
|
||||
- If the implementation of mock types is inevitable, implement them in dedicated source code files and in a generic way, so they can be reused across all tests in a test target. Currently no mock types or mocking library exist; reusable UI-test helpers live in `Tests/NextcloudUITests` (`UITestBackend` and its `Responses/` decodables) — extend these before adding new ones.
|
||||
- If the implementation of an existing mock type does not fulfill the requirements introduced by new tests, prefer updating the existing type before implementing a mostly redundant alternative type.
|
||||
- UI tests require a Nextcloud server at `http://localhost:8080` (credentials `admin`/`admin`, see `Tests/TestConstants.swift`); start one with `Tests/Server.sh` (requires Docker). CI provisions the same server.
|
||||
- `NextcloudIntegrationTests` is currently an empty target: `LoginIntegrationTests.swift` is on disk but excluded from the build and references a nonexistent `EnvVars` type — do not model new tests on it.
|
||||
- Verify that all tests are passing and correct them if necessary.
|
||||
- Run tests the way CI does (see `.github/workflows/xcode.yml`): `xcodebuild test -scheme Nextcloud -destination "platform=iOS Simulator,name=iPhone 17,OS=27.0"` (adjust the simulator to what is installed locally). Without a local test server, restrict to `-only-testing:NextcloudUnitTests`.
|
||||
@@ -0,0 +1,159 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import UIKit
|
||||
import NextcloudKit
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
final class ActionViewController: UIViewController {
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
let groupIdentifier = NCBrandOptions.shared.capabilitiesGroup
|
||||
let storedLogLevel = UserDefaults(suiteName: groupIdentifier)?
|
||||
.object(forKey: "Preferences_logLevel") as? Int
|
||||
let logLevel = storedLogLevel.flatMap(NKLogLevel.init(rawValue:)) ?? .normal
|
||||
let logDirectory = FileManager.default
|
||||
.containerURL(forSecurityApplicationGroupIdentifier: groupIdentifier)?
|
||||
.appendingPathComponent("Logs", isDirectory: true)
|
||||
|
||||
NextcloudKit.configureLogger(
|
||||
logLevel: NCBrandOptions.shared.disable_log ? .disabled : logLevel,
|
||||
logDirectory: logDirectory
|
||||
)
|
||||
|
||||
view.isHidden = true
|
||||
view.alpha = 0
|
||||
view.backgroundColor = .clear
|
||||
preferredContentSize = .zero
|
||||
|
||||
Task {
|
||||
await handleAction()
|
||||
}
|
||||
}
|
||||
|
||||
private func handleAction() async {
|
||||
guard let text = await loadText() else {
|
||||
extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
|
||||
return
|
||||
}
|
||||
|
||||
NCAssistantSharedTextStore.save(text)
|
||||
openMainAppForAssistantSharedText()
|
||||
}
|
||||
|
||||
private func loadText() async -> String? {
|
||||
guard let extensionItems = extensionContext?.inputItems as? [NSExtensionItem] else {
|
||||
return nil
|
||||
}
|
||||
|
||||
for extensionItem in extensionItems {
|
||||
guard let attachments = extensionItem.attachments else {
|
||||
continue
|
||||
}
|
||||
|
||||
for provider in attachments {
|
||||
if provider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) {
|
||||
return await loadText(from: provider, typeIdentifier: UTType.plainText.identifier)
|
||||
}
|
||||
|
||||
if provider.hasItemConformingToTypeIdentifier(UTType.utf8PlainText.identifier) {
|
||||
return await loadText(from: provider, typeIdentifier: UTType.utf8PlainText.identifier)
|
||||
}
|
||||
|
||||
if provider.hasItemConformingToTypeIdentifier(UTType.text.identifier) {
|
||||
return await loadText(from: provider, typeIdentifier: UTType.text.identifier)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
private func loadText(from provider: NSItemProvider, typeIdentifier: String) async -> String? {
|
||||
await withCheckedContinuation { continuation in
|
||||
provider.loadItem(forTypeIdentifier: typeIdentifier, options: nil) { item, _ in
|
||||
let text: String?
|
||||
|
||||
if let string = item as? String {
|
||||
text = string
|
||||
} else if let attributedString = item as? NSAttributedString {
|
||||
text = attributedString.string
|
||||
} else if let data = item as? Data {
|
||||
text = String(data: data, encoding: .utf8)
|
||||
} else if let url = item as? URL {
|
||||
text = try? String(contentsOf: url, encoding: .utf8)
|
||||
} else {
|
||||
text = nil
|
||||
}
|
||||
|
||||
guard let text, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
continuation.resume(returning: nil)
|
||||
return
|
||||
}
|
||||
|
||||
continuation.resume(returning: text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func openMainAppForAssistantSharedText() {
|
||||
guard let url = URL(string: "nextcloud://assistant/shared-text") else {
|
||||
extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
|
||||
return
|
||||
}
|
||||
|
||||
openAssistantSharedTextURLThroughResponderChain(url)
|
||||
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
|
||||
self?.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the Assistant shared-text deep link from the Share extension.
|
||||
///
|
||||
/// Share extensions cannot use `UIApplication.shared` directly because it is not
|
||||
/// extension-safe. This method walks the responder chain until it finds the hidden
|
||||
/// `UIApplication` responder and invokes the modern `open(_:options:completionHandler:)`
|
||||
/// Objective-C selector dynamically.
|
||||
///
|
||||
/// This is intentionally isolated because it relies on Objective-C runtime dispatch.
|
||||
///
|
||||
/// - Parameter url: Deep link URL to open in the containing application.
|
||||
private func openAssistantSharedTextURLThroughResponderChain(_ url: URL) {
|
||||
let selector = NSSelectorFromString("openURL:options:completionHandler:")
|
||||
let applicationClass: AnyClass? = NSClassFromString("UIApplication")
|
||||
var responder: UIResponder? = self
|
||||
|
||||
while let currentResponder = responder {
|
||||
guard let applicationClass,
|
||||
currentResponder.isKind(of: applicationClass),
|
||||
currentResponder.responds(to: selector),
|
||||
let implementation = currentResponder.method(for: selector) else {
|
||||
responder = currentResponder.next
|
||||
continue
|
||||
}
|
||||
|
||||
typealias CompletionBlock = @convention(block) (Bool) -> Void
|
||||
typealias OpenURLFunction = @convention(c) (AnyObject, Selector, NSURL, NSDictionary, CompletionBlock?) -> Void
|
||||
|
||||
let openURL = unsafeBitCast(implementation, to: OpenURLFunction.self)
|
||||
|
||||
let completion: CompletionBlock = { success in
|
||||
if success {
|
||||
nkLog(debug: "Assistant shared text deep link performed through modern responder chain")
|
||||
} else {
|
||||
nkLog(error: "Assistant shared text deep link modern responder chain returned false")
|
||||
}
|
||||
NextcloudKit.flushLogger()
|
||||
}
|
||||
|
||||
openURL(currentResponder, selector, url as NSURL, NSDictionary(), completion)
|
||||
return
|
||||
}
|
||||
|
||||
nkLog(error: "Assistant shared text deep link failed because no UIApplication responder can open URL")
|
||||
NextcloudKit.flushLogger()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="24765" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="ObA-dk-sSI">
|
||||
<device id="retina6_12" orientation="portrait" appearance="light"/>
|
||||
<dependencies>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="24743"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
<!--Image-->
|
||||
<scene sceneID="7MM-of-jgj">
|
||||
<objects>
|
||||
<viewController title="Image" id="ObA-dk-sSI" customClass="ActionViewController" customModule="Action_Assistant" sceneMemberID="viewController">
|
||||
<freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
|
||||
<size key="freeformSize" width="320" height="528"/>
|
||||
</viewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="X47-rx-isc" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="139" y="131"/>
|
||||
</scene>
|
||||
</scenes>
|
||||
</document>
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"filename" : "Senza titolo.png",
|
||||
"idiom" : "universal",
|
||||
"platform" : "ios",
|
||||
"size" : "1024x1024"
|
||||
},
|
||||
{
|
||||
"appearances" : [
|
||||
{
|
||||
"appearance" : "luminosity",
|
||||
"value" : "dark"
|
||||
}
|
||||
],
|
||||
"filename" : "Senza titolo 1.png",
|
||||
"idiom" : "universal",
|
||||
"platform" : "ios",
|
||||
"size" : "1024x1024"
|
||||
},
|
||||
{
|
||||
"appearances" : [
|
||||
{
|
||||
"appearance" : "luminosity",
|
||||
"value" : "tinted"
|
||||
}
|
||||
],
|
||||
"filename" : "Senza titolo 2.png",
|
||||
"idiom" : "universal",
|
||||
"platform" : "ios",
|
||||
"size" : "1024x1024"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 8.2 KiB |
|
After Width: | Height: | Size: 8.2 KiB |
|
After Width: | Height: | Size: 8.2 KiB |
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="141.485" height="99.603" xmlns:svg="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" version="1.1" viewBox="0 0 141.485 99.603">
|
||||
<!-- Generator: Adobe Illustrator 29.5.1, SVG Export Plug-In . SVG Version: 2.1.0 Build 141) -->
|
||||
<g id="Layer_1" inkscape:version="0.92.3 (2405546, 2018-03-11)">
|
||||
<sodipodi:namedview id="namedview16" bordercolor="#666666" borderopacity="1" fit-margin-bottom="10" fit-margin-left="10" fit-margin-right="10" fit-margin-top="10" gridtolerance="10" guidetolerance="10" inkscape:bbox-nodes="true" inkscape:bbox-paths="true" inkscape:current-layer="Layer_1" inkscape:cx="-34.704986" inkscape:cy="33.920203" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:snap-bbox="true" inkscape:snap-bbox-edge-midpoints="true" inkscape:snap-bbox-midpoints="true" inkscape:snap-page="true" inkscape:window-height="1046" inkscape:window-maximized="1" inkscape:window-width="1920" inkscape:window-x="0" inkscape:window-y="34" inkscape:zoom="2.8284271" objecttolerance="10" pagecolor="#ffffff" showgrid="false" units="px"/>
|
||||
<path id="path1052" d="M70.835,22.149c-12.592,0-23.265,8.537-26.573,20.103-2.875-6.135-9.105-10.433-16.281-10.433-9.869,0-17.981,8.112-17.981,17.981s8.112,17.985,17.981,17.985c7.176,0,13.406-4.301,16.281-10.437,3.308,11.567,13.981,20.107,26.573,20.107,12.499,0,23.118-8.411,26.51-19.848,2.928,5.997,9.081,10.177,16.155,10.177,9.869,0,17.985-8.116,17.985-17.985s-8.116-17.981-17.985-17.981c-7.074,0-13.227,4.178-16.155,10.174-3.393-11.436-14.011-19.844-26.51-19.844ZM70.835,32.704c9.506,0,17.099,7.59,17.099,17.096s-7.594,17.099-17.099,17.099-17.096-7.594-17.096-17.099,7.59-17.096,17.096-17.096ZM27.981,42.374c4.165,0,7.429,3.261,7.429,7.426s-3.265,7.429-7.429,7.429-7.426-3.265-7.426-7.429,3.261-7.426,7.426-7.426ZM113.5,42.374c4.165,0,7.429,3.261,7.429,7.426s-3.265,7.429-7.429,7.429-7.426-3.265-7.426-7.429,3.261-7.426,7.426-7.426Z" inkscape:connector-curvature="0" inkscape:export-filename="Nextcloud Hub logo variants.png" inkscape:export-xdpi="300" inkscape:export-ydpi="300" fill="#fff"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.3 KiB |
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" version="1.1" viewBox="0 0 141.49 99.6">
|
||||
<!-- Generator: Adobe Illustrator 30.3.0, SVG Export Plug-In . SVG Version: 2.1.3 Build 182) -->
|
||||
<defs>
|
||||
<style>
|
||||
.st0 {
|
||||
fill: #fff;
|
||||
}
|
||||
</style>
|
||||
</defs>
|
||||
<path id="path1052" class="st0" d="M70.83,22.15c-12.59,0-23.26,8.54-26.57,20.1-2.88-6.14-9.1-10.43-16.28-10.43-9.87,0-17.98,8.11-17.98,17.98s8.11,17.99,17.98,17.99c7.18,0,13.41-4.3,16.28-10.44,3.31,11.57,13.98,20.11,26.57,20.11s23.12-8.41,26.51-19.85c2.93,6,9.08,10.18,16.15,10.18,9.87,0,17.99-8.12,17.99-17.99s-8.12-17.98-17.99-17.98c-7.07,0-13.23,4.18-16.15,10.17-3.39-11.44-14.01-19.84-26.51-19.84h0ZM70.83,32.7c9.51,0,17.1,7.59,17.1,17.1s-7.59,17.1-17.1,17.1-17.1-7.59-17.1-17.1,7.59-17.1,17.1-17.1ZM27.98,42.37c4.16,0,7.43,3.26,7.43,7.43s-3.26,7.43-7.43,7.43-7.43-3.26-7.43-7.43,3.26-7.43,7.43-7.43ZM113.5,42.37c4.17,0,7.43,3.26,7.43,7.43s-3.26,7.43-7.43,7.43-7.43-3.26-7.43-7.43,3.26-7.43,7.43-7.43Z" inkscape:connector-curvature="0" inkscape:export-filename="Nextcloud Hub logo variants.png" inkscape:export-xdpi="300" inkscape:export-ydpi="300"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -1,26 +1,28 @@
|
||||
{
|
||||
"fill" : {
|
||||
"solid" : "display-p3:0.10980,0.68627,1.00000,1.00000"
|
||||
"linear-gradient" : [
|
||||
"display-p3:0.10980,0.68627,1.00000,1.00000",
|
||||
"srgb:0.00000,0.50980,0.78824,1.00000"
|
||||
],
|
||||
"orientation" : {
|
||||
"start" : {
|
||||
"x" : 0.5,
|
||||
"y" : 0
|
||||
},
|
||||
"stop" : {
|
||||
"x" : 0.5,
|
||||
"y" : 0.7
|
||||
}
|
||||
}
|
||||
},
|
||||
"groups" : [
|
||||
{
|
||||
"layers" : [
|
||||
{
|
||||
"glass-specializations" : [
|
||||
{
|
||||
"value" : true
|
||||
},
|
||||
{
|
||||
"idiom" : "square",
|
||||
"value" : true
|
||||
}
|
||||
],
|
||||
"hidden" : false,
|
||||
"image-name" : "Nextcloud-logo-markonly-white.svg",
|
||||
"name" : "Nextcloud-logo-markonly-white",
|
||||
"opacity" : 1,
|
||||
"image-name" : "Nextcloud-logo-white.svg",
|
||||
"name" : "Nextcloud-logo-white",
|
||||
"position" : {
|
||||
"scale" : 7,
|
||||
"scale" : 6.8,
|
||||
"translation-in-points" : [
|
||||
0,
|
||||
0
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import Photos
|
||||
import NextcloudKit
|
||||
|
||||
extension BackgroundUploadExtension {
|
||||
/// Validates Photos access, feature settings, the active auto-upload account, and server support.
|
||||
/// Configures the account's NextcloudKit session and returns `nil` when processing must be skipped.
|
||||
func setupAccount() async -> tableAccount? {
|
||||
guard PHPhotoLibrary.authorizationStatus(for: .readWrite) == .authorized else {
|
||||
logInfo("Background upload account setup skipped: Photos authorization is not granted")
|
||||
return nil
|
||||
}
|
||||
|
||||
guard NCPreferences().shouldUseBackgroundUploadExtension else {
|
||||
logInfo("Background upload account setup skipped: feature is disabled")
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let account = await database.getTableAccountAsync(predicate: NSPredicate(format: "autoUploadStart == true")) else {
|
||||
logInfo("Background upload account setup skipped: no Auto Upload account")
|
||||
return nil
|
||||
}
|
||||
|
||||
// The extension runs in its own process, so rebuild the in-memory session from shared account data.
|
||||
NextcloudKit.shared.appendSession(
|
||||
account: account.account,
|
||||
urlBase: account.urlBase,
|
||||
user: account.user,
|
||||
userId: account.userId,
|
||||
password: NCPreferences().getPassword(account: account.account),
|
||||
userAgent: userAgent,
|
||||
httpMaximumConnectionsPerHost: NCBrandOptions.shared.httpMaximumConnectionsPerHost,
|
||||
httpMaximumConnectionsPerHostInDownload: NCBrandOptions.shared.httpMaximumConnectionsPerHostInDownload,
|
||||
httpMaximumConnectionsPerHostInUpload: NCBrandOptions.shared.httpMaximumConnectionsPerHostInUpload,
|
||||
groupIdentifier: NCBrandOptions.shared.capabilitiesGroup
|
||||
)
|
||||
|
||||
guard let capabilities = await database.getCapabilities(account: account.account) else {
|
||||
logError("Background upload account setup failed: capabilities not found for \(account.account)")
|
||||
return nil
|
||||
}
|
||||
|
||||
guard NCBrandOptions.shared.isServerVersion(
|
||||
capabilities,
|
||||
greaterOrEqualTo: .v35
|
||||
) else {
|
||||
logInfo("Background upload extension stopped because account \(account.account) uses a server lower than version 35")
|
||||
return nil
|
||||
}
|
||||
|
||||
return account
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import Photos
|
||||
import NextcloudKit
|
||||
|
||||
extension BackgroundUploadExtension {
|
||||
/// Builds the authenticated WebDAV PUT request that PhotoKit uses as an upload destination.
|
||||
/// Applies network policy and asset timestamps, returning `nil` when URL or session data is invalid.
|
||||
func buildDestination(metadata: tableMetadata, asset: PHAsset) -> URLRequest? {
|
||||
guard let url = metadata.serverUrlFileName.encodedToUrl as? URL else {
|
||||
logError("Invalid destination URL: \(metadata.serverUrlFileName)")
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let nkSession = nkComm.nksessions.session(forAccount: metadata.account) else {
|
||||
logError("Session not found for account: \(metadata.account)")
|
||||
return nil
|
||||
}
|
||||
|
||||
let wifiOnly = metadata.session == nkComm.identifierSessionUploadBackgroundWWan
|
||||
let loginString = "\(nkSession.user):\(nkSession.password)"
|
||||
var request = URLRequest(url: url)
|
||||
|
||||
guard let loginData = loginString.data(using: .utf8) else {
|
||||
logError("Unable to encode credentials for account: \(metadata.account)")
|
||||
return nil
|
||||
}
|
||||
|
||||
request.httpMethod = "PUT"
|
||||
request.allowsCellularAccess = !wifiOnly
|
||||
request.allowsExpensiveNetworkAccess = true
|
||||
request.setValue(nkSession.userAgent, forHTTPHeaderField: "User-Agent")
|
||||
request.setValue("Basic \(loginData.base64EncodedString())", forHTTPHeaderField: "Authorization")
|
||||
request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
|
||||
// Let Nextcloud create missing auto-upload folders and identify PhotoKit-specific requests.
|
||||
request.setValue("1", forHTTPHeaderField: "X-NC-WebDAV-Auto-Mkcol")
|
||||
request.setValue("1", forHTTPHeaderField: "X-NC-PhotoKit-Upload")
|
||||
|
||||
if let creationDate = asset.creationDate,
|
||||
creationDate.timeIntervalSince1970 > 0 {
|
||||
request.setValue("\(creationDate.timeIntervalSince1970)", forHTTPHeaderField: "X-OC-CTime")
|
||||
}
|
||||
|
||||
if let modificationDate = asset.modificationDate,
|
||||
modificationDate.timeIntervalSince1970 > 0 {
|
||||
request.setValue("\(modificationDate.timeIntervalSince1970)", forHTTPHeaderField: "X-OC-MTime")
|
||||
}
|
||||
|
||||
logInfo("Destination created for \(metadata.fileName) -> \(metadata.serverUrlFileName)")
|
||||
|
||||
return request
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import Photos
|
||||
import NextcloudKit
|
||||
|
||||
extension BackgroundUploadExtension {
|
||||
/// Finds eligible assets and creates up to `limit` pending metadata records for their resources.
|
||||
/// Confirmed transfers advance the incremental date; unfinished resources keep it from moving past them.
|
||||
func createPendingMetadatas(account: tableAccount, limit: Int) async -> Bool {
|
||||
guard limit > 0,
|
||||
account.autoUploadImage || account.autoUploadVideo else {
|
||||
return false
|
||||
}
|
||||
|
||||
let autoUploadServerUrlBase = await database.getAccountAutoUploadServerUrlBaseAsync(
|
||||
account: account.account,
|
||||
urlBase: account.urlBase,
|
||||
userId: account.userId
|
||||
)
|
||||
|
||||
let livePhotoEnabled = NCPreferences().livePhoto
|
||||
let fetchOptions = PHFetchOptions()
|
||||
var mediaPredicates: [NSPredicate] = []
|
||||
|
||||
if account.autoUploadImage {
|
||||
mediaPredicates.append(NSPredicate(format: "mediaType == %d", PHAssetMediaType.image.rawValue))
|
||||
}
|
||||
|
||||
if account.autoUploadVideo {
|
||||
mediaPredicates.append(NSPredicate(format: "mediaType == %d", PHAssetMediaType.video.rawValue))
|
||||
}
|
||||
|
||||
var predicates: [NSPredicate] = [NSCompoundPredicate(orPredicateWithSubpredicates: mediaPredicates)]
|
||||
|
||||
if let datePredicate = account.autoUploadDatePredicate {
|
||||
predicates.append(datePredicate)
|
||||
}
|
||||
|
||||
fetchOptions.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
|
||||
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
|
||||
|
||||
let fetchResults = autoUploadCollections(for: account).map {
|
||||
PHAsset.fetchAssets(in: $0, options: fetchOptions)
|
||||
}
|
||||
var fetchIndexes = Array(repeating: 0, count: fetchResults.count)
|
||||
var yieldedAssetIdentifiers = Set<String>()
|
||||
guard let activeMetadatas = await database.getMetadatasAsync(predicate: NSPredicate(
|
||||
format: "account == %@ AND autoUploadServerUrlBase == %@ AND status IN %@",
|
||||
account.account, autoUploadServerUrlBase, global.metadataStatusUploadingAllMode
|
||||
), limit: nil) else { return false }
|
||||
let activeAssets = Dictionary(grouping: activeMetadatas, by: \.assetLocalIdentifier)
|
||||
var trackedMetadataFileNames = Set(activeMetadatas.map(\.fileNameView))
|
||||
|
||||
var remaining = limit
|
||||
var madeProgress = false
|
||||
var lastUploadedDate: Date?
|
||||
var canAdvanceSinceDate = true
|
||||
|
||||
// PhotoKit already sorts every result; merge them lazily and stop as soon as the job slots are full.
|
||||
discoveryLoop: while remaining > 0,
|
||||
let asset = nextAsset(from: fetchResults, indexes: &fetchIndexes, yieldedIdentifiers: &yieldedAssetIdentifiers) {
|
||||
guard let current = database.getTableAccount(account: account.account),
|
||||
current.autoUploadStart,
|
||||
current.autoUploadSessionIdentifier == account.autoUploadSessionIdentifier else { break }
|
||||
|
||||
let isLivePhotoAsset = asset.mediaSubtypes.contains(.photoLive)
|
||||
let isLivePhoto = isLivePhotoAsset && livePhotoEnabled
|
||||
|
||||
let history: [NCAutoUploadResource]
|
||||
do {
|
||||
history = try await NCLocalDatabase.shared.autoUploadResources(
|
||||
account: account.account,
|
||||
serverUrlBase: autoUploadServerUrlBase,
|
||||
assetLocalIdentifier: asset.localIdentifier,
|
||||
sessionIdentifier: account.autoUploadForceReupload ? account.autoUploadSessionIdentifier : nil
|
||||
)
|
||||
} catch {
|
||||
logError("Unable to read background upload history: \(error)")
|
||||
break
|
||||
}
|
||||
let queued = activeAssets[asset.localIdentifier] ?? []
|
||||
let queuedClasses = Set(queued.map(\.classFile))
|
||||
let primaryClassFile = asset.mediaType == .video ? NKTypeClassFile.video.rawValue : NKTypeClassFile.image.rawValue
|
||||
let requiredClasses = isLivePhoto ? [primaryClassFile, NKTypeClassFile.video.rawValue] : [primaryClassFile]
|
||||
let uploadedClasses = Set(history.filter(\.uploaded).map(\.classFile))
|
||||
if requiredClasses.allSatisfy({ uploadedClasses.contains($0) }) {
|
||||
if canAdvanceSinceDate { lastUploadedDate = asset.creationDate ?? lastUploadedDate }
|
||||
continue
|
||||
}
|
||||
|
||||
// Check capacity before generating a name that may advance the incremental counter.
|
||||
guard requiredClasses.filter({ !uploadedClasses.contains($0) && !queuedClasses.contains($0) }).count <= remaining else { break }
|
||||
|
||||
guard let primaryResource = primaryUploadResource(for: asset),
|
||||
let originalFileName = primaryResource.filename,
|
||||
!originalFileName.isEmpty else {
|
||||
logError("Upload resource not found for asset \(asset.localIdentifier)")
|
||||
canAdvanceSinceDate = false
|
||||
continue
|
||||
}
|
||||
|
||||
let creationDate = asset.creationDate ?? Date()
|
||||
let queuedPrimary = queued.first { $0.classFile == primaryClassFile }
|
||||
let primaryFileName = queuedPrimary?.fileNameView
|
||||
?? queued.first { $0.isLivePhotoVideo }?.livePhotoFile
|
||||
?? history.first { $0.classFile == primaryClassFile }?.fileName
|
||||
?? utilityFileSystem.createFileName(originalFileName, fileDate: creationDate, fileType: asset.mediaType)
|
||||
let videoFileName = queued.first { $0.classFile == NKTypeClassFile.video.rawValue }?.fileNameView
|
||||
?? queuedPrimary.flatMap { $0.isLivePhotoImage ? $0.livePhotoFile : nil }
|
||||
?? history.first { $0.classFile == NKTypeClassFile.video.rawValue }?.fileName
|
||||
?? (primaryFileName as NSString).deletingPathExtension + ".mov"
|
||||
var uploadResources: [(resource: PHAssetResource, fileName: String, classFile: String, livePhotoFile: String)]
|
||||
|
||||
if isLivePhoto {
|
||||
guard let pairedVideoResource = pairedVideoResource(for: asset) else {
|
||||
logError("Paired video resource not found for Live Photo asset \(asset.localIdentifier)")
|
||||
canAdvanceSinceDate = false
|
||||
continue
|
||||
}
|
||||
|
||||
uploadResources = [
|
||||
(primaryResource, primaryFileName, NKTypeClassFile.image.rawValue, videoFileName),
|
||||
(pairedVideoResource, videoFileName, NKTypeClassFile.video.rawValue, primaryFileName)
|
||||
]
|
||||
} else {
|
||||
uploadResources = [
|
||||
(primaryResource, primaryFileName, primaryClassFile, "")
|
||||
]
|
||||
}
|
||||
|
||||
// Completed components are independent from the server metadata refreshed by sync.
|
||||
canAdvanceSinceDate = false
|
||||
let resourcesToUpload = uploadResources.filter {
|
||||
!uploadedClasses.contains($0.classFile) && !queuedClasses.contains($0.classFile) && !trackedMetadataFileNames.contains($0.fileName)
|
||||
}
|
||||
|
||||
// Each resource selects its own pipeline: PhotoKit up to 100 MB, host-app chunks above it.
|
||||
for uploadResource in resourcesToUpload {
|
||||
let chunkSize = Int64(uploadResource.resource.dataSize ?? 0) > Int64(global.chunkSize) ? global.chunkSize : nil
|
||||
|
||||
let inserted = await createPendingMetadata(
|
||||
asset: asset,
|
||||
resource: uploadResource.resource,
|
||||
fileName: uploadResource.fileName,
|
||||
classFile: uploadResource.classFile,
|
||||
livePhotoFile: uploadResource.livePhotoFile,
|
||||
legacyChunkSize: chunkSize,
|
||||
account: account
|
||||
)
|
||||
|
||||
guard inserted else { break discoveryLoop }
|
||||
trackedMetadataFileNames.insert(uploadResource.fileName)
|
||||
remaining -= 1
|
||||
madeProgress = true
|
||||
}
|
||||
}
|
||||
|
||||
if let lastUploadedDate {
|
||||
await database.updateAutoUploadSinceDateIfEnabledAsync(lastUploadedDate, account: account.account, sessionIdentifier: account.autoUploadSessionIdentifier)
|
||||
}
|
||||
|
||||
return madeProgress
|
||||
}
|
||||
|
||||
/// Returns the next oldest unique asset across already sorted PhotoKit fetch results.
|
||||
/// Only one candidate per selected collection is retained, keeping discovery memory bounded.
|
||||
private func nextAsset(from fetchResults: [PHFetchResult<PHAsset>], indexes: inout [Int], yieldedIdentifiers: inout Set<String>) -> PHAsset? {
|
||||
var selectedResultIndex: Int?
|
||||
var selectedAsset: PHAsset?
|
||||
|
||||
for resultIndex in fetchResults.indices {
|
||||
let result = fetchResults[resultIndex]
|
||||
|
||||
while indexes[resultIndex] < result.count {
|
||||
let candidate = result.object(at: indexes[resultIndex])
|
||||
|
||||
if yieldedIdentifiers.contains(candidate.localIdentifier) {
|
||||
indexes[resultIndex] += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if let selectedAsset,
|
||||
(candidate.creationDate ?? .distantPast) >= (selectedAsset.creationDate ?? .distantPast) {
|
||||
break
|
||||
}
|
||||
|
||||
selectedResultIndex = resultIndex
|
||||
selectedAsset = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
guard let selectedResultIndex, let selectedAsset else {
|
||||
return nil
|
||||
}
|
||||
|
||||
indexes[selectedResultIndex] += 1
|
||||
yieldedIdentifiers.insert(selectedAsset.localIdentifier)
|
||||
return selectedAsset
|
||||
}
|
||||
|
||||
/// Creates the transfer metadata that connects a Photos resource to its server path.
|
||||
/// Large resources remain ordinary metadata for the host app; all others wait for a PhotoKit job.
|
||||
private func createPendingMetadata(asset: PHAsset, resource: PHAssetResource, fileName: String, classFile: String, livePhotoFile: String, legacyChunkSize: Int?, account: tableAccount) async -> Bool {
|
||||
let session = NCSession.Session(account: account.account, urlBase: account.urlBase, user: account.user, userId: account.userId)
|
||||
let autoUploadServerUrlBase = await database.getAccountAutoUploadServerUrlBaseAsync(account: account.account, urlBase: account.urlBase, userId: account.userId)
|
||||
|
||||
let serverUrl: String
|
||||
let wifiOnly = asset.mediaType == .image ? account.autoUploadWWAnPhoto : account.autoUploadWWAnVideo
|
||||
|
||||
if account.autoUploadCreateSubfolder {
|
||||
serverUrl = utilityFileSystem.createGranularityPath(asset: asset, serverUrlBase: autoUploadServerUrlBase, granularity: account.autoUploadSubfolderGranularity)
|
||||
} else {
|
||||
serverUrl = autoUploadServerUrlBase
|
||||
}
|
||||
|
||||
let metadata = await NCManageDatabaseCreateMetadata().createMetadataAsync(fileName: fileName, ocId: UUID().uuidString, serverUrl: serverUrl, session: session, sceneIdentifier: nil)
|
||||
|
||||
metadata.assetLocalIdentifier = asset.localIdentifier
|
||||
metadata.autoUploadServerUrlBase = autoUploadServerUrlBase
|
||||
metadata.nativeFormat = true
|
||||
metadata.contentType = resource.contentType.preferredMIMEType ?? "application/octet-stream"
|
||||
metadata.typeIdentifier = resource.contentType.identifier
|
||||
metadata.classFile = classFile
|
||||
metadata.livePhotoFile = livePhotoFile
|
||||
metadata.size = Int64(resource.dataSize ?? 0)
|
||||
metadata.width = asset.pixelWidth
|
||||
metadata.height = asset.pixelHeight
|
||||
|
||||
if let creationDate = asset.creationDate {
|
||||
metadata.creationDate = creationDate as NSDate
|
||||
}
|
||||
|
||||
if let modificationDate = asset.modificationDate {
|
||||
metadata.date = modificationDate as NSDate
|
||||
}
|
||||
|
||||
metadata.session = wifiOnly ? nkComm.identifierSessionUploadBackgroundWWan : nkComm.identifierSessionUploadBackground
|
||||
metadata.sessionSelector = global.selectorUploadAutoUpload
|
||||
metadata.sessionDate = Date()
|
||||
metadata.status = global.metadataStatusWaitUpload
|
||||
metadata.chunk = legacyChunkSize ?? 0
|
||||
metadata.backgroundUploadJobIdentifier = legacyChunkSize == nil ? "pending" : ""
|
||||
|
||||
do {
|
||||
guard try await NCLocalDatabase.shared.recordAutoUploadTransfer(metadata, sessionIdentifier: account.autoUploadSessionIdentifier) else { return false }
|
||||
} catch {
|
||||
logError("Unable to register background upload transfer: \(error)")
|
||||
return false
|
||||
}
|
||||
|
||||
await database.addAutoUploadMetadatasAsync([metadata], account: account.account, sessionIdentifier: account.autoUploadSessionIdentifier)
|
||||
guard await database.getMetadataAsync(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) != nil else { return false }
|
||||
|
||||
if legacyChunkSize == nil {
|
||||
logInfo("Created pending metadata for \(fileName), account: \(account.account), asset: \(asset.localIdentifier)")
|
||||
} else {
|
||||
logInfo("Deferred large resource to the host app chunked upload pipeline: \(fileName), size: \(metadata.size)")
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// Selects the full-size primary resource for an image or video asset when available.
|
||||
/// Falls back to the standard photo or video resource and rejects unsupported media types.
|
||||
private func primaryUploadResource(for asset: PHAsset) -> PHAssetResource? {
|
||||
let resources = PHAssetResource.assetResources(for: asset)
|
||||
|
||||
switch asset.mediaType {
|
||||
case .image:
|
||||
return resources.first {
|
||||
$0.type == .fullSizePhoto
|
||||
} ?? resources.first {
|
||||
$0.type == .photo
|
||||
}
|
||||
|
||||
case .video:
|
||||
return resources.first {
|
||||
$0.type == .fullSizeVideo
|
||||
} ?? resources.first {
|
||||
$0.type == .video
|
||||
}
|
||||
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects the motion component of a Live Photo, preferring its full-size representation.
|
||||
/// Returns `nil` when the asset does not expose a paired video resource.
|
||||
private func pairedVideoResource(for asset: PHAsset) -> PHAssetResource? {
|
||||
let resources = PHAssetResource.assetResources(for: asset)
|
||||
|
||||
return resources.first {
|
||||
$0.type == .fullSizePairedVideo
|
||||
} ?? resources.first {
|
||||
$0.type == .pairedVideo
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the explicitly selected albums or, when none are configured, the Camera Roll.
|
||||
/// An unavailable explicit selection returns no collections to avoid uploading unintended assets.
|
||||
private func autoUploadCollections(for account: tableAccount) -> [PHAssetCollection] {
|
||||
let albumIds = NCPreferences().getAutoUploadAlbumIds(account: account.account)
|
||||
|
||||
if !albumIds.isEmpty {
|
||||
let result = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: Array(albumIds), options: nil)
|
||||
var collections: [PHAssetCollection] = []
|
||||
|
||||
result.enumerateObjects { collection, _, _ in
|
||||
collections.append(collection)
|
||||
}
|
||||
|
||||
if collections.isEmpty {
|
||||
logInfo("Background upload skipped because the selected albums are no longer available")
|
||||
}
|
||||
|
||||
return collections
|
||||
}
|
||||
|
||||
let result = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil)
|
||||
|
||||
guard let cameraRoll = result.firstObject else {
|
||||
return []
|
||||
}
|
||||
|
||||
return [cameraRoll]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,644 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import Photos
|
||||
import NextcloudKit
|
||||
|
||||
extension BackgroundUploadExtension {
|
||||
/// Converts pending metadata records into PhotoKit upload jobs until the job limit is reached.
|
||||
/// Persists each PhotoKit identifier so later invocations can reconcile the job with Realm state.
|
||||
func createUploadJobs(account: tableAccount) async throws -> Bool {
|
||||
let availableJobs = availableUploadJobSlots()
|
||||
|
||||
guard availableJobs > 0 else {
|
||||
logInfo("No available background upload job slots")
|
||||
return false
|
||||
}
|
||||
|
||||
let predicate = NSPredicate(
|
||||
format: """
|
||||
status == %d AND \
|
||||
backgroundUploadJobIdentifier == %@ AND \
|
||||
account == %@
|
||||
""",
|
||||
global.metadataStatusWaitUpload,
|
||||
"pending",
|
||||
account.account
|
||||
)
|
||||
|
||||
guard let metadatas = await database.getMetadatasAsync(
|
||||
predicate: predicate,
|
||||
sortedByKeyPath: "sessionDate",
|
||||
ascending: true,
|
||||
limit: availableJobs
|
||||
),
|
||||
!metadatas.isEmpty else {
|
||||
return false
|
||||
}
|
||||
|
||||
let library = PHPhotoLibrary.shared()
|
||||
var madeProgress = false
|
||||
|
||||
for metadata in metadatas {
|
||||
guard let currentAccount = await database.getTableAccountAsync(
|
||||
predicate: NSPredicate(format: "account == %@", account.account)
|
||||
), currentAccount.autoUploadStart,
|
||||
currentAccount.autoUploadSessionIdentifier == account.autoUploadSessionIdentifier else {
|
||||
break
|
||||
}
|
||||
|
||||
guard let currentMetadata = await database.getMetadataAsync(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)),
|
||||
!currentMetadata.backgroundUploadCancellationRequested else {
|
||||
continue
|
||||
}
|
||||
let assets = PHAsset.fetchAssets(withLocalIdentifiers: [metadata.assetLocalIdentifier], options: nil)
|
||||
|
||||
guard let asset = assets.firstObject else {
|
||||
await database.deleteMetadataAsync(id: metadata.ocId)
|
||||
madeProgress = true
|
||||
logInfo("Deleted pending background upload metadata for missing asset \(metadata.assetLocalIdentifier), file: \(metadata.fileName)")
|
||||
continue
|
||||
}
|
||||
|
||||
guard let resource = uploadResource(for: asset, metadata: metadata) else {
|
||||
await database.deleteMetadataAsync(id: metadata.ocId)
|
||||
madeProgress = true
|
||||
|
||||
logInfo(
|
||||
"Deleted pending background upload metadata because the resource is no longer available for asset \(metadata.assetLocalIdentifier), file: \(metadata.fileName)"
|
||||
)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
guard let backgroundUploadResource = try await NCLocalDatabase.shared.autoUploadResource(for: metadata) else { continue }
|
||||
if backgroundUploadResource.uploaded {
|
||||
await database.deleteMetadataAsync(id: metadata.ocId)
|
||||
madeProgress = true
|
||||
continue
|
||||
}
|
||||
|
||||
guard let destination = buildDestination(metadata: metadata, asset: asset) else {
|
||||
continue
|
||||
}
|
||||
|
||||
var jobIdentifier: String?
|
||||
|
||||
// PhotoKit job creation must happen inside its library change transaction.
|
||||
try library.performChangesAndWait {
|
||||
guard let current = self.database.getTableAccount(account: account.account),
|
||||
current.autoUploadStart,
|
||||
current.autoUploadSessionIdentifier == account.autoUploadSessionIdentifier,
|
||||
let currentMetadata = self.database.getMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)),
|
||||
!currentMetadata.backgroundUploadCancellationRequested,
|
||||
currentMetadata.backgroundUploadJobIdentifier == "pending" else { return }
|
||||
let request = PHAssetResourceUploadJobChangeRequest.creationRequestForJob(destination: destination, resource: resource)
|
||||
jobIdentifier = request.placeholderForCreatedAssetResourceUploadJob?.localIdentifier
|
||||
}
|
||||
|
||||
guard let jobIdentifier, !jobIdentifier.isEmpty else {
|
||||
logError("Created job has no local identifier")
|
||||
continue
|
||||
}
|
||||
|
||||
await persistMetadataState(
|
||||
.uploading(jobIdentifier: jobIdentifier, incrementRetryCount: false),
|
||||
metadata: metadata
|
||||
)
|
||||
|
||||
guard let savedMetadata = await database.getMetadataAsync(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)),
|
||||
!savedMetadata.backgroundUploadCancellationRequested else {
|
||||
_ = try await cancelRequestedUploadJobs()
|
||||
continue
|
||||
}
|
||||
if let current = database.getTableAccount(account: account.account),
|
||||
!current.autoUploadStart || current.autoUploadSessionIdentifier != account.autoUploadSessionIdentifier {
|
||||
metadata.backgroundUploadCancellationRequested = true
|
||||
await database.updateBackgroundUploadMetadataAsync(metadata, expectedJobIdentifier: jobIdentifier)
|
||||
_ = try await cancelRequestedUploadJobs()
|
||||
break
|
||||
}
|
||||
|
||||
madeProgress = true
|
||||
|
||||
logInfo("Created background upload job \(jobIdentifier), file: \(metadata.fileName), resource: \(resource.filename ?? "<unknown>")")
|
||||
}
|
||||
|
||||
return madeProgress
|
||||
}
|
||||
|
||||
/// Cancels jobs requested by the app and recovers jobs whose identifier was not persisted after creation.
|
||||
/// A job is treated as orphaned only when no pending metadata matches its asset and destination.
|
||||
func cancelRequestedUploadJobs() async throws -> Bool {
|
||||
let library = PHPhotoLibrary.shared()
|
||||
var madeProgress = false
|
||||
let cancellableJobs = PHAssetResourceUploadJob.fetchJobs(action: .process, options: nil)
|
||||
|
||||
for index in 0..<cancellableJobs.count {
|
||||
let job = cancellableJobs.object(at: index)
|
||||
let jobIdentifier = job.localIdentifier
|
||||
let metadata = await resolveMetadata(for: job)
|
||||
|
||||
guard let metadata else {
|
||||
guard try cancel(job: job, library: library) else {
|
||||
logError("Unable to cancel orphan background upload job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
madeProgress = true
|
||||
logInfo("Cancelled orphan background upload job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
guard metadata.backgroundUploadCancellationRequested else {
|
||||
continue
|
||||
}
|
||||
|
||||
guard try cancel(job: job, library: library) else {
|
||||
logError("Unable to cancel job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
await database.deleteMetadataAsync(id: metadata.ocId)
|
||||
madeProgress = true
|
||||
logInfo("Cancelled background upload job \(jobIdentifier), file: \(metadata.fileName)")
|
||||
}
|
||||
|
||||
let retryJobs = PHAssetResourceUploadJob.fetchJobs(action: .retry, options: nil)
|
||||
let acknowledgeJobs = PHAssetResourceUploadJob.fetchJobs(action: .acknowledge, options: nil)
|
||||
var handledTerminalJobIdentifiers = Set<String>()
|
||||
|
||||
for jobs in [retryJobs, acknowledgeJobs] {
|
||||
for index in 0..<jobs.count {
|
||||
let job = jobs.object(at: index)
|
||||
let jobIdentifier = job.localIdentifier
|
||||
|
||||
// Failed jobs can appear in both collections; acknowledge each one only once.
|
||||
guard handledTerminalJobIdentifiers.insert(jobIdentifier).inserted else {
|
||||
continue
|
||||
}
|
||||
|
||||
let metadata = await resolveMetadata(for: job)
|
||||
|
||||
guard let metadata else {
|
||||
guard try acknowledge(job: job, library: library) else {
|
||||
logError("Unable to acknowledge orphan background upload job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
madeProgress = true
|
||||
logInfo("Acknowledged orphan background upload job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
guard metadata.backgroundUploadCancellationRequested else {
|
||||
continue
|
||||
}
|
||||
|
||||
if !(job.responseHeaderFields?["oc-fileid"] ?? "").isEmpty {
|
||||
guard await processUploadSuccess(metadata: metadata, job: job) else { continue }
|
||||
await persistMetadataState(.completed, metadata: metadata)
|
||||
} else if job.state == .succeeded {
|
||||
logError("Stop deferred for successful job without oc-fileid: \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
guard try acknowledge(job: job, library: library) else {
|
||||
logError("Unable to acknowledge cancelled job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
if metadata.status != global.metadataStatusNormal {
|
||||
await database.deleteMetadataAsync(id: metadata.ocId)
|
||||
}
|
||||
madeProgress = true
|
||||
logInfo("Acknowledged cancelled background upload job \(jobIdentifier), state: \(job.state.rawValue)")
|
||||
}
|
||||
}
|
||||
|
||||
return madeProgress
|
||||
}
|
||||
|
||||
/// Examines jobs for which PhotoKit offers a retry and decides whether to retry or acknowledge them.
|
||||
/// Server-confirmed uploads and permanent failures are acknowledged instead of being uploaded again.
|
||||
func processRetryableUploadJobs() async throws -> Bool {
|
||||
let jobs = PHAssetResourceUploadJob.fetchJobs(action: .retry, options: nil)
|
||||
|
||||
guard jobs.count > 0 else {
|
||||
return false
|
||||
}
|
||||
|
||||
let library = PHPhotoLibrary.shared()
|
||||
var madeProgress = false
|
||||
|
||||
for index in 0..<jobs.count {
|
||||
let job = jobs.object(at: index)
|
||||
let jobIdentifier = job.localIdentifier
|
||||
|
||||
guard let metadata = await resolveMetadata(for: job) else {
|
||||
guard try acknowledge(job: job, library: library) else {
|
||||
logError("Unable to acknowledge orphan retry job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
madeProgress = true
|
||||
|
||||
logInfo("Acknowledged orphan retry job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
guard !metadata.backgroundUploadCancellationRequested else {
|
||||
logInfo("Skipping retry for cancellation-requested job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
let sessionIdentifier = database.getTableAccount(account: metadata.account)?.autoUploadSessionIdentifier ?? ""
|
||||
logUploadJobDiagnostics(job: job, action: "retry")
|
||||
|
||||
if hasConfirmedUploadResponse(job: job) {
|
||||
// Nextcloud committed the file even though PhotoKit classified the overwrite as failed.
|
||||
// First persist the successful response in Realm, including the server file identifier,
|
||||
// auto-upload history, and any pending Live Photo component.
|
||||
guard await processUploadSuccess(metadata: metadata, job: job) else {
|
||||
continue
|
||||
}
|
||||
|
||||
// Close local tracking before acknowledging PhotoKit. If the extension stops between
|
||||
// these operations, the remaining terminal job is safely acknowledged as an orphan.
|
||||
await persistMetadataState(.completed, metadata: metadata)
|
||||
|
||||
// Acknowledgement is the final confirmation to PhotoKit: it removes the completed job
|
||||
// from the system queue and prevents PhotoKit from uploading the same resource again.
|
||||
guard try acknowledge(job: job, library: library) else {
|
||||
logError("Unable to acknowledge server-confirmed retry job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
madeProgress = true
|
||||
logInfo("Accepted server-confirmed upload for \(metadata.fileName), job: \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
let authenticationRequired = isAuthenticationFailure(job: job)
|
||||
let retryLimitReached = !canAutomaticallyRetry(metadata: metadata)
|
||||
let queueSuspended = preferences.isBackgroundUploadSuspended(account: metadata.account)
|
||||
|
||||
// Stop before a fourth upload, invalid credentials, or work on a suspended account queue.
|
||||
if authenticationRequired || retryLimitReached || queueSuspended {
|
||||
if authenticationRequired {
|
||||
// Invalid credentials affect every file, so suspend the account immediately.
|
||||
preferences.setBackgroundUploadSuspended(true, account: metadata.account)
|
||||
} else if retryLimitReached,
|
||||
!queueSuspended,
|
||||
recordTerminalUploadFailure(metadata: metadata) {
|
||||
logError("Suspended background upload after \(maximumConsecutiveBackgroundUploadFailures) consecutive asset failures for account \(metadata.account)")
|
||||
}
|
||||
|
||||
await updateMetadataForUploadFailure(metadata: metadata, job: job)
|
||||
|
||||
guard try acknowledge(job: job, library: library) else {
|
||||
logError("Unable to acknowledge stopped job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
// Keep the failed transfer available for an explicit retry from the host app.
|
||||
await persistMetadataState(.manualRetryRequired, metadata: metadata, sessionIdentifier: sessionIdentifier)
|
||||
|
||||
madeProgress = true
|
||||
if authenticationRequired {
|
||||
logError("Stopped background upload after authentication failure for \(metadata.fileName), job: \(jobIdentifier)")
|
||||
} else if retryLimitReached {
|
||||
logError("Stopped background upload after \(maximumBackgroundUploadAttempts) failed attempts for \(metadata.fileName), job: \(jobIdentifier)")
|
||||
} else {
|
||||
logInfo("Stopped background upload because the account queue is suspended for \(metadata.fileName), job: \(jobIdentifier)")
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
let assets = PHAsset.fetchAssets(withLocalIdentifiers: [metadata.assetLocalIdentifier], options: nil)
|
||||
|
||||
guard let asset = assets.firstObject else {
|
||||
guard try acknowledge(job: job, library: library) else {
|
||||
logError("Unable to acknowledge retry job for missing asset \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
await database.deleteMetadataAsync(id: metadata.ocId)
|
||||
madeProgress = true
|
||||
logInfo("Acknowledged retry job and deleted metadata for missing asset \(metadata.assetLocalIdentifier), file: \(metadata.fileName)")
|
||||
continue
|
||||
}
|
||||
|
||||
guard let destination = buildDestination(metadata: metadata, asset: asset) else {
|
||||
logError("Unable to rebuild destination for job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
guard let retryAccount = database.getTableAccount(account: metadata.account),
|
||||
retryAccount.autoUploadStart else { continue }
|
||||
var retryRequested = false
|
||||
|
||||
try library.performChangesAndWait {
|
||||
guard let current = self.database.getTableAccount(account: metadata.account),
|
||||
current.autoUploadStart,
|
||||
current.autoUploadSessionIdentifier == retryAccount.autoUploadSessionIdentifier,
|
||||
let currentMetadata = self.database.getMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)),
|
||||
!currentMetadata.backgroundUploadCancellationRequested else { return }
|
||||
guard let request = PHAssetResourceUploadJobChangeRequest(for: job) else {
|
||||
return
|
||||
}
|
||||
|
||||
request.retry(destination: destination)
|
||||
retryRequested = true
|
||||
}
|
||||
|
||||
guard retryRequested else {
|
||||
logError("Unable to create retry request for job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
// PhotoKit is about to perform the next upload attempt for the same job.
|
||||
await persistMetadataState(
|
||||
.uploading(jobIdentifier: jobIdentifier, incrementRetryCount: true),
|
||||
metadata: metadata
|
||||
)
|
||||
|
||||
if let current = database.getTableAccount(account: metadata.account),
|
||||
!current.autoUploadStart || current.autoUploadSessionIdentifier != retryAccount.autoUploadSessionIdentifier {
|
||||
metadata.backgroundUploadCancellationRequested = true
|
||||
await database.updateBackgroundUploadMetadataAsync(metadata, expectedJobIdentifier: jobIdentifier)
|
||||
_ = try await cancelRequestedUploadJobs()
|
||||
continue
|
||||
}
|
||||
madeProgress = true
|
||||
|
||||
logInfo("Retry requested for \(metadata.fileName), job: \(jobIdentifier)")
|
||||
}
|
||||
|
||||
return madeProgress
|
||||
}
|
||||
|
||||
/// Records terminal job results in Realm before acknowledging them to free PhotoKit capacity.
|
||||
/// Successful uploads are finalized; retryable failures create pending work for a new job.
|
||||
func acknowledgeUploadJobs() async throws -> Bool {
|
||||
let jobs = PHAssetResourceUploadJob.fetchJobs(action: .acknowledge, options: nil)
|
||||
|
||||
guard jobs.count > 0 else {
|
||||
return false
|
||||
}
|
||||
|
||||
let library = PHPhotoLibrary.shared()
|
||||
var madeProgress = false
|
||||
|
||||
for index in 0..<jobs.count {
|
||||
let job = jobs.object(at: index)
|
||||
let jobIdentifier = job.localIdentifier
|
||||
|
||||
guard let metadata = await resolveMetadata(for: job) else {
|
||||
guard try acknowledge(job: job, library: library) else {
|
||||
logError("Unable to acknowledge orphan job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
madeProgress = true
|
||||
|
||||
logInfo("Acknowledged orphan job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
guard !metadata.backgroundUploadCancellationRequested else {
|
||||
logInfo("Skipping normal acknowledgement for cancellation-requested job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
let sessionIdentifier = database.getTableAccount(account: metadata.account)?.autoUploadSessionIdentifier ?? ""
|
||||
let uploadSucceeded: Bool
|
||||
let createNewJob: Bool
|
||||
|
||||
switch job.state {
|
||||
case .succeeded:
|
||||
uploadSucceeded = await processUploadSuccess(metadata: metadata, job: job)
|
||||
if !uploadSucceeded && hasConfirmedUploadResponse(job: job) { continue }
|
||||
createNewJob = false
|
||||
|
||||
case .failed:
|
||||
logUploadJobDiagnostics(job: job, action: "acknowledge")
|
||||
|
||||
if hasConfirmedUploadResponse(job: job) {
|
||||
// A valid oc-fileid takes precedence over PhotoKit's failed state for HTTP 204.
|
||||
uploadSucceeded = await processUploadSuccess(metadata: metadata, job: job)
|
||||
guard uploadSucceeded else { continue }
|
||||
createNewJob = false
|
||||
logInfo("Accepted server-confirmed upload for \(metadata.fileName), job: \(jobIdentifier)")
|
||||
} else {
|
||||
let authenticationRequired = isAuthenticationFailure(job: job)
|
||||
let retryLimitReached = !canAutomaticallyRetry(metadata: metadata)
|
||||
let queueSuspended = preferences.isBackgroundUploadSuspended(account: metadata.account)
|
||||
|
||||
if authenticationRequired {
|
||||
// Invalid credentials affect every file, so suspend the account immediately.
|
||||
preferences.setBackgroundUploadSuspended(true, account: metadata.account)
|
||||
} else if retryLimitReached,
|
||||
!queueSuspended,
|
||||
recordTerminalUploadFailure(metadata: metadata) {
|
||||
logError("Suspended background upload after \(maximumConsecutiveBackgroundUploadFailures) consecutive asset failures for account \(metadata.account)")
|
||||
}
|
||||
|
||||
await updateMetadataForUploadFailure(metadata: metadata, job: job)
|
||||
uploadSucceeded = false
|
||||
createNewJob = !authenticationRequired && !retryLimitReached && !queueSuspended
|
||||
}
|
||||
|
||||
default:
|
||||
logUploadJobDiagnostics(job: job, action: "acknowledge")
|
||||
logError("Unexpected state \(job.state.rawValue) for job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
if uploadSucceeded {
|
||||
// Persist the closed local state first. If acknowledgement is interrupted, the
|
||||
// remaining PhotoKit job is harmless and will be cleaned up as an orphan next time.
|
||||
await persistMetadataState(.completed, metadata: metadata)
|
||||
}
|
||||
|
||||
// The terminal result is now stored locally; acknowledge it to release PhotoKit's job slot.
|
||||
guard try acknowledge(job: job, library: library) else {
|
||||
logError("Unable to acknowledge job \(jobIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
if !uploadSucceeded && createNewJob {
|
||||
// A PhotoKit job can be retried only once; create a fresh job for the remaining attempt.
|
||||
await persistMetadataState(.pendingRetry, metadata: metadata, sessionIdentifier: sessionIdentifier)
|
||||
|
||||
logInfo("Prepared new background upload job for \(metadata.fileName), retry: \(metadata.backgroundUploadRetryCount)")
|
||||
} else if !uploadSucceeded {
|
||||
// `uploadError` prevents automatic scheduling while `pending` enables manual retry.
|
||||
await persistMetadataState(.manualRetryRequired, metadata: metadata, sessionIdentifier: sessionIdentifier)
|
||||
|
||||
logInfo("Background upload requires a manual retry for \(metadata.fileName)")
|
||||
}
|
||||
|
||||
madeProgress = true
|
||||
|
||||
logInfo("Acknowledged job \(jobIdentifier), state: \(job.state.rawValue)")
|
||||
}
|
||||
|
||||
return madeProgress
|
||||
}
|
||||
|
||||
/// Resolves a job through its stored identifier or reconnects it to metadata left pending by an interruption.
|
||||
/// Asset identity narrows the candidates and the destination URL distinguishes Live Photo components.
|
||||
private func resolveMetadata(for job: PHAssetResourceUploadJob) async -> tableMetadata? {
|
||||
if let metadata = await database.getMetadataAsync(backgroundUploadJobIdentifier: job.localIdentifier) {
|
||||
return metadata
|
||||
}
|
||||
|
||||
guard let resource = PHAssetResource.assetResource(forUploadJob: job),
|
||||
let destinationURL = job.destination.url else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let candidates = await database.getPendingBackgroundUploadMetadatasAsync(
|
||||
assetLocalIdentifier: resource.assetLocalIdentifier
|
||||
)
|
||||
let matchingCandidates = candidates.filter { metadata in
|
||||
guard let metadataURL = metadata.serverUrlFileName.encodedToUrl as? URL else {
|
||||
return false
|
||||
}
|
||||
|
||||
return metadataURL == destinationURL
|
||||
}
|
||||
|
||||
guard matchingCandidates.count == 1,
|
||||
let metadata = matchingCandidates.first else {
|
||||
if matchingCandidates.count > 1 {
|
||||
logError("Unable to recover job \(job.localIdentifier): multiple pending metadata match its destination")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PhotoKit committed the job before the previous process could store its identifier in Realm.
|
||||
await persistMetadataState(
|
||||
.uploading(jobIdentifier: job.localIdentifier, incrementRetryCount: false),
|
||||
metadata: metadata
|
||||
)
|
||||
|
||||
logInfo(
|
||||
"Recovered background upload job \(job.localIdentifier), file: \(metadata.fileName), " +
|
||||
"resource: \(resource.filename ?? "<unknown>")"
|
||||
)
|
||||
return await database.getMetadataAsync(backgroundUploadJobIdentifier: job.localIdentifier)
|
||||
}
|
||||
|
||||
/// Resolves the Photos resource represented by a metadata record, including Live Photo components.
|
||||
/// It prefers an exact filename match before falling back to the asset's primary resource type.
|
||||
private func uploadResource(for asset: PHAsset, metadata: tableMetadata) -> PHAssetResource? {
|
||||
let resources = PHAssetResource.assetResources(for: asset)
|
||||
|
||||
if metadata.isLivePhotoVideo {
|
||||
return resources.first {
|
||||
$0.type == .fullSizePairedVideo
|
||||
} ?? resources.first {
|
||||
$0.type == .pairedVideo
|
||||
}
|
||||
}
|
||||
|
||||
if metadata.isLivePhotoImage {
|
||||
return resources.first {
|
||||
$0.type == .fullSizePhoto
|
||||
} ?? resources.first {
|
||||
$0.type == .photo
|
||||
}
|
||||
}
|
||||
|
||||
if let resource = resources.first(where: {
|
||||
$0.filename?.caseInsensitiveCompare(metadata.fileName) == .orderedSame
|
||||
}) {
|
||||
return resource
|
||||
}
|
||||
|
||||
switch asset.mediaType {
|
||||
case .image:
|
||||
return resources.first {
|
||||
$0.type == .fullSizePhoto
|
||||
} ?? resources.first {
|
||||
$0.type == .photo
|
||||
}
|
||||
|
||||
case .video:
|
||||
return resources.first {
|
||||
$0.type == .fullSizeVideo
|
||||
} ?? resources.first {
|
||||
$0.type == .video
|
||||
}
|
||||
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Confirms to PhotoKit that the terminal result has already been persisted and can be discarded.
|
||||
/// Acknowledgement removes the job from the system queue and prevents any further retry for it.
|
||||
/// Returns `false` if PhotoKit cannot create a change request for the supplied job.
|
||||
private func acknowledge(job: PHAssetResourceUploadJob, library: PHPhotoLibrary) throws -> Bool {
|
||||
var acknowledged = false
|
||||
|
||||
try library.performChangesAndWait {
|
||||
guard let request = PHAssetResourceUploadJobChangeRequest(for: job) else {
|
||||
return
|
||||
}
|
||||
|
||||
// This is the actual confirmation to PhotoKit; it is not another server request.
|
||||
request.acknowledge()
|
||||
acknowledged = true
|
||||
}
|
||||
|
||||
return acknowledged
|
||||
}
|
||||
|
||||
/// Requests cancellation of a registered or pending PhotoKit job inside a library transaction.
|
||||
/// Returns `false` if the job is no longer mutable by the time the change block executes.
|
||||
private func cancel(job: PHAssetResourceUploadJob, library: PHPhotoLibrary) throws -> Bool {
|
||||
var cancelled = false
|
||||
|
||||
try library.performChangesAndWait {
|
||||
guard let request = PHAssetResourceUploadJobChangeRequest(for: job) else {
|
||||
return
|
||||
}
|
||||
|
||||
request.cancel()
|
||||
cancelled = true
|
||||
}
|
||||
|
||||
return cancelled
|
||||
}
|
||||
|
||||
/// Computes free PhotoKit capacity by deduplicating jobs exposed through all actionable states.
|
||||
/// The extension intentionally caps its own queue at 20 jobs even if the system limit is higher.
|
||||
func availableUploadJobSlots() -> Int {
|
||||
let actions: [PHAssetResourceUploadJob.Action] = [.process, .retry, .acknowledge]
|
||||
var jobIdentifiers = Set<String>()
|
||||
|
||||
for action in actions {
|
||||
let jobs = PHAssetResourceUploadJob.fetchJobs(action: action, options: nil)
|
||||
|
||||
for index in 0..<jobs.count {
|
||||
jobIdentifiers.insert(jobs.object(at: index).localIdentifier)
|
||||
}
|
||||
}
|
||||
|
||||
let jobLimit = min(PHAssetResourceUploadJob.jobLimit, 20)
|
||||
return max(0, jobLimit - jobIdentifiers.count)
|
||||
}
|
||||
|
||||
/// Reports whether PhotoKit still exposes jobs requiring processing, retry, or acknowledgement.
|
||||
/// This keeps the extension scheduled while system-managed upload work remains outstanding.
|
||||
func hasActiveUploadJobs() -> Bool {
|
||||
PHAssetResourceUploadJob.fetchJobs(action: .process, options: nil).count > 0 ||
|
||||
PHAssetResourceUploadJob.fetchJobs(action: .retry, options: nil).count > 0 ||
|
||||
PHAssetResourceUploadJob.fetchJobs(action: .acknowledge, options: nil).count > 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import NextcloudKit
|
||||
|
||||
extension BackgroundUploadExtension {
|
||||
/// Links up to ten fully uploaded Live Photo pairs without letting one failed pair block the others.
|
||||
/// Failed records remain in Realm so a later extension run or the host app can retry safely.
|
||||
func processPendingLivePhotos(account: String) async -> Bool {
|
||||
let livePhotos = await database.getLivePhotos(account: account, limit: 10)
|
||||
var madeProgress = false
|
||||
|
||||
for livePhoto in livePhotos {
|
||||
if await linkLivePhoto(livePhoto, account: account) {
|
||||
madeProgress = true
|
||||
}
|
||||
|
||||
// An authentication failure affects the whole account; avoid repeating it for the batch.
|
||||
if preferences.isBackgroundUploadSuspended(account: account) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return madeProgress
|
||||
}
|
||||
|
||||
/// Links both server resources and removes the pending record only after both calls succeed.
|
||||
private func linkLivePhoto(_ livePhoto: tableLivePhoto, account: String) async -> Bool {
|
||||
let videoResult = await NextcloudKit.shared.setLivephotoAsync(
|
||||
serverUrlfileNamePath: livePhoto.serverUrlFileNameVideo,
|
||||
livePhotoFile: livePhoto.fileIdImage,
|
||||
account: account
|
||||
)
|
||||
|
||||
guard videoResult.error == .success else {
|
||||
return await handleLivePhotoLinkFailure(
|
||||
livePhoto,
|
||||
component: "video",
|
||||
path: livePhoto.serverUrlFileNameVideo,
|
||||
error: videoResult.error,
|
||||
account: account
|
||||
)
|
||||
}
|
||||
|
||||
let imageResult = await NextcloudKit.shared.setLivephotoAsync(
|
||||
serverUrlfileNamePath: livePhoto.serverUrlFileNameImage,
|
||||
livePhotoFile: livePhoto.fileIdVideo,
|
||||
account: account
|
||||
)
|
||||
|
||||
guard imageResult.error == .success else {
|
||||
return await handleLivePhotoLinkFailure(
|
||||
livePhoto,
|
||||
component: "image",
|
||||
path: livePhoto.serverUrlFileNameImage,
|
||||
error: imageResult.error,
|
||||
account: account
|
||||
)
|
||||
}
|
||||
|
||||
await database.setLivePhotoFile(
|
||||
fileId: livePhoto.fileIdVideo,
|
||||
livePhotoFile: livePhoto.fileIdImage
|
||||
)
|
||||
await database.setLivePhotoFile(
|
||||
fileId: livePhoto.fileIdImage,
|
||||
livePhotoFile: livePhoto.fileIdVideo
|
||||
)
|
||||
await database.deleteLivePhoto(
|
||||
account: account,
|
||||
serverUrlFileNameNoExt: livePhoto.serverUrlFileNameNoExt
|
||||
)
|
||||
|
||||
logInfo(
|
||||
"Linked Live Photo \(livePhoto.serverUrlFileNameImage) with " +
|
||||
"\(livePhoto.serverUrlFileNameVideo)"
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
/// Removes pairs whose server resource no longer exists and retains transient failures for retry.
|
||||
/// Authentication errors suspend the account immediately to avoid repeating invalid requests.
|
||||
private func handleLivePhotoLinkFailure(
|
||||
_ livePhoto: tableLivePhoto,
|
||||
component: String,
|
||||
path: String,
|
||||
error: NKError,
|
||||
account: String
|
||||
) async -> Bool {
|
||||
if error.errorCode == global.errorResourceNotFound {
|
||||
await database.deleteLivePhoto(
|
||||
account: account,
|
||||
serverUrlFileNameNoExt: livePhoto.serverUrlFileNameNoExt
|
||||
)
|
||||
logError("Discarded Live Photo because its \(component) resource no longer exists: \(path)")
|
||||
return true
|
||||
}
|
||||
|
||||
await database.setLivePhotoError(
|
||||
account: account,
|
||||
serverUrlFileNameNoExt: livePhoto.serverUrlFileNameNoExt
|
||||
)
|
||||
|
||||
if error.errorCode == global.errorUnauthorized {
|
||||
preferences.setBackgroundUploadSuspended(true, account: account)
|
||||
logError("Suspended background upload after a Live Photo authentication failure for account \(account)")
|
||||
}
|
||||
|
||||
logError("Unable to link Live Photo \(component) \(path), error: \(error.logDescription)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import Photos
|
||||
import NextcloudKit
|
||||
|
||||
extension BackgroundUploadExtension {
|
||||
/// Reports whether another automatic upload attempt is available for the metadata.
|
||||
/// The stored retry count excludes the initial upload, so the limit reserves one attempt for it.
|
||||
func canAutomaticallyRetry(metadata: tableMetadata) -> Bool {
|
||||
metadata.backgroundUploadRetryCount < maximumBackgroundUploadAttempts - 1
|
||||
}
|
||||
|
||||
/// Records a terminal asset failure and suspends the account after three distinct failures.
|
||||
/// Returns `true` when this failure opens the account-level circuit breaker.
|
||||
@discardableResult
|
||||
func recordTerminalUploadFailure(metadata: tableMetadata) -> Bool {
|
||||
let assetIdentifier = metadata.assetLocalIdentifier.isEmpty ? metadata.ocIdTransfer : metadata.assetLocalIdentifier
|
||||
let failureCount = preferences.recordBackgroundUploadFailure(
|
||||
account: metadata.account,
|
||||
assetIdentifier: assetIdentifier
|
||||
)
|
||||
let shouldSuspend = failureCount >= maximumConsecutiveBackgroundUploadFailures
|
||||
|
||||
if shouldSuspend {
|
||||
preferences.setBackgroundUploadSuspended(true, account: metadata.account)
|
||||
}
|
||||
|
||||
return shouldSuspend
|
||||
}
|
||||
|
||||
/// Detects authentication failures from normalized response headers or the sanitized URL error.
|
||||
/// The shared classification keeps retry and acknowledgement behavior consistent.
|
||||
func isAuthenticationFailure(job: PHAssetResourceUploadJob) -> Bool {
|
||||
let error = job.error.map { $0 as NSError }
|
||||
|
||||
return job.responseHeaderFields?["www-authenticate"] != nil ||
|
||||
(error?.domain == NSURLErrorDomain && error?.code == URLError.userAuthenticationRequired.rawValue)
|
||||
}
|
||||
|
||||
/// Treats a valid Nextcloud file identifier as proof that the server committed the upload.
|
||||
/// This covers successful overwrites that PhotoKit may expose as failed after an HTTP 204 response.
|
||||
func hasConfirmedUploadResponse(job: PHAssetResourceUploadJob) -> Bool {
|
||||
guard let ocId = job.responseHeaderFields?["oc-fileid"] else {
|
||||
return false
|
||||
}
|
||||
|
||||
return !ocId.isEmpty
|
||||
}
|
||||
|
||||
/// Logs the diagnostic values PhotoKit exposes for a failed or otherwise unexpected upload job.
|
||||
/// Request headers are excluded and sensitive response header values are redacted.
|
||||
func logUploadJobDiagnostics(job: PHAssetResourceUploadJob, action: String) {
|
||||
let error = job.error.map { $0 as NSError }
|
||||
let sensitiveHeaderNames = Set(["authorization", "cookie", "proxy-authorization", "set-cookie"])
|
||||
let responseHeaders = job.responseHeaderFields?.reduce(into: [String: String]()) { result, header in
|
||||
result[header.key] = sensitiveHeaderNames.contains(header.key.lowercased())
|
||||
? "<redacted>"
|
||||
: header.value
|
||||
} ?? [:]
|
||||
let state: String
|
||||
let type: String
|
||||
|
||||
switch job.state {
|
||||
case .registered:
|
||||
state = "registered"
|
||||
case .pending:
|
||||
state = "pending"
|
||||
case .failed:
|
||||
state = "failed"
|
||||
case .succeeded:
|
||||
state = "succeeded"
|
||||
case .cancelled:
|
||||
state = "cancelled"
|
||||
@unknown default:
|
||||
state = "unknown"
|
||||
}
|
||||
|
||||
switch job.type {
|
||||
case .upload:
|
||||
type = "upload"
|
||||
case .downloadOnly:
|
||||
type = "downloadOnly"
|
||||
@unknown default:
|
||||
type = "unknown"
|
||||
}
|
||||
|
||||
var destinationComponents = job.destination.url.flatMap {
|
||||
URLComponents(url: $0, resolvingAgainstBaseURL: false)
|
||||
}
|
||||
destinationComponents?.user = nil
|
||||
destinationComponents?.password = nil
|
||||
destinationComponents?.query = nil
|
||||
destinationComponents?.fragment = nil
|
||||
|
||||
logInfo(
|
||||
"PhotoKit job diagnostics, action: \(action), job: \(job.localIdentifier), " +
|
||||
"state: \(state) (\(job.state.rawValue)), type: \(type) (\(job.type.rawValue)), " +
|
||||
"method: \(job.destination.httpMethod ?? "<nil>"), " +
|
||||
"destination: \(destinationComponents?.string ?? "<nil>"), " +
|
||||
"error domain: \(error?.domain ?? "<nil>"), code: \(error?.code ?? 0), " +
|
||||
"description: \(error?.localizedDescription ?? "<nil>"), " +
|
||||
"failure reason: \(error?.localizedFailureReason ?? "<nil>"), " +
|
||||
"recovery suggestion: \(error?.localizedRecoverySuggestion ?? "<nil>"), " +
|
||||
"userInfo: \(error?.userInfo ?? [:]), headers: \(responseHeaders)"
|
||||
)
|
||||
}
|
||||
|
||||
/// Stores the terminal upload error and resets transient task state on the associated metadata.
|
||||
/// Authentication failures receive a stable error code so the host app can require manual retry.
|
||||
func updateMetadataForUploadFailure(metadata: tableMetadata, job: PHAssetResourceUploadJob) async {
|
||||
let error: NKError
|
||||
|
||||
if isAuthenticationFailure(job: job) {
|
||||
error = NKError(errorCode: NSURLErrorUserAuthenticationRequired, errorDescription: "Authentication required for account \(metadata.user)")
|
||||
} else if let jobError = job.error {
|
||||
error = NKError(error: jobError)
|
||||
} else {
|
||||
error = NKError(errorCode: NSURLErrorUnknown, errorDescription: "Background upload failed")
|
||||
}
|
||||
|
||||
await persistMetadataState(.failed(error), metadata: metadata)
|
||||
|
||||
logError("Background upload failed for \(metadata.fileName), account: \(metadata.account), job: \(job.localIdentifier), error: \(error.logDescription)")
|
||||
}
|
||||
|
||||
/// Applies Nextcloud response metadata and records the asset as successfully auto-uploaded.
|
||||
/// A missing `oc-fileid` converts the result to an upload error and requires manual recovery.
|
||||
func processUploadSuccess(metadata: tableMetadata, job: PHAssetResourceUploadJob) async -> Bool {
|
||||
let succeeded = await NCBackgroundUploadExtensionManager.shared.recordUploadSuccess(metadata: metadata, job: job)
|
||||
if !succeeded, !hasConfirmedUploadResponse(job: job) {
|
||||
await persistMetadataState(
|
||||
.failed(NKError(errorCode: NSURLErrorBadServerResponse, errorDescription: "Upload response missing oc-fileid")),
|
||||
metadata: metadata
|
||||
)
|
||||
}
|
||||
return succeeded
|
||||
}
|
||||
|
||||
/// Applies a complete background-upload state transition and persists it in Realm.
|
||||
/// Keeping related fields together prevents partially configured metadata between processing stages.
|
||||
func persistMetadataState(_ state: MetadataState, metadata: tableMetadata, sessionIdentifier: String? = nil) async {
|
||||
let expectedJobIdentifier = metadata.backgroundUploadJobIdentifier
|
||||
switch state {
|
||||
case let .uploading(jobIdentifier, incrementRetryCount):
|
||||
if incrementRetryCount, metadata.backgroundUploadRetryCount < Int.max {
|
||||
metadata.backgroundUploadRetryCount += 1
|
||||
}
|
||||
|
||||
metadata.backgroundUploadJobIdentifier = jobIdentifier
|
||||
metadata.backgroundUploadNextRetryDate = nil
|
||||
metadata.sessionDate = Date()
|
||||
metadata.sessionError = ""
|
||||
metadata.errorCode = 0
|
||||
metadata.errorKind = ""
|
||||
metadata.status = global.metadataStatusUploading
|
||||
|
||||
case .pendingRetry:
|
||||
if metadata.backgroundUploadRetryCount < Int.max {
|
||||
metadata.backgroundUploadRetryCount += 1
|
||||
}
|
||||
|
||||
metadata.backgroundUploadJobIdentifier = "pending"
|
||||
metadata.backgroundUploadNextRetryDate = nil
|
||||
metadata.sessionTaskIdentifier = 0
|
||||
metadata.sessionDate = Date()
|
||||
metadata.status = global.metadataStatusWaitUpload
|
||||
|
||||
case .manualRetryRequired:
|
||||
metadata.backgroundUploadJobIdentifier = "pending"
|
||||
metadata.backgroundUploadNextRetryDate = nil
|
||||
|
||||
case let .failed(error):
|
||||
metadata.sessionTaskIdentifier = 0
|
||||
metadata.sessionDate = Date()
|
||||
metadata.sessionError = error.errorDescription
|
||||
metadata.errorCode = error.errorCode
|
||||
metadata.errorKind = error.kind?.rawValue ?? ""
|
||||
metadata.status = global.metadataStatusUploadError
|
||||
|
||||
case .completed:
|
||||
metadata.chunk = 0
|
||||
metadata.sceneIdentifier = nil
|
||||
metadata.session = ""
|
||||
metadata.sessionError = ""
|
||||
metadata.errorKind = ""
|
||||
metadata.sessionDate = nil
|
||||
metadata.sessionTaskIdentifier = 0
|
||||
metadata.status = global.metadataStatusNormal
|
||||
metadata.backgroundUploadJobIdentifier = ""
|
||||
metadata.backgroundUploadRetryCount = 0
|
||||
metadata.backgroundUploadNextRetryDate = nil
|
||||
}
|
||||
|
||||
await database.updateBackgroundUploadMetadataAsync(metadata, expectedJobIdentifier: expectedJobIdentifier, sessionIdentifier: sessionIdentifier)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import ExtensionFoundation
|
||||
import Photos
|
||||
import NextcloudKit
|
||||
import OSLog
|
||||
|
||||
@main
|
||||
final class BackgroundUploadExtension: PHBackgroundResourceUploadJobExtension {
|
||||
private actor ProcessingCoordinator {
|
||||
private var isProcessing = false
|
||||
|
||||
/// Claims the processing pass, or returns false when another invocation already owns it.
|
||||
func beginProcessing() -> Bool {
|
||||
guard !isProcessing else { return false }
|
||||
|
||||
isProcessing = true
|
||||
return true
|
||||
}
|
||||
|
||||
/// Releases the processing pass after every success or handled failure.
|
||||
func endProcessing() {
|
||||
isProcessing = false
|
||||
}
|
||||
}
|
||||
|
||||
private static let processingCoordinator = ProcessingCoordinator()
|
||||
|
||||
enum MetadataState: Sendable {
|
||||
case uploading(jobIdentifier: String, incrementRetryCount: Bool)
|
||||
case pendingRetry
|
||||
case manualRetryRequired
|
||||
case failed(NKError)
|
||||
case completed
|
||||
}
|
||||
|
||||
let global = NCGlobal.shared
|
||||
let database = NCManageDatabase.shared
|
||||
let utilityFileSystem = NCUtilityFileSystem()
|
||||
let nkComm = NextcloudKit.shared.nkCommonInstance
|
||||
let preferences = NCPreferences()
|
||||
let logger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "BackgroundUploadExtension", category: NCGlobal.shared.logTagBackgroundUpload)
|
||||
// One initial upload followed by at most two automatic retry attempts.
|
||||
let maximumBackgroundUploadAttempts = 3
|
||||
// Suspend the account after this many distinct assets fail without an intervening success.
|
||||
let maximumConsecutiveBackgroundUploadFailures = 3
|
||||
private let isDatabaseAvailable: Bool
|
||||
|
||||
/// Opens the shared Realm database and configures NextcloudKit for extension use.
|
||||
/// A schema mismatch is retained as initialization state so job processing can fail safely.
|
||||
required init() {
|
||||
NextcloudKit.configureLogger(
|
||||
logLevel: NCBrandOptions.shared.disable_log ? .disabled : NCPreferences().log,
|
||||
logDirectory: NCPreferences.sharedLogDirectory
|
||||
)
|
||||
NextcloudKit.shared.setup(groupIdentifier: NCBrandOptions.shared.capabilitiesGroup)
|
||||
isDatabaseAvailable = NCManageDatabase.shared.openRealm()
|
||||
|
||||
if isDatabaseAvailable {
|
||||
logInfo("BackgroundUploadExtension initialized, bundle: \(Bundle.main.bundleIdentifier ?? "<nil>")")
|
||||
} else {
|
||||
logError("BackgroundUploadExtension initialization stopped because the database schema version does not match")
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconciles cancellations, retries, completed jobs, and newly discovered assets in that order.
|
||||
/// Returns whether PhotoKit should continue processing, stop, or report an unrecoverable failure.
|
||||
func processJobs() async -> PHBackgroundResourceUploadProcessingResult {
|
||||
defer { NextcloudKit.flushLogger() }
|
||||
|
||||
guard isDatabaseAvailable else {
|
||||
return .failure
|
||||
}
|
||||
|
||||
guard await Self.processingCoordinator.beginProcessing() else {
|
||||
logInfo("processJobs skipped because another invocation is active")
|
||||
return .processing
|
||||
}
|
||||
|
||||
let result = await processJobsPass()
|
||||
await Self.processingCoordinator.endProcessing()
|
||||
return result
|
||||
}
|
||||
|
||||
/// Performs one exclusive reconciliation pass after the shared coordinator grants ownership.
|
||||
private func processJobsPass() async -> PHBackgroundResourceUploadProcessingResult {
|
||||
|
||||
logInfo("processJobs begin")
|
||||
|
||||
let account = await setupAccount()
|
||||
var processingStage = "cancelRequestedUploadJobs"
|
||||
|
||||
do {
|
||||
var madeProgress = false
|
||||
|
||||
// Remove jobs cancelled by the user and clean up PhotoKit jobs no longer backed by metadata.
|
||||
if try await cancelRequestedUploadJobs() {
|
||||
madeProgress = true
|
||||
}
|
||||
|
||||
// Inspect jobs offered for retry; confirmed uploads are acknowledged without uploading again.
|
||||
processingStage = "processRetryableUploadJobs"
|
||||
if try await processRetryableUploadJobs() {
|
||||
madeProgress = true
|
||||
}
|
||||
|
||||
// Persist terminal upload results before acknowledging them and releasing PhotoKit capacity.
|
||||
processingStage = "acknowledgeUploadJobs"
|
||||
if try await acknowledgeUploadJobs() {
|
||||
madeProgress = true
|
||||
}
|
||||
|
||||
if let account {
|
||||
// Link completed Live Photo pairs unless a previous failure suspended the account queue.
|
||||
if !preferences.isBackgroundUploadSuspended(account: account.account) {
|
||||
processingStage = "processPendingLivePhotos"
|
||||
if await processPendingLivePhotos(account: account.account) {
|
||||
madeProgress = true
|
||||
}
|
||||
}
|
||||
|
||||
if preferences.isBackgroundUploadSuspended(account: account.account) {
|
||||
logInfo("Background upload queue is suspended for account \(account.account)")
|
||||
} else {
|
||||
// Register metadata already waiting in Realm before discovering more Photos assets.
|
||||
processingStage = "createUploadJobs(existing metadata)"
|
||||
if try await createUploadJobs(account: account) {
|
||||
madeProgress = true
|
||||
}
|
||||
|
||||
// Fill only the remaining PhotoKit slots so discovery stays bounded for large libraries.
|
||||
let availableJobs = availableUploadJobSlots()
|
||||
|
||||
if availableJobs > 0,
|
||||
await createPendingMetadatas(account: account, limit: availableJobs) {
|
||||
madeProgress = true
|
||||
|
||||
// Convert the metadata just discovered into executable PhotoKit upload jobs.
|
||||
processingStage = "createUploadJobs(new metadata)"
|
||||
if try await createUploadJobs(account: account) {
|
||||
madeProgress = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the extension scheduled while this pass progressed or PhotoKit still owns active jobs.
|
||||
let hasActiveJobs = hasActiveUploadJobs()
|
||||
let result: PHBackgroundResourceUploadProcessingResult = madeProgress || hasActiveJobs ? .processing : .completed
|
||||
|
||||
logInfo("processJobs end, madeProgress: \(madeProgress), hasActiveJobs: \(hasActiveJobs)")
|
||||
return result
|
||||
} catch let error as NSError where error.domain == PHPhotosErrorDomain && error.code == PHPhotosError.limitExceeded.rawValue {
|
||||
logInfo("Job limit reached during \(processingStage)")
|
||||
return .processing
|
||||
} catch {
|
||||
let error = error as NSError
|
||||
logError("processJobs error during \(processingStage): " + "domain: \(error.domain), code: \(error.code), " + "description: \(error.localizedDescription), userInfo: \(error.userInfo)")
|
||||
return .failure
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives the PhotoKit notification that the extension process is about to terminate.
|
||||
/// It currently records the lifecycle event without interrupting an active processing pass.
|
||||
func willTerminate() async {
|
||||
logInfo("BackgroundUploadExtension will terminate")
|
||||
NextcloudKit.flushLogger()
|
||||
}
|
||||
|
||||
/// Writes an informational message to unified logging and the persistent shared log.
|
||||
func logInfo(_ message: String) {
|
||||
logger.notice("\(message, privacy: .public)")
|
||||
nkLog(tag: global.logTagBackgroundUpload, emoji: .info, message: message)
|
||||
}
|
||||
|
||||
/// Writes an error to unified logging and to the persistent Nextcloud log.
|
||||
/// Use this for failures that require later diagnosis from the host app.
|
||||
func logError(_ message: String) {
|
||||
logger.error("\(message, privacy: .public)")
|
||||
nkLog(tag: global.logTagBackgroundUpload, emoji: .error, message: message)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import Photos
|
||||
import NextcloudKit
|
||||
|
||||
@available(iOS 27, *)
|
||||
final class NCBackgroundUploadExtensionManager {
|
||||
static let shared = NCBackgroundUploadExtensionManager()
|
||||
|
||||
private let database = NCManageDatabase.shared
|
||||
private let global = NCGlobal.shared
|
||||
|
||||
/// Creates the shared host-app manager used to control the PhotoKit extension state.
|
||||
/// Callers access this instance through `shared` so enable and disable decisions stay centralized.
|
||||
private init() {}
|
||||
|
||||
/// Checks whether device authorization, app settings, account state, and server version allow delegation.
|
||||
/// This method evaluates eligibility only and does not change the PhotoKit extension state.
|
||||
func shouldUseExtension() async -> Bool {
|
||||
guard PHPhotoLibrary.authorizationStatus(for: .readWrite) == .authorized else {
|
||||
return false
|
||||
}
|
||||
|
||||
guard NCPreferences().shouldUseBackgroundUploadExtension else {
|
||||
return false
|
||||
}
|
||||
|
||||
guard let account = await database.getTableAccountAsync(predicate: NSPredicate(format: "autoUploadStart == true")) else {
|
||||
return false
|
||||
}
|
||||
|
||||
let capabilities = await NKCapabilities.shared.getCapabilities(for: account.account)
|
||||
|
||||
guard NCBrandOptions.shared.isServerVersion(capabilities, greaterOrEqualTo: .v35) else {
|
||||
nkLog(tag: global.logTagBackgroundUpload, message: "Background upload extension unavailable for account \(account.account): server version is lower than 35")
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/// Enables the PhotoKit upload extension when eligible and refreshes its network options if active.
|
||||
/// Returns the resulting PhotoKit enabled state, or `false` when eligibility or configuration fails.
|
||||
func ensureEnabled() async -> Bool {
|
||||
guard NCPreferences().shouldUseBackgroundUploadExtension else {
|
||||
_ = await disableIfIdle()
|
||||
return false
|
||||
}
|
||||
|
||||
guard await shouldUseExtension() else {
|
||||
return false
|
||||
}
|
||||
|
||||
let library = PHPhotoLibrary.shared()
|
||||
let options = PHAssetResourceUploadJobOptions()
|
||||
// Per-request settings still enforce Wi-Fi-only uploads where configured by the account.
|
||||
options.preventsExpensiveNetworkAccess = false
|
||||
|
||||
do {
|
||||
if library.uploadJobExtensionEnabled {
|
||||
try library.setUploadJobExtensionOptions(options)
|
||||
} else {
|
||||
try library.enableUploadJobExtension(with: options)
|
||||
}
|
||||
|
||||
nkLog(tag: global.logTagBackgroundUpload, message: "Background upload extension enabled: \(library.uploadJobExtensionEnabled)")
|
||||
logUploadJobSnapshot()
|
||||
return library.uploadJobExtensionEnabled
|
||||
} catch {
|
||||
nkLog(tag: global.logTagBackgroundUpload, message: "Background upload extension enable failed: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads PhotoKit's actionable jobs without changing their state or requesting another upload.
|
||||
/// Pending jobs are outstanding work, not evidence that data is currently being transferred.
|
||||
private func logUploadJobSnapshot() {
|
||||
let actions: [(PHAssetResourceUploadJob.Action, String)] = [
|
||||
(.process, "process"),
|
||||
(.retry, "retry"),
|
||||
(.acknowledge, "acknowledge")
|
||||
]
|
||||
var jobIdentifiers = Set<String>()
|
||||
|
||||
for (action, actionName) in actions {
|
||||
let jobs = PHAssetResourceUploadJob.fetchJobs(action: action, options: nil)
|
||||
nkLog(tag: global.logTagBackgroundUpload, message: "PhotoKit queue snapshot, action: \(actionName), count: \(jobs.count)")
|
||||
|
||||
for index in 0..<jobs.count {
|
||||
let job = jobs.object(at: index)
|
||||
jobIdentifiers.insert(job.localIdentifier)
|
||||
let state: String
|
||||
|
||||
switch job.state {
|
||||
case .registered:
|
||||
state = "registered"
|
||||
case .pending:
|
||||
state = "pending"
|
||||
case .failed:
|
||||
state = "failed"
|
||||
case .succeeded:
|
||||
state = "succeeded"
|
||||
case .cancelled:
|
||||
state = "cancelled"
|
||||
@unknown default:
|
||||
state = "unknown"
|
||||
}
|
||||
|
||||
let error = job.error.map { $0 as NSError }
|
||||
nkLog(
|
||||
tag: global.logTagBackgroundUpload,
|
||||
message: "PhotoKit queue job, action: \(actionName), job: \(job.localIdentifier), " +
|
||||
"state: \(state) (\(job.state.rawValue)), type: \(job.type.rawValue), " +
|
||||
"error domain: \(error?.domain ?? "<nil>"), code: \(error?.code ?? 0)"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
nkLog(tag: global.logTagBackgroundUpload, message: "PhotoKit queue snapshot, unique jobs: \(jobIdentifiers.count)")
|
||||
}
|
||||
|
||||
func recordUploadSuccess(metadata: tableMetadata, job: PHAssetResourceUploadJob) async -> Bool {
|
||||
let nkComm = NextcloudKit.shared.nkCommonInstance
|
||||
let preferences = NCPreferences()
|
||||
let headers = job.responseHeaderFields ?? [:]
|
||||
|
||||
guard let ocId = headers["oc-fileid"], !ocId.isEmpty else {
|
||||
// A successful response without Nextcloud metadata is a server-level compatibility error.
|
||||
preferences.setBackgroundUploadSuspended(true, account: metadata.account)
|
||||
|
||||
logUploadMessage("Successful job without oc-fileid: \(job.localIdentifier)")
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
do {
|
||||
let sessionIdentifier = database.getTableAccount(account: metadata.account)?.autoUploadSessionIdentifier
|
||||
guard try await NCLocalDatabase.shared.recordAutoUploadTransfer(metadata, sessionIdentifier: sessionIdentifier, uploaded: true) else { return false }
|
||||
} catch {
|
||||
// Keep the terminal PhotoKit job available until its success is durably recorded.
|
||||
logUploadMessage("Unable to persist background upload completion: \(error)")
|
||||
return false
|
||||
}
|
||||
|
||||
// Any confirmed upload breaks the sequence of consecutive asset failures.
|
||||
preferences.resetBackgroundUploadConsecutiveFailures(account: metadata.account)
|
||||
|
||||
let etag = nkComm.normalizedETag(
|
||||
headers["oc-etag"] ?? headers["etag"]
|
||||
)
|
||||
|
||||
let date = headers["date"]?.parsedDate(
|
||||
using: "EEE, dd MMM y HH:mm:ss zzz"
|
||||
)
|
||||
|
||||
let ownerId = headers["x-nc-ownerid"]
|
||||
let permissions = headers["x-nc-permissions"]
|
||||
|
||||
metadata.uploadDate = (date as? NSDate) ?? NSDate()
|
||||
metadata.etag = etag ?? ""
|
||||
metadata.ocId = ocId
|
||||
|
||||
if let fileId = NCUtility().ocIdToFileId(ocId: ocId) {
|
||||
metadata.fileId = fileId
|
||||
}
|
||||
|
||||
if let ownerId, !ownerId.isEmpty {
|
||||
metadata.ownerId = ownerId
|
||||
if let ownerDisplayName = await NCManageDatabase.shared.getOwnerDisplayName(account: metadata.account, ownerId: ownerId) {
|
||||
metadata.ownerDisplayName = ownerDisplayName
|
||||
}
|
||||
}
|
||||
|
||||
if let permissions, !permissions.isEmpty {
|
||||
metadata.permissions = permissions
|
||||
}
|
||||
|
||||
await database.replaceMetadataAsync(ocId: metadata.ocIdTransfer, metadata: metadata)
|
||||
|
||||
if metadata.isLivePhoto,
|
||||
let capabilities = await database.getCapabilities(account: metadata.account),
|
||||
capabilities.isLivePhotoServerAvailable {
|
||||
await database.setLivePhotoVideo(
|
||||
account: metadata.account,
|
||||
serverUrlFileName: metadata.serverUrlFileName,
|
||||
fileId: metadata.fileId,
|
||||
classFile: metadata.classFile
|
||||
)
|
||||
}
|
||||
|
||||
do {
|
||||
try await NCLocalDatabase.shared.recordPhotoLibraryAssetUpload(
|
||||
account: metadata.account,
|
||||
assetLocalIdentifier: metadata.assetLocalIdentifier,
|
||||
classFile: metadata.classFile,
|
||||
isLivePhoto: metadata.isLivePhoto,
|
||||
creationDate: metadata.creationDate as Date
|
||||
)
|
||||
} catch {
|
||||
// The server upload remains successful even if its local PhotoKit state cannot be recorded.
|
||||
logUploadMessage("Unable to record uploaded photo library asset \(metadata.assetLocalIdentifier): \(error)")
|
||||
}
|
||||
|
||||
logUploadMessage("Completed background upload for \(metadata.fileName), job: \(job.localIdentifier), ocId: \(ocId)")
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
private func logUploadMessage(_ message: String) {
|
||||
nkLog(tag: global.logTagBackgroundUpload, message: message)
|
||||
}
|
||||
|
||||
/// Drains this account's jobs immediately; successful uploads are recorded before acknowledgement.
|
||||
func cancelUploads(account: String) async {
|
||||
defer { NextcloudKit.flushLogger() }
|
||||
let library = PHPhotoLibrary.shared()
|
||||
let actions: [PHAssetResourceUploadJob.Action] = [.process, .retry, .acknowledge]
|
||||
var handled = Set<String>()
|
||||
for action in actions {
|
||||
let jobs = PHAssetResourceUploadJob.fetchJobs(action: action, options: nil)
|
||||
for index in 0..<jobs.count {
|
||||
let job = jobs.object(at: index)
|
||||
guard handled.insert(job.localIdentifier).inserted,
|
||||
let metadata = await database.getMetadataAsync(backgroundUploadJobIdentifier: job.localIdentifier),
|
||||
metadata.account == account,
|
||||
metadata.backgroundUploadCancellationRequested else { continue }
|
||||
|
||||
let confirmed = !(job.responseHeaderFields?["oc-fileid"] ?? "").isEmpty
|
||||
if confirmed {
|
||||
guard await recordUploadSuccess(metadata: metadata, job: job) else { continue }
|
||||
metadata.status = global.metadataStatusNormal
|
||||
metadata.session = ""
|
||||
metadata.sessionTaskIdentifier = 0
|
||||
metadata.sessionDate = nil
|
||||
metadata.sessionError = ""
|
||||
metadata.errorCode = 0
|
||||
metadata.errorKind = ""
|
||||
metadata.chunk = 0
|
||||
metadata.sceneIdentifier = nil
|
||||
metadata.backgroundUploadRetryCount = 0
|
||||
metadata.backgroundUploadNextRetryDate = nil
|
||||
await database.replaceMetadataAsync(ocId: metadata.ocIdTransfer, metadata: metadata)
|
||||
} else if job.state == .succeeded {
|
||||
// Keep an unverified success recoverable instead of silently losing its result.
|
||||
logUploadMessage("Stop deferred for successful job without oc-fileid: \(job.localIdentifier)")
|
||||
continue
|
||||
}
|
||||
|
||||
do {
|
||||
var changed = false
|
||||
try library.performChangesAndWait {
|
||||
guard let request = PHAssetResourceUploadJobChangeRequest(for: job) else { return }
|
||||
if job.state == .registered || job.state == .pending {
|
||||
request.cancel()
|
||||
} else {
|
||||
request.acknowledge()
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
guard changed else { continue }
|
||||
if confirmed {
|
||||
metadata.backgroundUploadJobIdentifier = ""
|
||||
metadata.backgroundUploadCancellationRequested = false
|
||||
await database.replaceMetadataAsync(ocId: metadata.ocIdTransfer, metadata: metadata)
|
||||
} else {
|
||||
await database.deleteMetadataAsync(id: metadata.ocId)
|
||||
}
|
||||
logUploadMessage("Stopped background upload job: \(job.localIdentifier)")
|
||||
} catch {
|
||||
logUploadMessage("Unable to stop background upload job \(job.localIdentifier): \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = await disableIfIdle()
|
||||
}
|
||||
|
||||
/// Includes queued jobs and terminal results still waiting for acknowledgement.
|
||||
func hasOutstandingUploadJobs() -> Bool {
|
||||
let actions: [PHAssetResourceUploadJob.Action] = [.process, .retry, .acknowledge]
|
||||
return actions.contains { PHAssetResourceUploadJob.fetchJobs(action: $0, options: nil).count > 0 }
|
||||
}
|
||||
|
||||
/// Disables the PhotoKit extension after the feature or auto upload is turned off and no jobs remain.
|
||||
/// Active metadata defers disabling so cancellations and terminal results can still be reconciled.
|
||||
func disableIfIdle() async -> Bool {
|
||||
let featureEnabled = NCPreferences().shouldUseBackgroundUploadExtension
|
||||
let account = await database.getTableAccountAsync(predicate: NSPredicate(format: "autoUploadStart == true"))
|
||||
|
||||
guard !featureEnabled || account == nil else {
|
||||
return false
|
||||
}
|
||||
|
||||
let predicate = NSPredicate(format: "sessionSelector == %@ AND backgroundUploadJobIdentifier != ''", global.selectorUploadAutoUpload)
|
||||
let metadatas: [tableMetadata] = await database.getMetadatasAsync(predicate: predicate)
|
||||
|
||||
guard metadatas.isEmpty, !hasOutstandingUploadJobs() else {
|
||||
nkLog(tag: global.logTagBackgroundUpload, message: "Background upload extension disable deferred: metadata or PhotoKit jobs still active")
|
||||
return false
|
||||
}
|
||||
|
||||
let library = PHPhotoLibrary.shared()
|
||||
|
||||
guard library.uploadJobExtensionEnabled else {
|
||||
return true
|
||||
}
|
||||
|
||||
do {
|
||||
try library.disableUploadJobExtension()
|
||||
nkLog(tag: global.logTagBackgroundUpload, message: "Background upload extension disabled")
|
||||
return !library.uploadJobExtensionEnabled
|
||||
} catch {
|
||||
nkLog(tag: global.logTagBackgroundUpload, message: "Background upload extension disable failed: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import NextcloudKit
|
||||
import RealmSwift
|
||||
import OSLog
|
||||
|
||||
final class NCManageDatabase {
|
||||
static let shared = NCManageDatabase()
|
||||
|
||||
internal let core: NCManageDatabaseCore
|
||||
internal let databaseURL: URL?
|
||||
private let logger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "BackgroundUploadExtension", category: NCGlobal.shared.logTagBackgroundUpload)
|
||||
|
||||
/// Creates the extension database facade and resolves the Realm file inside the shared app group.
|
||||
/// A missing app-group container leaves `databaseURL` unset and causes `openRealm()` to fail safely.
|
||||
private init() {
|
||||
self.core = NCManageDatabaseCore()
|
||||
|
||||
if let dirGroup = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroup) {
|
||||
self.databaseURL = dirGroup
|
||||
.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud)
|
||||
.appendingPathComponent(databaseName)
|
||||
} else {
|
||||
self.databaseURL = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates the shared Realm schema before installing and opening the extension configuration.
|
||||
/// Returns `false` without migrating when the database is unavailable, incompatible, or cannot open.
|
||||
@discardableResult
|
||||
func openRealm() -> Bool {
|
||||
guard let databaseURL,
|
||||
let schemaVersion = try? schemaVersionAtURL(databaseURL),
|
||||
schemaVersion == databaseSchemaVersion else {
|
||||
logger.error("Realm was not opened because its schema version does not match the extension")
|
||||
return false
|
||||
}
|
||||
|
||||
do {
|
||||
let configuration = Realm.Configuration(
|
||||
fileURL: databaseURL,
|
||||
schemaVersion: databaseSchemaVersion,
|
||||
objectTypes: [
|
||||
NCKeyValue.self, tableMetadata.self, tableLocalFile.self, tableMetadataTag.self, tableLivePhoto.self,
|
||||
tableDirectory.self, tableAccount.self, tableCapabilities.self
|
||||
]
|
||||
)
|
||||
Realm.Configuration.defaultConfiguration = configuration
|
||||
|
||||
let realm = try Realm(configuration: configuration)
|
||||
if let url = realm.configuration.fileURL {
|
||||
logger.notice("Realm is located at: \(url.path, privacy: .public)")
|
||||
}
|
||||
return true
|
||||
} catch let error {
|
||||
logger.error("Realm error: \(error.localizedDescription, privacy: .public)")
|
||||
nkLog(tag: NCGlobal.shared.logTagBackgroundUpload, emoji: .error, message: "Realm error: \(error)")
|
||||
isSuspendingDatabaseOperation = true
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<!--
|
||||
- SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
- SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
- SPDX-License-Identifier: GPL-3.0-or-later
|
||||
-->
|
||||
|
||||
# Background upload extension
|
||||
|
||||
The following diagram documents the complete background-upload flow, including asset discovery, Live Photo handling, foreground chunk routing, PhotoKit job creation, server-confirmed success, automatic retries, acknowledgements, and account-level suspension.
|
||||
|
||||

|
||||
|
||||
## Routing summary
|
||||
|
||||
- A regular photo or video up to 100 MB is uploaded by PhotoKit.
|
||||
- A regular resource larger than 100 MB is stored as foreground metadata and handled by the host app.
|
||||
- A complete Live Photo up to 100 MB in total creates separate PhotoKit jobs for its HEIC and MOV resources.
|
||||
- A complete Live Photo larger than 100 MB in total creates one metadata seed; the host app later extracts and uploads both components.
|
||||
- After foreground extraction, the host app recalculates the actual chunk requirement for every concrete file using the current network.
|
||||
|
||||
## PhotoKit result handling
|
||||
|
||||
- A valid `oc-fileid` confirms that Nextcloud committed the upload, even when PhotoKit reports the job as failed after an HTTP 204 response.
|
||||
- A failed upload is attempted at most three times in total: the initial upload and two automatic retries.
|
||||
- Authentication failures and successful responses without `oc-fileid` suspend the account queue immediately.
|
||||
- Three consecutive terminal asset failures without an intervening success suspend the account queue.
|
||||
- Terminal PhotoKit jobs are acknowledged only after their result has been persisted locally.
|
||||
|
After Width: | Height: | Size: 1.4 MiB |
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.application-groups</key>
|
||||
<array>
|
||||
<string>group.it.twsweb.Crypto-Cloud</string>
|
||||
</array>
|
||||
<key>keychain-access-groups</key>
|
||||
<array>
|
||||
<string>$(AppIdentifierPrefix)it.twsweb.Crypto-Cloud</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST-1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>Nextcloud Assistant</string>
|
||||
|
||||
<key>NSExtension</key>
|
||||
<dict>
|
||||
<key>NSExtensionAttributes</key>
|
||||
<dict>
|
||||
<key>NSExtensionActivationRule</key>
|
||||
<dict>
|
||||
<key>NSExtensionActivationSupportsText</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</dict>
|
||||
|
||||
<key>NSExtensionMainStoryboard</key>
|
||||
<string>MainInterface</string>
|
||||
|
||||
<key>NSExtensionPointIdentifier</key>
|
||||
<string>com.apple.ui-services</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.application-groups</key>
|
||||
<array>
|
||||
<string>group.it.twsweb.Crypto-Cloud</string>
|
||||
</array>
|
||||
<key>keychain-access-groups</key>
|
||||
<array>
|
||||
<string>$(AppIdentifierPrefix)it.twsweb.Crypto-Cloud</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>BackgroundUploadURLBase</key>
|
||||
<string>https://cloud.nextcloud.com</string>
|
||||
<key>EXAppExtensionAttributes</key>
|
||||
<dict>
|
||||
<key>EXExtensionPointIdentifier</key>
|
||||
<string>com.apple.photos.background-upload</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -8,4 +8,4 @@ import Foundation
|
||||
//
|
||||
let databaseName = "nextcloud.realm"
|
||||
let tableAccountBackup = "tableAccountBackup.json"
|
||||
let databaseSchemaVersion: UInt64 = 409
|
||||
let databaseSchemaVersion: UInt64 = 424
|
||||
@@ -6,17 +6,6 @@
|
||||
<string>Nextcloud</string>
|
||||
<key>NSExtension</key>
|
||||
<dict>
|
||||
<key>NSExtensionFileProviderActions</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>NSExtensionFileProviderActionActivationRule</key>
|
||||
<string>TRUEPREDICATE</string>
|
||||
<key>NSExtensionFileProviderActionIdentifier</key>
|
||||
<string>com.mycompany.FileProviderUI.CustomAction</string>
|
||||
<key>NSExtensionFileProviderActionName</key>
|
||||
<string>Custom Action</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>NSExtensionMainStoryboard</key>
|
||||
<string>MainInterface</string>
|
||||
<key>NSExtensionPointIdentifier</key>
|
||||
|
||||
@@ -81,10 +81,10 @@
|
||||
<constraints>
|
||||
<constraint firstItem="Z5d-gx-rTR" firstAttribute="centerX" secondItem="Xnz-EW-9gg" secondAttribute="centerX" id="5JN-bZ-Cfc"/>
|
||||
<constraint firstItem="Z5d-gx-rTR" firstAttribute="top" relation="greaterThanOrEqual" secondItem="N4X-JQ-1c1" secondAttribute="bottom" constant="8" id="5bf-uK-zTE"/>
|
||||
<constraint firstItem="o6I-qu-IDh" firstAttribute="leading" secondItem="Yku-CN-snD" secondAttribute="leading" constant="8" id="5fD-CQ-g64"/>
|
||||
<constraint firstItem="o6I-qu-IDh" firstAttribute="leading" secondItem="Xnz-EW-9gg" secondAttribute="leading" constant="8" id="5fD-CQ-g64"/>
|
||||
<constraint firstItem="Yyc-bK-mqW" firstAttribute="centerX" secondItem="Xnz-EW-9gg" secondAttribute="centerX" id="73g-Jz-FyB"/>
|
||||
<constraint firstItem="Eu1-Gv-7Jx" firstAttribute="top" secondItem="o6I-qu-IDh" secondAttribute="bottom" constant="8" id="Eeu-jq-3mJ"/>
|
||||
<constraint firstItem="Yku-CN-snD" firstAttribute="trailing" secondItem="o6I-qu-IDh" secondAttribute="trailing" constant="8" id="Hc4-PE-nDo"/>
|
||||
<constraint firstItem="Xnz-EW-9gg" firstAttribute="trailing" secondItem="o6I-qu-IDh" secondAttribute="trailing" constant="8" id="Hc4-PE-nDo"/>
|
||||
<constraint firstItem="o6I-qu-IDh" firstAttribute="centerX" secondItem="Xnz-EW-9gg" secondAttribute="centerX" id="XgO-Ht-bat"/>
|
||||
<constraint firstItem="Yyc-bK-mqW" firstAttribute="top" secondItem="Eu1-Gv-7Jx" secondAttribute="bottom" priority="250" constant="64" id="avi-Qq-NVJ"/>
|
||||
<constraint firstItem="N4X-JQ-1c1" firstAttribute="top" secondItem="Yyc-bK-mqW" secondAttribute="bottom" constant="8" id="g2S-FI-zsd"/>
|
||||
|
||||
@@ -54,7 +54,7 @@ class NCIntroViewController: UIViewController, UICollectionViewDataSource, UICol
|
||||
if !NCManageDatabase.shared.getAllTableAccount().isEmpty {
|
||||
let navigationItemCancel = UIBarButtonItem(image: UIImage(systemName: "xmark"), style: .plain, target: self, action: #selector(actionCancel(_:)))
|
||||
navigationItemCancel.tintColor = textColor
|
||||
navigationItem.leftBarButtonItem = navigationItemCancel
|
||||
navigationItem.rightBarButtonItem = navigationItemCancel
|
||||
}
|
||||
|
||||
pageControl.currentPageIndicatorTintColor = textColor
|
||||
|
||||
@@ -20,6 +20,44 @@ let userAgent: String = {
|
||||
The codename embodies the concept of dynamic, living matter — reflecting our vision of a platform that is not only powerful and reliable, but also capable of continuous transformation and intelligent adaptation.
|
||||
*/
|
||||
|
||||
struct NextcloudVersion: Comparable {
|
||||
let major: Int
|
||||
let minor: Int
|
||||
let micro: Int
|
||||
|
||||
init(_ major: Int, _ minor: Int = 0, _ micro: Int = 0) {
|
||||
self.major = major
|
||||
self.minor = minor
|
||||
self.micro = micro
|
||||
}
|
||||
|
||||
init(_ capabilities: NKCapabilities.Capabilities) {
|
||||
self.major = capabilities.serverVersionMajor
|
||||
self.minor = capabilities.serverVersionMinor
|
||||
self.micro = capabilities.serverVersionMicro
|
||||
}
|
||||
|
||||
static let v18 = NextcloudVersion(18)
|
||||
static let v20 = NextcloudVersion(20)
|
||||
static let v23 = NextcloudVersion(23)
|
||||
static let v24 = NextcloudVersion(24)
|
||||
static let v25 = NextcloudVersion(25)
|
||||
static let v26 = NextcloudVersion(26)
|
||||
static let v27 = NextcloudVersion(27)
|
||||
static let v28 = NextcloudVersion(28)
|
||||
static let v30 = NextcloudVersion(30)
|
||||
static let v31 = NextcloudVersion(31)
|
||||
static let v32 = NextcloudVersion(32)
|
||||
static let v32_0_2 = NextcloudVersion(32, 0, 2)
|
||||
static let v33 = NextcloudVersion(33)
|
||||
static let v34 = NextcloudVersion(34)
|
||||
static let v35 = NextcloudVersion(35)
|
||||
|
||||
static func < (lhs: NextcloudVersion, rhs: NextcloudVersion) -> Bool {
|
||||
(lhs.major, lhs.minor, lhs.micro) < (rhs.major, rhs.minor, rhs.micro)
|
||||
}
|
||||
}
|
||||
|
||||
final class NCBrandOptions: @unchecked Sendable {
|
||||
static let shared = NCBrandOptions()
|
||||
|
||||
@@ -27,7 +65,7 @@ final class NCBrandOptions: @unchecked Sendable {
|
||||
var brandUserAgent: String = ""
|
||||
var textCopyrightNextcloudiOS: String = "Nextcloud Matheria for iOS %@ © 2026"
|
||||
var textCopyrightNextcloudServer: String = "Nextcloud Server %@"
|
||||
var loginBaseUrl: String = "https://cloud.nextcloud.com"
|
||||
var loginBaseUrl: String = ""
|
||||
var pushNotificationServerProxy: String = ""
|
||||
var linkLoginHost: String = "https://nextcloud.com/install"
|
||||
var linkloginPreferredProviders: String = "https://nextcloud.com/signup-ios"
|
||||
@@ -37,6 +75,8 @@ final class NCBrandOptions: @unchecked Sendable {
|
||||
var mobileconfig: String = "/remote.php/dav/provisioning/apple-provisioning.mobileconfig"
|
||||
var appStoreUrl: String = "https://apps.apple.com/in/app/nextcloud/id1125420102"
|
||||
|
||||
var doNotAskPasscodeAtStartup: Bool = false
|
||||
|
||||
// Auto Upload default folder
|
||||
var folderDefaultAutoUpload: String = "Photos"
|
||||
|
||||
@@ -45,21 +85,21 @@ final class NCBrandOptions: @unchecked Sendable {
|
||||
var capabilitiesGroupApps: String = "group.com.nextcloud.apps"
|
||||
|
||||
// BRAND ONLY
|
||||
var use_AppConfig: Bool = false // Don't touch me !!
|
||||
var use_AppConfig: Bool = false
|
||||
|
||||
// Use server theming color
|
||||
var use_themingColor: Bool = true
|
||||
|
||||
// MDM settings
|
||||
var disable_intro: Bool = false
|
||||
var disable_request_login_url: Bool = false
|
||||
var disable_multiaccount: Bool = false
|
||||
var disable_more_external_site: Bool = false
|
||||
var disable_openin_file: Bool = false // Don't touch me !!
|
||||
var disable_openin_file: Bool = false
|
||||
var disable_crash_service: Bool = false
|
||||
var disable_log: Bool = false
|
||||
var disable_mobileconfig: Bool = false
|
||||
var disable_show_more_nextcloud_apps_in_settings: Bool = false
|
||||
var doNotAskPasscodeAtStartup: Bool = false
|
||||
var disable_source_code_in_settings: Bool = false
|
||||
var enforce_passcode_lock = false
|
||||
var enforce_privacyScreenEnabled = false
|
||||
@@ -68,23 +108,23 @@ final class NCBrandOptions: @unchecked Sendable {
|
||||
var enforce_servers: [(name: String, url: String)] = []
|
||||
|
||||
// Internal option behaviour
|
||||
var cleanUpDay: Int = 0 // Set default "Delete all cached files older than" possible days value are: 0, 1, 7, 30, 90, 180, 365
|
||||
var cleanUpDay: Int = 0 // Set default "Delete all cached files older than". Possible days value are: 0, 1, 7, 30, 90, 180, 365
|
||||
|
||||
// Max request/download/upload concurrent
|
||||
// Max request/download/upload concurrent connections per host, default is 8 (same as iOS default)
|
||||
let httpMaximumConnectionsPerHost: Int = 8
|
||||
let httpMaximumConnectionsPerHostInDownload: Int = 8
|
||||
let httpMaximumConnectionsPerHostInUpload: Int = 8
|
||||
|
||||
// Max request/download/upload process
|
||||
// Max request/download/upload processes
|
||||
let numMaximumProcess: Int = 20
|
||||
|
||||
// Number of failed attempts after reset app
|
||||
// Number of failed attempts before resetting the app
|
||||
let resetAppPasscodeAttempts: Int = 10
|
||||
let passcodeSecondsFail: Int = 60
|
||||
|
||||
// Info Paging
|
||||
enum NCInfoPagingTab: Int, CaseIterable {
|
||||
case activity, sharing
|
||||
case activity, sharing, details
|
||||
}
|
||||
|
||||
init() {
|
||||
@@ -129,19 +169,8 @@ final class NCBrandOptions: @unchecked Sendable {
|
||||
}
|
||||
|
||||
func isServerVersion(_ capabilities: NKCapabilities.Capabilities,
|
||||
greaterOrEqualTo major: Int,
|
||||
_ minor: Int,
|
||||
_ micro: Int) -> Bool {
|
||||
|
||||
let server = (
|
||||
capabilities.serverVersionMajor,
|
||||
capabilities.serverVersionMinor,
|
||||
capabilities.serverVersionMicro
|
||||
)
|
||||
|
||||
let required = (major, minor, micro)
|
||||
|
||||
return server >= required
|
||||
greaterOrEqualTo version: NextcloudVersion) -> Bool {
|
||||
return NextcloudVersion(capabilities) >= version
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,7 +178,7 @@ final class NCBrandColor: @unchecked Sendable {
|
||||
static let shared = NCBrandColor()
|
||||
|
||||
// This is rewrited from customet theme, default is Nextcloud color
|
||||
let customer: UIColor = UIColor(red: 0.0 / 255.0, green: 130.0 / 255.0, blue: 201.0 / 255.0, alpha: 1.0) // Nextcloud : #0082C9
|
||||
let customer: UIColor = UIColor(red: 0.0 / 255.0, green: 130.0 / 255.0, blue: 201.0 / 255.0, alpha: 1.0) // Nextcloud default: #0082C9
|
||||
var customerText: UIColor = .white
|
||||
|
||||
// INTERNAL DEFINE COLORS
|
||||
|
||||
@@ -30,8 +30,7 @@
|
||||
<key>NSExtensionAttributes</key>
|
||||
<dict>
|
||||
<key>NSExtensionActivationRule</key>
|
||||
<string>SUBQUERY (extensionItems, $extensionItem, SUBQUERY ($extensionItem.attachments,$attachment,(ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.data")).@count == $extensionItem.attachments.@count).@count > 0
|
||||
</string>
|
||||
<string>SUBQUERY (extensionItems, $extensionItem, SUBQUERY ($extensionItem.attachments, $attachment, (ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.data" OR ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.text")).@count == $extensionItem.attachments.@count).@count > 0</string>
|
||||
</dict>
|
||||
<key>NSExtensionMainStoryboard</key>
|
||||
<string>MainInterface</string>
|
||||
@@ -39,4 +38,4 @@
|
||||
<string>com.apple.share-services</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
</plist>
|
||||
@@ -2,11 +2,6 @@
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsArbitraryLoads</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>NSExtension</key>
|
||||
<dict>
|
||||
<key>NSExtensionAttributes</key>
|
||||
|
||||
@@ -85,16 +85,6 @@
|
||||
</array>
|
||||
<key>PHPhotoLibraryPreventAutomaticLimitedAccessAlert</key>
|
||||
<true/>
|
||||
<key>UIAppFonts</key>
|
||||
<array>
|
||||
<string>Inconsolata-Light.ttf</string>
|
||||
<string>Inconsolata-Regular.ttf</string>
|
||||
<string>Inconsolata-ExtraLight.ttf</string>
|
||||
<string>Inconsolata-Medium.ttf</string>
|
||||
<string>Inconsolata-Bold.ttf</string>
|
||||
<string>Inconsolata-ExtraBold.ttf</string>
|
||||
<string>Inconsolata-Black.ttf</string>
|
||||
</array>
|
||||
<key>UIApplicationSceneManifest</key>
|
||||
<dict>
|
||||
<key>UIApplicationSupportsMultipleScenes</key>
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
|
||||
SPDX-License-Identifier: GPL-3.0-or-later
|
||||
@@ -1,85 +0,0 @@
|
||||
//
|
||||
// NCApplicationHandle.swift
|
||||
// Nextcloud
|
||||
//
|
||||
// Created by Marino Faggiana on 25/11/22.
|
||||
// Copyright © 2022 Marino Faggiana. All rights reserved.
|
||||
//
|
||||
// Author Marino Faggiana <marino.faggiana@nextcloud.com>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import NextcloudKit
|
||||
import UIKit
|
||||
import Parchment
|
||||
|
||||
class NCApplicationHandle: NSObject {
|
||||
|
||||
// class: AppDelegate
|
||||
// func nextcloudPushNotificationAction(data: [String: AnyObject])
|
||||
func nextcloudPushNotificationAction(data: [String: AnyObject]) -> [String: AnyObject]? {
|
||||
return data
|
||||
}
|
||||
|
||||
// class: AppDelegate
|
||||
// func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void)
|
||||
func applicationOpenUserActivity(_ userActivity: NSUserActivity) -> Bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// class: AppDelegate
|
||||
// func: application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:])
|
||||
func applicationOpenURL(_ url: URL) -> Bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// class: NCFunctionCenter
|
||||
// func: downloadedFile(_ notification: NSNotification)
|
||||
func downloadedFile(selector: String, metadata: tableMetadata) {
|
||||
}
|
||||
|
||||
// class: NCMore
|
||||
// func: loadItems()
|
||||
func loadItems(functionMenu: inout [NKExternalSite]) {
|
||||
}
|
||||
|
||||
// class: NCMore
|
||||
// func: tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
|
||||
func didSelectItem(_ item: NKExternalSite, viewController: UIViewController) {
|
||||
}
|
||||
|
||||
// class: NCSharePaging
|
||||
// func pagingViewController(_: PagingViewController, viewControllerAt index: Int) -> UIViewController
|
||||
func pagingViewController(_: PagingViewController, viewControllerAt index: Int, metadata: tableMetadata, topHeight: CGFloat) -> UIViewController {
|
||||
return UIViewController()
|
||||
}
|
||||
|
||||
// class: NCSharePaging
|
||||
// func pagingViewController(_: PagingViewController, pagingItemAt index: Int) -> PagingItem
|
||||
func pagingViewController(_: PagingViewController, pagingItemAt index: Int) -> PagingItem {
|
||||
return PagingIndexItem(index: index, title: "")
|
||||
}
|
||||
|
||||
// class: NCActionCenter
|
||||
func filterPages(pages: [NCBrandOptions.NCInfoPagingTab], page: NCBrandOptions.NCInfoPagingTab, metadata: tableMetadata) -> ([NCBrandOptions.NCInfoPagingTab], NCBrandOptions.NCInfoPagingTab) {
|
||||
return (pages, page)
|
||||
}
|
||||
|
||||
// class: NCNotification
|
||||
func didSelectNotification(_ notification: NKNotifications, viewController: UIViewController) -> NKNotifications? {
|
||||
return notification
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,6 @@
|
||||
//
|
||||
// DocumentActionViewController.swift
|
||||
// File Provider Extension UI
|
||||
//
|
||||
// Created by Marino Faggiana on 30/01/23.
|
||||
// Copyright © 2023 Marino Faggiana. All rights reserved.
|
||||
//
|
||||
// Author Marino Faggiana <marino.faggiana@nextcloud.com>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
//
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2023 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import UIKit
|
||||
import FileProviderUI
|
||||
|
||||
@@ -42,7 +42,10 @@ class FileProviderData: NSObject {
|
||||
let tblAccounts = NCManageDatabase.shared.getAllTableAccount()
|
||||
var matchAccount: tableAccount?
|
||||
|
||||
NextcloudKit.configureLogger(logLevel: (NCBrandOptions.shared.disable_log ? .disabled : NCPreferences().log))
|
||||
NextcloudKit.configureLogger(
|
||||
logLevel: NCBrandOptions.shared.disable_log ? .disabled : NCPreferences().log,
|
||||
logDirectory: NCPreferences.sharedLogDirectory
|
||||
)
|
||||
|
||||
if let domain {
|
||||
self.domain = domain
|
||||
@@ -90,7 +93,7 @@ class FileProviderData: NSObject {
|
||||
return isPaginated
|
||||
} else if serverUrl == NCUtilityFileSystem().getHomeServer(session: session),
|
||||
let capabilities = await NextcloudKit.shared.getCapabilitiesAsync(account: session.account).capabilities,
|
||||
NCBrandOptions.shared.isServerVersion(capabilities, greaterOrEqualTo: 32, 0, 2) {
|
||||
NCBrandOptions.shared.isServerVersion(capabilities, greaterOrEqualTo: .v32_0_2) {
|
||||
isPaginated = true
|
||||
return true
|
||||
}
|
||||
@@ -147,10 +150,7 @@ class FileProviderData: NSObject {
|
||||
|
||||
func downloadComplete(fileName: String,
|
||||
serverUrl: String,
|
||||
etag: String?,
|
||||
date: Date?,
|
||||
dateLastModified: Date?,
|
||||
length: Int64,
|
||||
allHeaderFields: [AnyHashable: Any]?,
|
||||
task: URLSessionTask,
|
||||
error: NKError) async {
|
||||
let taskIdentifier = task.taskIdentifier
|
||||
@@ -165,6 +165,7 @@ class FileProviderData: NSObject {
|
||||
}
|
||||
|
||||
let ocId = metadata.ocId
|
||||
let etag = NextcloudKit.shared.nkCommonInstance.findHeader("oc-etag", allHeaderFields: allHeaderFields)
|
||||
|
||||
await NCManageDatabase.shared.setMetadataSessionAsync(ocId: ocId,
|
||||
session: "",
|
||||
@@ -196,7 +197,8 @@ class FileProviderData: NSObject {
|
||||
ocId: String?,
|
||||
etag: String?,
|
||||
date: Date?,
|
||||
size: Int64,
|
||||
ownerId: String?,
|
||||
permissions: String?,
|
||||
task: URLSessionTask,
|
||||
error: NKError) async {
|
||||
guard let metadata = await NCManageDatabase.shared.getMetadataAsync(predicate: NSPredicate(format: "serverUrl == %@ AND fileName == %@ AND sessionTaskIdentifier == %d", serverUrl, fileName, task.taskIdentifier)) else {
|
||||
@@ -225,14 +227,26 @@ class FileProviderData: NSObject {
|
||||
metadata.uploadDate = (date as? NSDate) ?? NSDate()
|
||||
metadata.etag = etag ?? ""
|
||||
metadata.ocId = ocId
|
||||
metadata.size = size
|
||||
|
||||
if let fileId = fileProviderUtility().ocIdToFileId(ocId: ocId) {
|
||||
metadata.fileId = fileId
|
||||
}
|
||||
|
||||
if let ownerId, !ownerId.isEmpty {
|
||||
metadata.ownerId = ownerId
|
||||
if let ownerDisplayName = await NCManageDatabase.shared.getOwnerDisplayName(account: metadata.account, ownerId: ownerId) {
|
||||
metadata.ownerDisplayName = ownerDisplayName
|
||||
}
|
||||
}
|
||||
|
||||
if let permissions, !permissions.isEmpty {
|
||||
metadata.permissions = permissions
|
||||
}
|
||||
|
||||
metadata.sceneIdentifier = nil
|
||||
metadata.session = ""
|
||||
metadata.sessionError = ""
|
||||
metadata.errorKind = ""
|
||||
metadata.sessionSelector = ""
|
||||
metadata.sessionDate = nil
|
||||
metadata.sessionTaskIdentifier = 0
|
||||
|
||||
@@ -139,7 +139,7 @@ extension FileProviderExtension {
|
||||
|
||||
} else {
|
||||
|
||||
completionHandler(nil, NSFileProviderError(.noSuchItem, userInfo: [NSLocalizedDescriptionKey: resultsMove.error.errorDescription, NSLocalizedFailureReasonErrorKey: ""]))
|
||||
completionHandler(nil, NSFileProviderError(.noSuchItem, userInfo: [NSLocalizedDescriptionKey: resultsMove.error.localizedGenericMessage, NSLocalizedFailureReasonErrorKey: ""]))
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -176,7 +176,7 @@ extension FileProviderExtension {
|
||||
|
||||
} else if resultsMove.error.errorCode == NCGlobal.shared.errorBadRequest {
|
||||
|
||||
completionHandler(nil, NSFileProviderError(.noSuchItem, userInfo: [NSLocalizedDescriptionKey: resultsMove.error.errorDescription, NSLocalizedFailureReasonErrorKey: ""]))
|
||||
completionHandler(nil, NSFileProviderError(.noSuchItem, userInfo: [NSLocalizedDescriptionKey: resultsMove.error.localizedGenericMessage, NSLocalizedFailureReasonErrorKey: ""]))
|
||||
return
|
||||
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
Creative Commons Legal Code
|
||||
|
||||
CC0 1.0 Universal
|
||||
|
||||
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
||||
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
|
||||
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
||||
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
||||
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
|
||||
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
|
||||
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
|
||||
HEREUNDER.
|
||||
|
||||
Statement of Purpose
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer
|
||||
exclusive Copyright and Related Rights (defined below) upon the creator
|
||||
and subsequent owner(s) (each and all, an "owner") of an original work of
|
||||
authorship and/or a database (each, a "Work").
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for
|
||||
the purpose of contributing to a commons of creative, cultural and
|
||||
scientific works ("Commons") that the public can reliably and without fear
|
||||
of later claims of infringement build upon, modify, incorporate in other
|
||||
works, reuse and redistribute as freely as possible in any form whatsoever
|
||||
and for any purposes, including without limitation commercial purposes.
|
||||
These owners may contribute to the Commons to promote the ideal of a free
|
||||
culture and the further production of creative, cultural and scientific
|
||||
works, or to gain reputation or greater distribution for their Work in
|
||||
part through the use and efforts of others.
|
||||
|
||||
For these and/or other purposes and motivations, and without any
|
||||
expectation of additional consideration or compensation, the person
|
||||
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
|
||||
is an owner of Copyright and Related Rights in the Work, voluntarily
|
||||
elects to apply CC0 to the Work and publicly distribute the Work under its
|
||||
terms, with knowledge of his or her Copyright and Related Rights in the
|
||||
Work and the meaning and intended legal effect of CC0 on those rights.
|
||||
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may be
|
||||
protected by copyright and related or neighboring rights ("Copyright and
|
||||
Related Rights"). Copyright and Related Rights include, but are not
|
||||
limited to, the following:
|
||||
|
||||
i. the right to reproduce, adapt, distribute, perform, display,
|
||||
communicate, and translate a Work;
|
||||
ii. moral rights retained by the original author(s) and/or performer(s);
|
||||
iii. publicity and privacy rights pertaining to a person's image or
|
||||
likeness depicted in a Work;
|
||||
iv. rights protecting against unfair competition in regards to a Work,
|
||||
subject to the limitations in paragraph 4(a), below;
|
||||
v. rights protecting the extraction, dissemination, use and reuse of data
|
||||
in a Work;
|
||||
vi. database rights (such as those arising under Directive 96/9/EC of the
|
||||
European Parliament and of the Council of 11 March 1996 on the legal
|
||||
protection of databases, and under any national implementation
|
||||
thereof, including any amended or successor version of such
|
||||
directive); and
|
||||
vii. other similar, equivalent or corresponding rights throughout the
|
||||
world based on applicable law or treaty, and any national
|
||||
implementations thereof.
|
||||
|
||||
2. Waiver. To the greatest extent permitted by, but not in contravention
|
||||
of, applicable law, Affirmer hereby overtly, fully, permanently,
|
||||
irrevocably and unconditionally waives, abandons, and surrenders all of
|
||||
Affirmer's Copyright and Related Rights and associated claims and causes
|
||||
of action, whether now known or unknown (including existing as well as
|
||||
future claims and causes of action), in the Work (i) in all territories
|
||||
worldwide, (ii) for the maximum duration provided by applicable law or
|
||||
treaty (including future time extensions), (iii) in any current or future
|
||||
medium and for any number of copies, and (iv) for any purpose whatsoever,
|
||||
including without limitation commercial, advertising or promotional
|
||||
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
|
||||
member of the public at large and to the detriment of Affirmer's heirs and
|
||||
successors, fully intending that such Waiver shall not be subject to
|
||||
revocation, rescission, cancellation, termination, or any other legal or
|
||||
equitable action to disrupt the quiet enjoyment of the Work by the public
|
||||
as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. Public License Fallback. Should any part of the Waiver for any reason
|
||||
be judged legally invalid or ineffective under applicable law, then the
|
||||
Waiver shall be preserved to the maximum extent permitted taking into
|
||||
account Affirmer's express Statement of Purpose. In addition, to the
|
||||
extent the Waiver is so judged Affirmer hereby grants to each affected
|
||||
person a royalty-free, non transferable, non sublicensable, non exclusive,
|
||||
irrevocable and unconditional license to exercise Affirmer's Copyright and
|
||||
Related Rights in the Work (i) in all territories worldwide, (ii) for the
|
||||
maximum duration provided by applicable law or treaty (including future
|
||||
time extensions), (iii) in any current or future medium and for any number
|
||||
of copies, and (iv) for any purpose whatsoever, including without
|
||||
limitation commercial, advertising or promotional purposes (the
|
||||
"License"). The License shall be deemed effective as of the date CC0 was
|
||||
applied by Affirmer to the Work. Should any part of the License for any
|
||||
reason be judged legally invalid or ineffective under applicable law, such
|
||||
partial invalidity or ineffectiveness shall not invalidate the remainder
|
||||
of the License, and in such case Affirmer hereby affirms that he or she
|
||||
will not (i) exercise any of his or her remaining Copyright and Related
|
||||
Rights in the Work or (ii) assert any associated claims and causes of
|
||||
action with respect to the Work, in either case contrary to Affirmer's
|
||||
express Statement of Purpose.
|
||||
|
||||
4. Limitations and Disclaimers.
|
||||
|
||||
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
||||
surrendered, licensed or otherwise affected by this document.
|
||||
b. Affirmer offers the Work as-is and makes no representations or
|
||||
warranties of any kind concerning the Work, express, implied,
|
||||
statutory or otherwise, including without limitation warranties of
|
||||
title, merchantability, fitness for a particular purpose, non
|
||||
infringement, or the absence of latent or other defects, accuracy, or
|
||||
the present or absence of errors, whether or not discoverable, all to
|
||||
the greatest extent permissible under applicable law.
|
||||
c. Affirmer disclaims responsibility for clearing rights of other persons
|
||||
that may apply to the Work or any use thereof, including without
|
||||
limitation any person's Copyright and Related Rights in the Work.
|
||||
Further, Affirmer disclaims responsibility for obtaining any necessary
|
||||
consents, permissions or other rights required for any use of the
|
||||
Work.
|
||||
d. Affirmer understands and acknowledges that Creative Commons is not a
|
||||
party to this document and has no duty or obligation with respect to
|
||||
this CC0 or use of the Work.
|
||||
@@ -0,0 +1,232 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
“This License” refers to version 3 of the GNU General Public License.
|
||||
|
||||
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||
|
||||
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
|
||||
|
||||
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
|
||||
|
||||
A “covered work” means either the unmodified Program or a work based on the Program.
|
||||
|
||||
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||
|
||||
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
|
||||
|
||||
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||
|
||||
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
|
||||
|
||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||
|
||||
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||
|
||||
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||
|
||||
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
|
||||
|
||||
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||
|
||||
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,9 @@
|
||||
The Nextcloud marks
|
||||
Nextcloud and the Nextcloud logo is a registered trademark of Nextcloud GmbH in Germany and/or other countries.
|
||||
These guidelines cover the following marks pertaining both to the product names and the logo: “Nextcloud”
|
||||
and the blue/white cloud logo with or without the word Nextcloud; the service “Nextcloud Enterprise”;
|
||||
and our products: “Nextcloud Files”; “Nextcloud Groupware” and “Nextcloud Talk”.
|
||||
This set of marks is collectively referred to as the “Nextcloud marks.”
|
||||
|
||||
Use of Nextcloud logos and other marks is only permitted under the guidelines provided by the Nextcloud GmbH.
|
||||
A copy can be found at https://nextcloud.com/trademarks/
|
||||
@@ -0,0 +1,18 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) <year> <copyright holders>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
associated documentation files (the "Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
|
||||
following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial
|
||||
portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
|
||||
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
||||
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
||||
USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,375 @@
|
||||
{
|
||||
"originHash" : "7880536aedfe5f5b326df402ac666a6126ac1b325106ab3eb7b6c78a6ef725ff",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "abseil-cpp-binary",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/abseil-cpp-binary.git",
|
||||
"state" : {
|
||||
"revision" : "26509120768c4add61cc1a63059f15f4fb49edb4",
|
||||
"version" : "1.2025051202.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "alamofire",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/Alamofire/Alamofire",
|
||||
"state" : {
|
||||
"revision" : "bda9ed57d72988a3a2ada33d824583541f86eac6",
|
||||
"version" : "5.12.2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "app-check",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/app-check.git",
|
||||
"state" : {
|
||||
"revision" : "c7eb17e5545f36e43dc50e70da09c2e999714e16",
|
||||
"version" : "12.0.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "codescanner",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/twostraws/CodeScanner.git",
|
||||
"state" : {
|
||||
"revision" : "5e886430238944c7200fc9e10dbf2d9550dba865",
|
||||
"version" : "2.5.2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "dropdown",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/AssistoLab/DropDown",
|
||||
"state" : {
|
||||
"branch" : "master",
|
||||
"revision" : "2ab6f6ce19f0117d1a76ea043ef8f57722c65d16"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "easytipview",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/marinofaggiana/EasyTipView",
|
||||
"state" : {
|
||||
"branch" : "master",
|
||||
"revision" : "bb25a13c8fa5d65144c8e5b5d31237b80a001b07"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "firebase-ios-sdk",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/firebase/firebase-ios-sdk",
|
||||
"state" : {
|
||||
"revision" : "1c35b9453868cea1ecdf9f112b5b23b8b6343854",
|
||||
"version" : "13.0.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "google-ads-on-device-conversion-ios-sdk",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/googleads/google-ads-on-device-conversion-ios-sdk",
|
||||
"state" : {
|
||||
"revision" : "0208e2681ec81f8a9c81084696f60fcce26cb7ee",
|
||||
"version" : "3.7.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "googleappmeasurement",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/GoogleAppMeasurement.git",
|
||||
"state" : {
|
||||
"revision" : "1a3546fb9189292e9d64db9e72add7a286c0f85a",
|
||||
"version" : "13.0.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "googledatatransport",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/GoogleDataTransport.git",
|
||||
"state" : {
|
||||
"revision" : "ba3358d3c3dbae8ef230b58a46b97ad65e84e974",
|
||||
"version" : "10.1.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "googleutilities",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/GoogleUtilities.git",
|
||||
"state" : {
|
||||
"revision" : "cc31f5ed464b111f877ce8554cbef4455d410d91",
|
||||
"version" : "8.1.4"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "grdb.swift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/groue/GRDB.swift",
|
||||
"state" : {
|
||||
"revision" : "b83108d10f42680d78f23fe4d4d80fc88dab3212",
|
||||
"version" : "7.11.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "grpc-binary",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/grpc-binary.git",
|
||||
"state" : {
|
||||
"revision" : "9d5e9f05670c9eab8d8c22731ddd5d4d9cf867a8",
|
||||
"version" : "1.83.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "gtm-session-fetcher",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/gtm-session-fetcher.git",
|
||||
"state" : {
|
||||
"revision" : "724a52eea6329b7e12d3ad8300d76ca9f3895fcc",
|
||||
"version" : "5.3.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "gzipswift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/1024jp/GzipSwift",
|
||||
"state" : {
|
||||
"revision" : "41d37421fe2cbbfae4a5593dc29d12999fb73cd7",
|
||||
"version" : "7.0.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "interop-ios-for-google-sdks",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/interop-ios-for-google-sdks.git",
|
||||
"state" : {
|
||||
"revision" : "040d087ac2267d2ddd4cca36c757d1c6a05fdbfe",
|
||||
"version" : "101.0.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "keychainaccess",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/kishikawakatsumi/KeychainAccess",
|
||||
"state" : {
|
||||
"revision" : "84e546727d66f1adc5439debad16270d0fdd04e7",
|
||||
"version" : "4.2.2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "leveldb",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/firebase/leveldb.git",
|
||||
"state" : {
|
||||
"revision" : "a0bc79961d7be727d258d33d5a6b2f1023270ba1",
|
||||
"version" : "1.22.5"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "lucidbanner",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/marinofaggiana/LucidBanner",
|
||||
"state" : {
|
||||
"revision" : "408af8b2ff2451f055ff17042d8b9fb5c822d5fd",
|
||||
"version" : "0.8.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "mantis",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/marinofaggiana/Mantis",
|
||||
"state" : {
|
||||
"revision" : "d145ce2403e0d94d4926eb8510bc4966fbf1bfca",
|
||||
"version" : "1.0.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "markdownkit",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/bmoliveira/MarkdownKit",
|
||||
"state" : {
|
||||
"revision" : "39ea7a3fc7e65bcafe55152592b834859be574a5",
|
||||
"version" : "1.7.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "nanopb",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/firebase/nanopb.git",
|
||||
"state" : {
|
||||
"revision" : "3851d94a41890dea16dc3db34caf60e585cb4163",
|
||||
"version" : "2.30910.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "nextcloudkit",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/nextcloud/NextcloudKit",
|
||||
"state" : {
|
||||
"revision" : "49eee789ab676d6aba0020ccbe0d850f62e1d449",
|
||||
"version" : "7.6.4"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "openssl",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/krzyzanowskim/OpenSSL",
|
||||
"state" : {
|
||||
"revision" : "0a6149bff4fb00921ce0ec1811f726b166638095",
|
||||
"version" : "3.6.5000"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "popupview",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/exyte/PopupView.git",
|
||||
"state" : {
|
||||
"revision" : "99695337ce9e965b70e4aa14b49b1a9920017333",
|
||||
"version" : "5.0.8"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "promises",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/promises.git",
|
||||
"state" : {
|
||||
"revision" : "f4a19a3c313dc2616c70bb49d29a799fb16be837",
|
||||
"version" : "2.4.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "qrcodereader.swift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/yannickl/QRCodeReader.swift",
|
||||
"state" : {
|
||||
"revision" : "5020b5a47199d8ba80c83a4b4fafd70e9dc9dc7f",
|
||||
"version" : "10.1.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "realm-core",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/realm/realm-core.git",
|
||||
"state" : {
|
||||
"revision" : "b4192c46305570577c4d08df790fddec5ab3aa04",
|
||||
"version" : "20.1.5"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "realm-swift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/realm/realm-swift",
|
||||
"state" : {
|
||||
"revision" : "a40ced79265b644a896e393b0f3a37e7916e7de3",
|
||||
"version" : "20.0.6"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-atomics",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-atomics.git",
|
||||
"state" : {
|
||||
"revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34",
|
||||
"version" : "1.3.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-collections",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-collections.git",
|
||||
"state" : {
|
||||
"revision" : "35a1edcb8ebd2bfe251d587f0b69e62af28f508c",
|
||||
"version" : "1.7.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-nio",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-nio.git",
|
||||
"state" : {
|
||||
"revision" : "6db9d9abd92ad7399b8a564cafbb87d3507245fa",
|
||||
"version" : "2.104.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-nio-ssl",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-nio-ssl",
|
||||
"state" : {
|
||||
"revision" : "322f3c2a4a21df31c84ca416bf65ee5e9059e440",
|
||||
"version" : "2.37.5"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-system",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-system.git",
|
||||
"state" : {
|
||||
"revision" : "869129b7bf4ecc57b97d0193ad29690ca2134750",
|
||||
"version" : "1.8.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swifter",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/httpswift/swifter.git",
|
||||
"state" : {
|
||||
"branch" : "stable",
|
||||
"revision" : "1e4f51c92d7ca486242d8bf0722b99de2c3531aa"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swiftrichstring",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/malcommac/SwiftRichString",
|
||||
"state" : {
|
||||
"revision" : "9bf4b5af6bb4386865636fc504d6c588c2b65040",
|
||||
"version" : "3.7.2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swiftyjson",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/SwiftyJSON/SwiftyJSON",
|
||||
"state" : {
|
||||
"revision" : "af76cf3ef710b6ca5f8c05f3a31307d44a3c5828",
|
||||
"version" : "5.0.2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swiftyxmlparser",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/yahoojapan/SwiftyXMLParser",
|
||||
"state" : {
|
||||
"revision" : "d7a1d23f04c86c1cd2e8f19247dd15d74e0ea8be",
|
||||
"version" : "5.6.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "taglistview",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/ElaWorkshop/TagListView",
|
||||
"state" : {
|
||||
"revision" : "b30b61826736f4d9ec04aef5df891f3914423f16",
|
||||
"version" : "1.4.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "tlphotopicker",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/tilltue/TLPhotoPicker",
|
||||
"state" : {
|
||||
"revision" : "91d7bca65721928af30c6a2bb1a1f517f7862964",
|
||||
"version" : "2.1.21"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "vlckit-spm",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/tylerjonesio/vlckit-spm",
|
||||
"state" : {
|
||||
"revision" : "e932bbd488872fdb74f6654d28c2f291eae03daf",
|
||||
"version" : "3.6.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "2700"
|
||||
version = "2.0">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES"
|
||||
buildArchitectures = "Automatic">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F7FB187F30401D0D00EB0AE6"
|
||||
BuildableName = "BackgroundUploadExtension.appex"
|
||||
BlueprintName = "BackgroundUploadExtension"
|
||||
ReferencedContainer = "container:Nextcloud.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
shouldAutocreateTestPlan = "YES">
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = ""
|
||||
selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"
|
||||
launchStyle = "0"
|
||||
askForAppToLaunch = "Yes"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES"
|
||||
launchAutomaticallySubstyle = "2"
|
||||
queueDebuggingEnabled = "No">
|
||||
<RemoteRunnable
|
||||
runnableDebuggingMode = "0"
|
||||
BundleIdentifier = "it.twsweb.Nextcloud"
|
||||
RemotePath = "/var/containers/Bundle/Application/96505171-B093-46F6-8C0A-C5A40B9B645E/Nextcloud.app">
|
||||
</RemoteRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
askForAppToLaunch = "Yes"
|
||||
launchAutomaticallySubstyle = "2">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F7FB187F30401D0D00EB0AE6"
|
||||
BuildableName = "BackgroundUploadExtension.appex"
|
||||
BlueprintName = "BackgroundUploadExtension"
|
||||
ReferencedContainer = "container:Nextcloud.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "2640"
|
||||
version = "1.7">
|
||||
version = "2.0">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
@@ -56,15 +56,17 @@
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F31F69412A2F6D4500162F76"
|
||||
BuildableName = "NextcloudSnapshotTests.xctest"
|
||||
BlueprintName = "NextcloudSnapshotTests"
|
||||
BlueprintIdentifier = "AF8ED1F82757821000B8DBC4"
|
||||
BuildableName = "NextcloudUnitTests.xctest"
|
||||
BlueprintName = "NextcloudUnitTests"
|
||||
ReferencedContainer = "container:Nextcloud.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
language = "en"
|
||||
region = "US"
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
|
||||
@@ -1,93 +1,125 @@
|
||||
//
|
||||
// NotificationService.swift
|
||||
// Notification Service Extension
|
||||
//
|
||||
// Created by Ivan Sein on 30.01.20.
|
||||
// Author Ivan Sein <ivan@nextcloud.com>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
//
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2020 Ivan Sein
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import UIKit
|
||||
import UserNotifications
|
||||
import os
|
||||
import NextcloudKit
|
||||
|
||||
class NotificationService: UNNotificationServiceExtension {
|
||||
var contentHandler: ((UNNotificationContent) -> Void)?
|
||||
var bestAttemptContent: UNMutableNotificationContent?
|
||||
var request: UNNotificationRequest?
|
||||
private let deliveryLock = OSAllocatedUnfairLock()
|
||||
|
||||
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
|
||||
self.contentHandler = contentHandler
|
||||
self.request = request
|
||||
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
|
||||
|
||||
NextcloudKit.configureLogger(logLevel: .verbose)
|
||||
NextcloudKit.configureLogger(
|
||||
logLevel: .verbose,
|
||||
logDirectory: NCPreferences.sharedLogDirectory
|
||||
)
|
||||
|
||||
if let bestAttemptContent = bestAttemptContent {
|
||||
bestAttemptContent.title = ""
|
||||
bestAttemptContent.body = "Nextcloud notification"
|
||||
do {
|
||||
if let message = bestAttemptContent.userInfo["subject"] as? String {
|
||||
for tableAccount in NCManageDatabase.shared.getAllTableAccount() {
|
||||
guard let privateKey = NCPreferences().getPushNotificationPrivateKey(account: tableAccount.account) else {
|
||||
bestAttemptContent.body = "Error retrieving private key for \(tableAccount.account)"
|
||||
continue
|
||||
}
|
||||
guard let bestAttemptContent else { return }
|
||||
|
||||
let prefixData = Data(privateKey.prefix(8))
|
||||
let prefixBase64 = prefixData.base64EncodedString()
|
||||
nkLog(debug: "🔑 Loaded private key for \(tableAccount.account): prefix(Base64)=\(prefixBase64)")
|
||||
bestAttemptContent.title = ""
|
||||
bestAttemptContent.body = "Nextcloud notification"
|
||||
|
||||
guard let decryptedMessage = NCPushNotificationEncryption.shared().decryptPushNotification(message, withDevicePrivateKey: privateKey) else {
|
||||
bestAttemptContent.body = "Error decryption for \(tableAccount.account)"
|
||||
continue
|
||||
}
|
||||
guard let data = decryptedMessage.data(using: .utf8) else {
|
||||
bestAttemptContent.body = "Error decryption data utf8 for \(tableAccount.account)"
|
||||
continue
|
||||
}
|
||||
var matchedAccount: tableAccount?
|
||||
var payload: [String: AnyObject]?
|
||||
|
||||
if var json = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject],
|
||||
let subject = json["subject"] as? String {
|
||||
bestAttemptContent.body = subject
|
||||
if let pref = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup) {
|
||||
json["account"] = tableAccount.account as AnyObject
|
||||
pref.set(json, forKey: "NOTIFICATION_DATA")
|
||||
pref.synchronize()
|
||||
}
|
||||
} else {
|
||||
bestAttemptContent.body = "Error JSON Serialization for \(tableAccount.account)"
|
||||
}
|
||||
break
|
||||
do {
|
||||
if let message = bestAttemptContent.userInfo["subject"] as? String {
|
||||
for tableAccount in NCManageDatabase.shared.getAllTableAccount() {
|
||||
guard let privateKey = NCPreferences().getPushNotificationPrivateKey(account: tableAccount.account) else {
|
||||
bestAttemptContent.body = "Error retrieving private key for \(tableAccount.account)"
|
||||
continue
|
||||
}
|
||||
|
||||
let prefixData = Data(privateKey.prefix(8))
|
||||
let prefixBase64 = prefixData.base64EncodedString()
|
||||
nkLog(debug: "🔑 Loaded private key for \(tableAccount.account): prefix(Base64)=\(prefixBase64)")
|
||||
|
||||
guard let decryptedMessage = NCPushNotificationEncryption.shared().decryptPushNotification(message, withDevicePrivateKey: privateKey) else {
|
||||
bestAttemptContent.body = "Error decrypting notification for \(tableAccount.account)"
|
||||
continue
|
||||
}
|
||||
guard let data = decryptedMessage.data(using: .utf8) else {
|
||||
bestAttemptContent.body = "Error decrypting UTF8 notification data for \(tableAccount.account)"
|
||||
continue
|
||||
}
|
||||
|
||||
if var json = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject],
|
||||
let subject = json["subject"] as? String {
|
||||
bestAttemptContent.body = subject
|
||||
if let pref = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup) {
|
||||
json["account"] = tableAccount.account as AnyObject
|
||||
pref.set(json, forKey: "NOTIFICATION_DATA")
|
||||
pref.synchronize()
|
||||
}
|
||||
|
||||
matchedAccount = tableAccount
|
||||
payload = json
|
||||
} else {
|
||||
bestAttemptContent.body = "Error with notification JSON for \(tableAccount.account)"
|
||||
}
|
||||
break
|
||||
}
|
||||
} catch let error as NSError {
|
||||
nkLog(error: "Failed : \(error.localizedDescription)")
|
||||
}
|
||||
} catch let error as NSError {
|
||||
nkLog(error: "Failed : \(error.localizedDescription)")
|
||||
}
|
||||
|
||||
guard let tblAccount = matchedAccount,
|
||||
let nid = payload?["nid"] as? Int,
|
||||
payload?["delete"] as? Bool != true,
|
||||
payload?["delete-all"] as? Bool != true else {
|
||||
deliver()
|
||||
return
|
||||
}
|
||||
|
||||
// NextcloudKit Session
|
||||
NextcloudKit.shared.setup(groupIdentifier: NCBrandOptions.shared.capabilitiesGroup, delegate: NCNetworking.shared)
|
||||
NextcloudKit.shared.appendSession(account: tblAccount.account,
|
||||
urlBase: tblAccount.urlBase,
|
||||
user: tblAccount.user,
|
||||
userId: tblAccount.userId,
|
||||
password: NCPreferences().getPassword(account: tblAccount.account),
|
||||
userAgent: userAgent,
|
||||
groupIdentifier: NCBrandOptions.shared.capabilitiesGroup)
|
||||
|
||||
Task {
|
||||
let results = await NextcloudKit.shared.getNotificationsAsync(idNotification: nid,
|
||||
account: tblAccount.account,
|
||||
options: NKRequestOptions(timeout: 20))
|
||||
|
||||
if results.error == .success, let notification = results.notifications?.first {
|
||||
bestAttemptContent.title = notification.message.isEmpty ? NCBrandOptions.shared.brand : notification.subject
|
||||
bestAttemptContent.body = notification.message.isEmpty ? notification.subject : notification.message
|
||||
}
|
||||
|
||||
contentHandler(bestAttemptContent)
|
||||
deliver()
|
||||
}
|
||||
}
|
||||
|
||||
override func serviceExtensionTimeWillExpire() {
|
||||
// Called just before the extension will be terminated by the system.
|
||||
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
|
||||
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
|
||||
bestAttemptContent.title = ""
|
||||
bestAttemptContent.body = "Nextcloud Notification Time Will Expire"
|
||||
contentHandler(bestAttemptContent)
|
||||
deliver()
|
||||
}
|
||||
|
||||
private func deliver() {
|
||||
NextcloudKit.flushLogger()
|
||||
|
||||
let handler = deliveryLock.withLock {
|
||||
let handler = contentHandler
|
||||
contentHandler = nil
|
||||
return handler
|
||||
}
|
||||
|
||||
if let handler, let bestAttemptContent {
|
||||
handler(bestAttemptContent)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,5 @@
|
||||
//
|
||||
// Notification_Service_Extension-Bridging-Header.h
|
||||
// Nextcloud
|
||||
//
|
||||
// Created by Ivan Sein on 30.01.20.
|
||||
// Author Ivan Sein <[email protected]>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
//
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2020 Ivan Sein
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
#import "NCPushNotificationEncryption.h"
|
||||
@@ -0,0 +1,2 @@
|
||||
SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
|
||||
SPDX-License-Identifier: GPL-3.0-or-later
|
||||
@@ -0,0 +1,68 @@
|
||||
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
version = 1
|
||||
SPDX-PackageName = "Nextcloud iOS App"
|
||||
SPDX-PackageSupplier = "Nextcloud GmbH <https://nextcloud.com/impressum/>"
|
||||
SPDX-PackageDownloadLocation = "https://github.com/nextcloud/ios/"
|
||||
|
||||
[[annotations]]
|
||||
path = [".gitattributes", ".gitignore", "iOSClient/.tx/config", "iOSClient/PrivacyInfo.xcprivacy", "iOSClient/Settings/Acknowledgements.rtf"]
|
||||
precedence = "aggregate"
|
||||
SPDX-FileCopyrightText = "2016-2024 Nextcloud GmbH and Nextcloud contributors"
|
||||
SPDX-License-Identifier = "GPL-3.0-or-later"
|
||||
|
||||
[[annotations]]
|
||||
path = ["**/*.storyboard", "**/*.xib"]
|
||||
precedence = "aggregate"
|
||||
SPDX-FileCopyrightText = "2016-2026 Nextcloud GmbH and Nextcloud contributors"
|
||||
SPDX-License-Identifier = "GPL-3.0-or-later"
|
||||
|
||||
[[annotations]]
|
||||
path = ["Nextcloud.xcodeproj/**"]
|
||||
precedence = "aggregate"
|
||||
SPDX-FileCopyrightText = "2016-2026 Nextcloud GmbH and Nextcloud contributors"
|
||||
SPDX-License-Identifier = "GPL-3.0-or-later"
|
||||
|
||||
[[annotations]]
|
||||
path = ["Brand/**", "Widget/Intent/*.lproj/*.intentdefinition"]
|
||||
precedence = "aggregate"
|
||||
SPDX-FileCopyrightText = "2016-2026 Nextcloud GmbH and Nextcloud contributors"
|
||||
SPDX-License-Identifier = "GPL-3.0-or-later"
|
||||
|
||||
[[annotations]]
|
||||
path = ["iOSClient/Images.xcassets/**", "Widget/Assets.xcassets/**", "Action Assistant/Images.xcassets/**"]
|
||||
precedence = "aggregate"
|
||||
SPDX-FileCopyrightText = "2016-2026 Nextcloud GmbH and Nextcloud contributors"
|
||||
SPDX-License-Identifier = "GPL-3.0-or-later"
|
||||
|
||||
[[annotations]]
|
||||
path = ["Animation.gif", "Nextcloud Hub.png", "Reasons to use Nextcloud.pdf", "widget.png"]
|
||||
precedence = "aggregate"
|
||||
SPDX-FileCopyrightText = "2017-2023 Nextcloud GmbH and Nextcloud contributors"
|
||||
SPDX-License-Identifier = "GPL-3.0-or-later"
|
||||
|
||||
[[annotations]]
|
||||
path = ["BackgroundUploadExtension/diagram.png"]
|
||||
precedence = "aggregate"
|
||||
SPDX-FileCopyrightText = "2026 Nextcloud GmbH and Marino Faggiana"
|
||||
SPDX-License-Identifier = "GPL-3.0-or-later"
|
||||
|
||||
# Translations are managed on Transifex; headers here would be overwritten on sync.
|
||||
[[annotations]]
|
||||
path = ["iOSClient/Supporting Files/*.lproj/*.strings", "iOSClient/Supporting Files/*.lproj/*.stringsdict", "Widget/Intent/*.lproj/*.strings"]
|
||||
precedence = "aggregate"
|
||||
SPDX-FileCopyrightText = "2017-2025 Nextcloud translators"
|
||||
SPDX-License-Identifier = "GPL-3.0-or-later"
|
||||
|
||||
# The Nextcloud name and logo are trademarks; see LICENSES/LicenseRef-NextcloudTrademarks.txt
|
||||
[[annotations]]
|
||||
path = ["AppIcon.icon/**", "Brand/Custom.xcassets/AppIcon.appiconset/**", "Brand/Custom.xcassets/logo.imageset/**", "Action Assistant/Images.xcassets/AppIcon.appiconset/**", "Widget/Assets.xcassets/AppIcon.imageset/**", "iOSClient/Images.xcassets/logo.imageset/**"]
|
||||
precedence = "aggregate"
|
||||
SPDX-FileCopyrightText = "Nextcloud GmbH"
|
||||
SPDX-License-Identifier = "LicenseRef-NextcloudTrademarks"
|
||||
|
||||
[[annotations]]
|
||||
path = ["iOSClient/Utility/NYMnemonic/**"]
|
||||
precedence = "aggregate"
|
||||
SPDX-FileCopyrightText = "2014 Nybex, Inc. <https://nybex.com>"
|
||||
SPDX-License-Identifier = "MIT"
|
||||
@@ -34,7 +34,11 @@ class NCShareCell: UITableViewCell {
|
||||
imageCell?.layer.cornerRadius = 6
|
||||
imageCell?.layer.masksToBounds = true
|
||||
|
||||
if let image = UIImage.downsample(imageAt: URL(fileURLWithPath: NSTemporaryDirectory() + fileName), to: CGSize(width: 80, height: 80)) {
|
||||
if let image = UIImage.downsample(
|
||||
imageAt: URL(fileURLWithPath: NSTemporaryDirectory() + fileName),
|
||||
to: CGSize(width: 80, height: 80),
|
||||
scale: traitCollection.displayScale
|
||||
) {
|
||||
imageCell.image = image
|
||||
imageCell.contentMode = .scaleAspectFill
|
||||
} else {
|
||||
|
||||
@@ -104,6 +104,13 @@ extension NCShareExtension: UICollectionViewDataSource {
|
||||
|
||||
cell.setTags(tags: Array(metadata.tags))
|
||||
|
||||
let accessibilityLabel = [metadata.fileNameView, cell.labelInfo.text, cell.labelSubinfo.text]
|
||||
.compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }
|
||||
.filter { !$0.isEmpty }
|
||||
.joined(separator: ", ")
|
||||
cell.setAccessibility(label: accessibilityLabel, value: "")
|
||||
cell.accessibilityTraits = .button
|
||||
|
||||
cell.separator.isHidden = collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1
|
||||
|
||||
return cell
|
||||
|
||||
@@ -12,7 +12,22 @@ extension NCShareExtension {
|
||||
func reloadData() async {
|
||||
let session = NCShareExtensionData.shared.getSession()
|
||||
let layoutForView = NCManageDatabase.shared.getLayoutForView(account: session.account, key: keyLayout, serverUrl: serverUrl)
|
||||
let predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileName != %@ AND directory == true", session.account, serverUrl, NextcloudKit.shared.nkCommonInstance.rootFileName)
|
||||
let showHiddenFiles = NCPreferences().getShowHiddenFiles(account: session.account)
|
||||
let predicate = showHiddenFiles
|
||||
? NSPredicate(
|
||||
format: "account == %@ AND serverUrl == %@ AND fileName != %@ AND directory == true",
|
||||
session.account,
|
||||
serverUrl,
|
||||
NextcloudKit.shared.nkCommonInstance.rootFileName
|
||||
)
|
||||
: NSPredicate(
|
||||
format: "account == %@ AND serverUrl == %@ AND fileName != %@ AND directory == true AND NOT fileName BEGINSWITH[c] %@",
|
||||
session.account,
|
||||
serverUrl,
|
||||
NextcloudKit.shared.nkCommonInstance.rootFileName,
|
||||
"."
|
||||
)
|
||||
|
||||
let metadatas = await NCManageDatabase.shared.getMetadatasAsync(predicate: predicate,
|
||||
withLayout: layoutForView,
|
||||
withAccount: session.account)
|
||||
@@ -45,8 +60,8 @@ extension NCShareExtension {
|
||||
if resultsReadFolder.error == .success {
|
||||
self.metadataFolder = resultsReadFolder.metadataFolder
|
||||
await self.reloadData()
|
||||
} else {
|
||||
self.showAlert(description: resultsReadFolder.error.errorDescription)
|
||||
} else if let message = resultsReadFolder.error.userFriendlyMessage() {
|
||||
self.showAlert(description: message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,8 +34,8 @@ extension NCShareExtension: NCAccountRequestDelegate {
|
||||
vcAccountRequest.delegate = self
|
||||
vcAccountRequest.dismissDidEnterBackground = true
|
||||
|
||||
let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height / 5)
|
||||
let height = min(CGFloat(accounts.count * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
|
||||
let maximumHeight = view.safeAreaLayoutGuide.layoutFrame.height * 0.8
|
||||
let height = min(CGFloat(accounts.count * Int(vcAccountRequest.heightCell) + 45), maximumHeight)
|
||||
|
||||
let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height + 20)
|
||||
|
||||
@@ -53,6 +53,7 @@ extension NCShareExtension: NCAccountRequestDelegate {
|
||||
cancel(with: NCShareExtensionError.noAccount)
|
||||
return
|
||||
}
|
||||
showAccountView()
|
||||
|
||||
NextcloudKit.shared.setup(groupIdentifier: NCBrandOptions.shared.capabilitiesGroup, delegate: NCNetworking.shared)
|
||||
NextcloudKit.shared.appendSession(account: tblAccount.account,
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import UIKit
|
||||
import UniformTypeIdentifiers
|
||||
import NextcloudKit
|
||||
import LucidBanner
|
||||
import SwiftUI
|
||||
@@ -51,6 +52,9 @@ class NCShareExtension: UIViewController {
|
||||
var token: Int?
|
||||
var banner: LucidBanner?
|
||||
var sceneIdentifier: String = UUID().uuidString
|
||||
private var isPresentingNoAccountAlert = false
|
||||
private var isPresentingPasscode = false
|
||||
private var isPasscodeAuthenticated = false
|
||||
|
||||
// MARK: - View Life Cycle
|
||||
|
||||
@@ -86,7 +90,10 @@ class NCShareExtension: UIViewController {
|
||||
uploadView.addGestureRecognizer(uploadGesture)
|
||||
|
||||
let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, utility.getVersionBuild())
|
||||
NextcloudKit.configureLogger(logLevel: (NCBrandOptions.shared.disable_log ? .disabled : NCPreferences().log))
|
||||
NextcloudKit.configureLogger(
|
||||
logLevel: NCBrandOptions.shared.disable_log ? .disabled : NCPreferences().log,
|
||||
logDirectory: NCPreferences.sharedLogDirectory
|
||||
)
|
||||
|
||||
nkLog(start: "Start Share session " + versionNextcloudiOS)
|
||||
|
||||
@@ -100,11 +107,13 @@ class NCShareExtension: UIViewController {
|
||||
}
|
||||
|
||||
NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil) { _ in
|
||||
if NCPreferences().presentPasscode {
|
||||
NCPasscode.shared.presentPasscode(viewController: self, delegate: self) {
|
||||
NCPasscode.shared.enableTouchFaceID()
|
||||
}
|
||||
guard !self.maintenanceMode,
|
||||
self.validateAccount() else {
|
||||
return
|
||||
}
|
||||
|
||||
self.isPasscodeAuthenticated = false
|
||||
self.requestPasscodeIfNeeded()
|
||||
}
|
||||
|
||||
// Verify version
|
||||
@@ -138,11 +147,8 @@ class NCShareExtension: UIViewController {
|
||||
}
|
||||
}
|
||||
|
||||
guard NCShareExtensionData.shared.getTblAccoun() != nil,
|
||||
!NCPasscode.shared.isPasscodeReset else {
|
||||
return showAlert(description: "_no_active_account_") {
|
||||
self.cancel(with: .noAccount)
|
||||
}
|
||||
guard validateAccount() else {
|
||||
return
|
||||
}
|
||||
|
||||
guard let inputItems = extensionContext?.inputItems as? [NSExtensionItem] else {
|
||||
@@ -150,20 +156,18 @@ class NCShareExtension: UIViewController {
|
||||
return
|
||||
}
|
||||
|
||||
NCFilesExtensionHandler(items: inputItems) { fileNames in
|
||||
self.filesName = fileNames
|
||||
DispatchQueue.main.async {
|
||||
self.setCommandView()
|
||||
Task { @MainActor in
|
||||
NCFilesExtensionHandler(items: inputItems) { fileNames in
|
||||
self.filesName = fileNames
|
||||
DispatchQueue.main.async {
|
||||
self.setCommandView()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if NCPreferences().presentPasscode {
|
||||
NCPasscode.shared.presentPasscode(viewController: self, delegate: self) {
|
||||
NCPasscode.shared.enableTouchFaceID()
|
||||
}
|
||||
}
|
||||
self.requestPasscodeIfNeeded()
|
||||
|
||||
self.collectionView.reloadData()
|
||||
self.collectionView.reloadData()
|
||||
}
|
||||
}
|
||||
|
||||
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
|
||||
@@ -179,6 +183,58 @@ class NCShareExtension: UIViewController {
|
||||
tableView.visibleCells.forEach { $0.setNeedsLayout() }
|
||||
}
|
||||
|
||||
private func validateAccount() -> Bool {
|
||||
guard !NCPasscodeModel.isPasscodeReset else {
|
||||
return showNoAccountAlert()
|
||||
}
|
||||
|
||||
if let account = NCShareExtensionData.shared.getTblAccoun()?.account,
|
||||
NCManageDatabase.shared.getTableAccount(account: account) != nil {
|
||||
return true
|
||||
}
|
||||
|
||||
guard let activeAccount = NCManageDatabase.shared.getActiveTableAccount() else {
|
||||
return showNoAccountAlert()
|
||||
}
|
||||
|
||||
clearAccountView()
|
||||
accountRequestChangeAccount(account: activeAccount.account, controller: nil)
|
||||
return true
|
||||
}
|
||||
|
||||
private func showNoAccountAlert() -> Bool {
|
||||
clearAccountView()
|
||||
if !isPresentingNoAccountAlert {
|
||||
isPresentingNoAccountAlert = true
|
||||
showAlert(description: "_no_active_account_") {
|
||||
self.cancel(with: .noAccount)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private func clearAccountView() {
|
||||
dataSourceTask?.cancel()
|
||||
dataSourceTask = nil
|
||||
dataSource = NCCollectionViewDataSource()
|
||||
metadataFolder = nil
|
||||
|
||||
collectionView.isHidden = true
|
||||
tableView.isHidden = true
|
||||
commandView.isHidden = true
|
||||
separatorView.isHidden = true
|
||||
navigationItem.leftBarButtonItems = nil
|
||||
navigationItem.title = NCBrandOptions.shared.brand
|
||||
view.layoutIfNeeded()
|
||||
}
|
||||
|
||||
func showAccountView() {
|
||||
collectionView.isHidden = false
|
||||
tableView.isHidden = false
|
||||
commandView.isHidden = false
|
||||
separatorView.isHidden = false
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
func cancel(with error: NCShareExtensionError? = nil) {
|
||||
@@ -283,13 +339,15 @@ class NCShareExtension: UIViewController {
|
||||
guard let capabilities = NCNetworking.shared.capabilities[session.account] else {
|
||||
return
|
||||
}
|
||||
let alertController = UIAlertController.createFolderWith(serverUrl: serverUrl, session: session, capabilities: capabilities) { error in
|
||||
let alertController = UIAlertController.createFolderWith(serverUrl: serverUrl, session: session, capabilities: capabilities) { error, folderName in
|
||||
let context = NCErrorContext.createFolder(folderName: folderName)
|
||||
|
||||
if error == .success {
|
||||
Task {
|
||||
await self.loadFolder()
|
||||
}
|
||||
} else {
|
||||
self.showAlert(title: "_error_createsubfolders_upload_", description: error.errorDescription)
|
||||
} else if let message = error.userFriendlyMessage(for: context) {
|
||||
self.showAlert(title: context.failureTitle ?? "_error_", description: message)
|
||||
}
|
||||
}
|
||||
self.present(alertController, animated: true)
|
||||
@@ -378,7 +436,12 @@ extension NCShareExtension {
|
||||
|
||||
@MainActor
|
||||
func uploadAndExit() async {
|
||||
// A Share extension process can be reused by the system. Treat each
|
||||
// explicit share operation as a new server-key validation cycle.
|
||||
await NCNetworkingE2EE.beginNewServerKeyValidationCycle()
|
||||
|
||||
var error: NKError?
|
||||
var errorContext: NCErrorContext = .generic
|
||||
guard let window = self.view.window else {
|
||||
return
|
||||
}
|
||||
@@ -403,6 +466,7 @@ extension NCShareExtension {
|
||||
|
||||
error = await self.upload(metadata: metadata)
|
||||
if error != .success {
|
||||
errorContext = .upload(fileName: metadata.fileNameView)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -410,7 +474,11 @@ extension NCShareExtension {
|
||||
if error == .success {
|
||||
banner?.update(payload: LucidBannerPayload.Update(stage: .success, horizontalLayout: .centered(width: 100)), for: self.token)
|
||||
} else {
|
||||
banner?.update(payload: LucidBannerPayload.Update(subtitle: error?.errorDescription, stage: .error), for: self.token)
|
||||
let payload = LucidBannerPayload.Update(title: errorContext.failureTitle ?? NSLocalizedString("_error_", comment: ""),
|
||||
subtitle: error?.userFriendlyMessage(for: errorContext) ?? "",
|
||||
stage: .error)
|
||||
|
||||
banner?.update(payload: payload, for: self.token)
|
||||
}
|
||||
|
||||
Task { @MainActor in
|
||||
@@ -433,12 +501,8 @@ extension NCShareExtension {
|
||||
metadata.serverUrlFileName = utilityFileSystem.createServerUrl(serverUrl: metadata.serverUrl, fileName: metadata.fileName)
|
||||
|
||||
// CHUNK
|
||||
var chunkSize = NCGlobal.shared.chunkSizeMBCellular
|
||||
if NCNetworking.shared.networkReachability == NKTypeReachability.reachableEthernetOrWiFi {
|
||||
chunkSize = NCGlobal.shared.chunkSizeMBEthernetOrWiFi
|
||||
}
|
||||
if metadata.size > chunkSize {
|
||||
metadata.chunk = chunkSize
|
||||
if metadata.size > self.global.chunkSize {
|
||||
metadata.chunk = self.global.chunkSize
|
||||
} else {
|
||||
metadata.chunk = 0
|
||||
}
|
||||
@@ -514,18 +578,22 @@ extension NCShareExtension {
|
||||
}
|
||||
}
|
||||
|
||||
extension NCShareExtension: NCPasscodeDelegate {
|
||||
func passcodeReset(_ passcodeViewController: TOPasscodeViewController) {
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
|
||||
passcodeViewController.dismiss(animated: false)
|
||||
self.cancel(with: .noAccount)
|
||||
}
|
||||
}
|
||||
|
||||
func evaluatePolicy(_ passcodeViewController: TOPasscodeViewController, isCorrectCode: Bool) {
|
||||
if !isCorrectCode {
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
|
||||
passcodeViewController.dismiss(animated: false)
|
||||
extension NCShareExtension {
|
||||
/// Require authentication once per foreground session without reopening after dismissal.
|
||||
private func requestPasscodeIfNeeded() {
|
||||
guard NCPreferences().presentPasscode,
|
||||
!isPasscodeAuthenticated,
|
||||
!isPresentingPasscode else { return }
|
||||
isPresentingPasscode = true
|
||||
// Embed in the content controller; the helper hides the outer navigation bar.
|
||||
NCPasscodeView.embed(in: self) { [weak self] result in
|
||||
guard let self else { return }
|
||||
self.isPresentingPasscode = false
|
||||
switch result {
|
||||
case .authenticated:
|
||||
self.isPasscodeAuthenticated = true
|
||||
_ = self.validateAccount()
|
||||
case .cancelled, .reset, .configured, .disabled:
|
||||
self.cancel(with: .noAccount)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2016 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
// Use this file to import your target's public headers that you would like to expose to Swift.
|
||||
//
|
||||
// Use this file to import your target's public headers that you would like to expose to Swift.
|
||||
|
||||
#import "NCEndToEndEncryption.h"
|
||||
#import "UIImage+animatedGIF.h"
|
||||
#import "TOPasscodeViewController.h"
|
||||
@@ -1,10 +1,6 @@
|
||||
//
|
||||
// NextcloudIntegrationTests.swift
|
||||
// NextcloudIntegrationTests
|
||||
//
|
||||
// Created by Milen Pivchev on 5/19/23.
|
||||
// Copyright © 2023 Marino Faggiana. All rights reserved.
|
||||
//
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2023 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import XCTest
|
||||
import NextcloudKit
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2025 Iva Horn
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// There are no unit tests yet.
|
||||
// This is an empty placeholder file.
|
||||
// The compiler requires at least an empty file for every target.
|
||||
@@ -1,5 +1,6 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2025 Milen Pivchev
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
@@ -58,92 +59,136 @@ class BaseUIXCTestCase: XCTestCase {
|
||||
try await Task.sleep(for: .seconds(TestConstants.controlExistenceTimeout))
|
||||
}
|
||||
|
||||
///
|
||||
/// Automation of the sign-in, if required.
|
||||
///
|
||||
///
|
||||
/// Sign in through the app's authentication flow, supporting system authentication and the embedded fallback.
|
||||
func logIn() async throws {
|
||||
guard app.buttons["login"].exists else {
|
||||
return
|
||||
let login = app.buttons["login"]
|
||||
let deadline = Date().addingTimeInterval(30)
|
||||
// Startup can restore the main interface after the first accessibility snapshot.
|
||||
// Wait for either destination instead of assuming that the login screen will appear.
|
||||
repeat {
|
||||
if app.buttons["openSidebar"].exists || app.buttons["accountSwitcher"].exists {
|
||||
return
|
||||
}
|
||||
if login.exists && login.isHittable {
|
||||
break
|
||||
}
|
||||
try await Task.sleep(for: .milliseconds(250))
|
||||
} while Date() < deadline
|
||||
guard login.exists else {
|
||||
attachAuthenticationDiagnostics()
|
||||
throw UITestError.waitForExistence(login)
|
||||
}
|
||||
login.tap()
|
||||
|
||||
app.buttons["login"].tap()
|
||||
|
||||
let serverAddressTextField = app.textFields["serverAddress"].firstMatch
|
||||
guard serverAddressTextField.await() else { return }
|
||||
|
||||
try await aSmallMoment()
|
||||
|
||||
serverAddressTextField.tap()
|
||||
serverAddressTextField.typeText(TestConstants.server)
|
||||
|
||||
let serverAddress = app.textFields["serverAddress"].firstMatch
|
||||
guard serverAddress.await() else { throw UITestError.waitForExistence(serverAddress) }
|
||||
serverAddress.tap()
|
||||
serverAddress.typeText(TestConstants.server)
|
||||
app.buttons["submitServerAddress"].tap()
|
||||
|
||||
try await aSmallMoment()
|
||||
|
||||
let webView = app.webViews.firstMatch
|
||||
|
||||
guard webView.await() else {
|
||||
throw UITestError.waitForExistence(webView)
|
||||
let webView = try await authenticationWebView()
|
||||
let username = webView.textFields.firstMatch
|
||||
let loginButton = webView.buttons["Log in"].firstMatch
|
||||
if !username.exists, loginButton.await(timeout: 5) {
|
||||
loginButton.tap()
|
||||
}
|
||||
|
||||
// try await aSmallMoment()
|
||||
|
||||
let loginButton = webView.buttons["Log in"]
|
||||
|
||||
// try await aSmallMoment()
|
||||
|
||||
if loginButton.await() {
|
||||
if username.await() {
|
||||
username.tap()
|
||||
username.typeText(TestConstants.username)
|
||||
let password = webView.secureTextFields.firstMatch
|
||||
guard password.await() else { throw UITestError.waitForExistence(password) }
|
||||
password.tap()
|
||||
password.typeText(TestConstants.password)
|
||||
guard loginButton.await() else { throw UITestError.waitForExistence(loginButton) }
|
||||
loginButton.tap()
|
||||
}
|
||||
|
||||
// try await aSmallMoment()
|
||||
|
||||
let usernameTextField = webView.textFields.firstMatch
|
||||
|
||||
if usernameTextField.await() {
|
||||
|
||||
try await aSmallMoment()
|
||||
|
||||
guard usernameTextField.await() else { return }
|
||||
usernameTextField.tap()
|
||||
|
||||
try await aSmallMoment()
|
||||
|
||||
usernameTextField.typeText(TestConstants.username)
|
||||
|
||||
try await aSmallMoment()
|
||||
|
||||
let passwordSecureTextField = webView.secureTextFields.firstMatch
|
||||
|
||||
try await aSmallMoment()
|
||||
|
||||
passwordSecureTextField.tap()
|
||||
|
||||
|
||||
try await aSmallMoment()
|
||||
|
||||
passwordSecureTextField.typeText(TestConstants.password)
|
||||
|
||||
try await aSmallMoment()
|
||||
|
||||
webView.buttons.firstMatch.tap()
|
||||
let grant = webView.buttons["Grant access"]
|
||||
guard try await waitForAuthenticationConsent() else {
|
||||
attachAuthenticationDiagnostics()
|
||||
throw UITestError.waitForExistence(grant)
|
||||
}
|
||||
|
||||
try await aSmallMoment()
|
||||
|
||||
let grantButton = webView.buttons["Grant access"]
|
||||
|
||||
guard grantButton.await() else {
|
||||
throw UITestError.waitForExistence(grantButton)
|
||||
let sidebar = app.buttons["openSidebar"].firstMatch
|
||||
guard sidebar.await(timeout: 30) || app.buttons["accountSwitcher"].exists else {
|
||||
attachAuthenticationDiagnostics()
|
||||
throw UITestError.waitForExistence(sidebar)
|
||||
}
|
||||
}
|
||||
|
||||
grantButton.tap()
|
||||
grantButton.awaitInexistence()
|
||||
/// Waiting alone does not trigger interruption monitors; dismiss password prompts in their owning process.
|
||||
private func waitForAuthenticationConsent() async throws -> Bool {
|
||||
let browsers = [app!, XCUIApplication(bundleIdentifier: "com.apple.SafariViewService")]
|
||||
let hosts = browsers + [XCUIApplication(bundleIdentifier: "com.apple.springboard")]
|
||||
let deadline = Date().addingTimeInterval(30)
|
||||
var passwordPromptDismissed = false
|
||||
repeat {
|
||||
promptSearch: for host in hosts where !passwordPromptDismissed && host.state != .notRunning {
|
||||
for label in ["Not Now", "Non ora", "Ora no"] {
|
||||
let button = host.buttons[label].firstMatch
|
||||
if button.exists && button.isHittable {
|
||||
button.tap()
|
||||
passwordPromptDismissed = true
|
||||
_ = button.waitForNonExistence(timeout: 5)
|
||||
break promptSearch
|
||||
}
|
||||
}
|
||||
}
|
||||
for browser in browsers where browser.state != .notRunning {
|
||||
let grant = browser.webViews.buttons["Grant access"].firstMatch
|
||||
if grant.exists && grant.isHittable {
|
||||
grant.tap()
|
||||
return true
|
||||
}
|
||||
}
|
||||
try await Task.sleep(for: .milliseconds(250))
|
||||
} while Date() < deadline
|
||||
return false
|
||||
}
|
||||
|
||||
app.buttons["accountSwitcher"].await()
|
||||
/// ASWebAuthenticationSession may expose its UI in SafariViewService rather than in the app hierarchy.
|
||||
private func authenticationWebView() async throws -> XCUIElement {
|
||||
let browsers = [app!, XCUIApplication(bundleIdentifier: "com.apple.SafariViewService")]
|
||||
let promptHosts = browsers + [XCUIApplication(bundleIdentifier: "com.apple.springboard")]
|
||||
// The app tries HTTPS first, even for the HTTP-only localhost test server.
|
||||
// Allow the initial URLSession request to time out before its HTTP fallback starts.
|
||||
let timeout = URLSessionConfiguration.default.timeoutIntervalForRequest + 30
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
repeat {
|
||||
for host in promptHosts where host.state != .notRunning {
|
||||
for label in ["Continue", "Allow"] {
|
||||
let button = host.alerts.buttons[label].firstMatch
|
||||
if button.exists && button.isHittable {
|
||||
button.tap()
|
||||
}
|
||||
}
|
||||
}
|
||||
for browser in browsers where browser.state != .notRunning {
|
||||
let webView = browser.webViews.firstMatch
|
||||
if webView.exists {
|
||||
return webView
|
||||
}
|
||||
}
|
||||
try await Task.sleep(for: .milliseconds(250))
|
||||
} while Date() < deadline
|
||||
|
||||
try await aSmallMoment()
|
||||
attachAuthenticationDiagnostics()
|
||||
throw UITestError.waitForExistence(app.webViews.firstMatch)
|
||||
}
|
||||
|
||||
/// Keep login diagnostics in the xcresult instead of losing the context on a CI failure.
|
||||
private func attachAuthenticationDiagnostics() {
|
||||
let screenshot = XCTAttachment(screenshot: XCUIScreen.main.screenshot())
|
||||
screenshot.name = "Authentication screen"
|
||||
screenshot.lifetime = .keepAlways
|
||||
add(screenshot)
|
||||
for host in [app!, XCUIApplication(bundleIdentifier: "com.apple.SafariViewService"), XCUIApplication(bundleIdentifier: "com.apple.springboard")]
|
||||
where host.state == .runningForeground {
|
||||
let hierarchy = XCTAttachment(string: host.debugDescription)
|
||||
hierarchy.name = "Authentication UI hierarchy"
|
||||
hierarchy.lifetime = .keepAlways
|
||||
add(hierarchy)
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import XCTest
|
||||
|
||||
/// Exercises real settings and app-lock flows against the standard UI-test server.
|
||||
@MainActor
|
||||
final class PasscodeUITests: BaseUIXCTestCase {
|
||||
private let originalCode = "135790"
|
||||
private let replacementCode = "246801"
|
||||
private let wrongCode = "000000"
|
||||
private let resetTestLockoutSeconds = 10
|
||||
private var currentCode: String?
|
||||
private let languageArguments = ["-AppleLanguages", "(en)", "-AppleLocale", "en_US"]
|
||||
|
||||
private var title: XCUIElement { app.staticTexts["passcode.title"] }
|
||||
private var closeButton: XCUIElement { app.buttons["passcode.close"] }
|
||||
private var lockWindow: XCUIElement { app.windows["passcode.window"] }
|
||||
private var lockout: XCUIElement { app.staticTexts["passcode.lockout.remaining"] }
|
||||
private var lockSetting: XCUIElement { app.buttons["settings.passcode.toggle"] }
|
||||
private var changeSetting: XCUIElement { app.buttons["settings.passcode.change"] }
|
||||
|
||||
override func setUp() async throws {
|
||||
try await super.setUp()
|
||||
continueAfterFailure = false
|
||||
addUIInterruptionMonitor(withDescription: "Allow Notifications", for: "Allow")
|
||||
app = XCUIApplication()
|
||||
app.launchArguments = ["UI_TESTING", "UI_TESTING_PASSCODE", "UI_TESTING_NO_EXIT"] + languageArguments
|
||||
if name.contains("testAppResetAfterTenFailuresAcrossLockouts") {
|
||||
app.launchEnvironment["UI_TESTING_PASSCODE_LOCKOUT_SECONDS"] = String(resetTestLockoutSeconds)
|
||||
}
|
||||
app.launch()
|
||||
try await logIn()
|
||||
openSettings()
|
||||
XCTAssertFalse(changeSetting.exists, "Each test must start with app lock disabled.")
|
||||
}
|
||||
|
||||
override func tearDown() async throws {
|
||||
// Avoid leaving the simulator locked if an assertion interrupted a test.
|
||||
if let currentCode, app != nil {
|
||||
app.activate()
|
||||
if lockout.exists {
|
||||
_ = lockout.waitForNonExistence(timeout: 65)
|
||||
}
|
||||
if title.exists && !closeButton.exists {
|
||||
clearPartialCode()
|
||||
enter(currentCode)
|
||||
}
|
||||
if closeButton.exists {
|
||||
closeButton.tap()
|
||||
}
|
||||
if !lockSetting.exists {
|
||||
openSettings()
|
||||
}
|
||||
if changeSetting.exists {
|
||||
lockSetting.tap()
|
||||
enter(currentCode)
|
||||
_ = title.waitForNonExistence(timeout: TestConstants.controlExistenceTimeout)
|
||||
}
|
||||
}
|
||||
app?.terminate()
|
||||
try await super.tearDown()
|
||||
}
|
||||
|
||||
func testCreateChangeAndDisablePasscode() {
|
||||
createPasscode()
|
||||
changeSetting.tap()
|
||||
assertTitle("Enter Passcode")
|
||||
enter(originalCode)
|
||||
assertTitle("Enter a new passcode")
|
||||
enter(replacementCode)
|
||||
assertTitle("Confirm new passcode")
|
||||
enter(replacementCode)
|
||||
currentCode = replacementCode
|
||||
XCTAssertTrue(title.waitForNonExistence(timeout: TestConstants.controlExistenceTimeout))
|
||||
|
||||
lockSetting.tap()
|
||||
assertTitle("Enter Passcode")
|
||||
enter(originalCode)
|
||||
XCTAssertTrue(app.staticTexts["passcode.error"].waitForExistence(timeout: 5))
|
||||
XCTAssertEqual(app.staticTexts["passcode.error"].label, "Incorrect passcode. Try again.")
|
||||
enter(replacementCode)
|
||||
XCTAssertTrue(title.waitForNonExistence(timeout: TestConstants.controlExistenceTimeout))
|
||||
XCTAssertFalse(changeSetting.exists)
|
||||
currentCode = nil
|
||||
}
|
||||
|
||||
/// Regression for the reported brute-force bypass when disabling app lock.
|
||||
func testDisableLockoutSurvivesReopeningBackgroundAndRelaunch() {
|
||||
createPasscode()
|
||||
lockSetting.tap()
|
||||
enter(wrongCode)
|
||||
closeButton.tap()
|
||||
XCTAssertTrue(title.waitForNonExistence(timeout: 5))
|
||||
lockSetting.tap()
|
||||
enter(wrongCode)
|
||||
closeButton.tap()
|
||||
XCTAssertTrue(title.waitForNonExistence(timeout: 5))
|
||||
lockSetting.tap()
|
||||
enter(wrongCode)
|
||||
assertLockedOut()
|
||||
let deadline = Date().addingTimeInterval(TimeInterval(remainingSeconds()))
|
||||
|
||||
// The third error promotes the request to a mandatory app lock.
|
||||
XCTAssertTrue(lockWindow.waitForExistence(timeout: 5))
|
||||
XCTAssertFalse(closeButton.exists)
|
||||
XCTAssertFalse(lockSetting.isHittable)
|
||||
assertLockedOut()
|
||||
waitForCountdown(toDropBelow: 56)
|
||||
assertOriginalDeadline(deadline)
|
||||
|
||||
// Background and foreground must preserve the mandatory lock.
|
||||
backgroundAndActivate()
|
||||
assertTitle("Enter Passcode")
|
||||
XCTAssertFalse(closeButton.exists)
|
||||
assertLockedOut()
|
||||
assertOriginalDeadline(deadline)
|
||||
|
||||
// Relaunch without setup flags: credentials and the deadline must persist in Keychain.
|
||||
app.terminate()
|
||||
app.launchArguments = languageArguments
|
||||
app.launch()
|
||||
assertTitle("Enter Passcode")
|
||||
XCTAssertFalse(closeButton.exists)
|
||||
assertLockedOut()
|
||||
assertOriginalDeadline(deadline)
|
||||
|
||||
XCTAssertTrue(lockout.waitForNonExistence(timeout: max(0, deadline.timeIntervalSinceNow) + 5))
|
||||
enter(originalCode)
|
||||
XCTAssertTrue(title.waitForNonExistence(timeout: TestConstants.controlExistenceTimeout))
|
||||
}
|
||||
|
||||
/// Changing the code must enforce the same persisted protection as disabling it.
|
||||
func testChangePasscodeCannotResetFailedAttemptsByReopening() {
|
||||
createPasscode()
|
||||
for attempt in 1...3 {
|
||||
changeSetting.tap()
|
||||
assertTitle("Enter Passcode")
|
||||
enter(wrongCode)
|
||||
if attempt < 3 {
|
||||
closeButton.tap()
|
||||
XCTAssertTrue(title.waitForNonExistence(timeout: 5))
|
||||
}
|
||||
}
|
||||
assertLockedOut()
|
||||
let deadline = Date().addingTimeInterval(TimeInterval(remainingSeconds()))
|
||||
XCTAssertTrue(lockWindow.waitForExistence(timeout: 5))
|
||||
XCTAssertFalse(closeButton.exists)
|
||||
XCTAssertFalse(changeSetting.isHittable)
|
||||
XCTAssertFalse(lockSetting.isHittable)
|
||||
assertOriginalDeadline(deadline)
|
||||
|
||||
// Waiting unlocks the keypad, never the app itself.
|
||||
XCTAssertTrue(lockout.waitForNonExistence(timeout: max(0, deadline.timeIntervalSinceNow) + 5))
|
||||
XCTAssertTrue(lockWindow.exists)
|
||||
XCTAssertFalse(closeButton.exists)
|
||||
XCTAssertFalse(changeSetting.isHittable)
|
||||
enter(originalCode)
|
||||
XCTAssertTrue(lockWindow.waitForNonExistence(timeout: 5))
|
||||
XCTAssertTrue(changeSetting.waitForExistence(timeout: 5))
|
||||
}
|
||||
|
||||
func testBackgroundCannotBypassMandatoryAppLock() {
|
||||
createPasscode()
|
||||
backgroundAndActivate()
|
||||
for _ in 0..<2 {
|
||||
assertTitle("Enter Passcode")
|
||||
XCTAssertFalse(closeButton.exists)
|
||||
XCTAssertFalse(lockSetting.isHittable, "Protected settings must remain inaccessible.")
|
||||
let start = app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.25))
|
||||
let end = app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.8))
|
||||
start.press(forDuration: 0.1, thenDragTo: end)
|
||||
XCTAssertTrue(title.exists, "Dragging must not dismiss the mandatory lock.")
|
||||
backgroundAndActivate()
|
||||
}
|
||||
enter(originalCode)
|
||||
XCTAssertTrue(title.waitForNonExistence(timeout: TestConstants.controlExistenceTimeout))
|
||||
XCTAssertTrue(lockSetting.waitForExistence(timeout: 5), "Unlocking must preserve the Settings screen.")
|
||||
}
|
||||
|
||||
/// An informational sheet stays in the app window while the mandatory lock covers it.
|
||||
func testAppLockAppearsAbovePresentedSheet() {
|
||||
createPasscode()
|
||||
let acknowledgements = app.buttons["Acknowledgements"]
|
||||
scrollTo(acknowledgements)
|
||||
acknowledgements.tap()
|
||||
let close = app.buttons["settings.acknowledgements.close"]
|
||||
XCTAssertTrue(close.waitForExistence(timeout: 5))
|
||||
|
||||
backgroundAndActivate()
|
||||
guard lockWindow.waitForExistence(timeout: 5) else {
|
||||
let screenshot = XCTAttachment(screenshot: XCUIScreen.main.screenshot())
|
||||
screenshot.name = "App lock above acknowledgements"
|
||||
screenshot.lifetime = .keepAlways
|
||||
add(screenshot)
|
||||
let hierarchy = XCTAttachment(string: app.debugDescription)
|
||||
hierarchy.name = "App lock UI hierarchy"
|
||||
hierarchy.lifetime = .keepAlways
|
||||
add(hierarchy)
|
||||
XCTFail("App-lock window missing after foreground. Passcode title exists: \(title.exists); acknowledgements close exists: \(close.exists).")
|
||||
return
|
||||
}
|
||||
assertTitle("Enter Passcode")
|
||||
XCTAssertFalse(close.isHittable)
|
||||
enter(originalCode)
|
||||
XCTAssertTrue(lockWindow.waitForNonExistence(timeout: 5))
|
||||
XCTAssertTrue(close.isHittable, "Unlocking must preserve the sheet underneath.")
|
||||
close.tap()
|
||||
scrollTo(lockSetting, towardsTop: true)
|
||||
}
|
||||
|
||||
/// An existing confirmation alert cannot intercept or prevent the app-lock window.
|
||||
func testAppLockAppearsAbovePresentedAlert() {
|
||||
createPasscode()
|
||||
let advanced = app.buttons["Advanced"]
|
||||
scrollTo(advanced)
|
||||
advanced.tap()
|
||||
let clearCache = app.buttons["Clear cache"]
|
||||
scrollTo(clearCache)
|
||||
clearCache.tap()
|
||||
let cancel = app.alerts.firstMatch.buttons["Cancel"]
|
||||
XCTAssertTrue(cancel.waitForExistence(timeout: 5))
|
||||
|
||||
backgroundAndActivate()
|
||||
XCTAssertTrue(lockWindow.waitForExistence(timeout: 5))
|
||||
assertTitle("Enter Passcode")
|
||||
XCTAssertFalse(cancel.isHittable)
|
||||
enter(originalCode)
|
||||
XCTAssertTrue(lockWindow.waitForNonExistence(timeout: 5))
|
||||
XCTAssertTrue(cancel.isHittable, "Unlocking must preserve the confirmation alert underneath.")
|
||||
cancel.tap()
|
||||
app.navigationBars["Advanced"].buttons["Settings"].tap()
|
||||
scrollTo(lockSetting, towardsTop: true)
|
||||
}
|
||||
|
||||
/// Waiting out each three-attempt lockout must not reset the ten-attempt app-wipe counter.
|
||||
func testAppResetAfterTenFailuresAcrossLockouts() {
|
||||
createPasscode()
|
||||
let resetSetting = app.switches["settings.passcode.reset"]
|
||||
for _ in 0..<3 where !resetSetting.isHittable {
|
||||
app.swipeUp()
|
||||
}
|
||||
XCTAssertTrue(resetSetting.waitForExistence(timeout: 5))
|
||||
// SwiftUI can expose the labelled row as a switch containing the actual control.
|
||||
let nestedSwitch = resetSetting.switches.firstMatch
|
||||
let resetControl = nestedSwitch.exists ? nestedSwitch : resetSetting
|
||||
XCTAssertEqual(resetControl.value as? String, "0")
|
||||
if nestedSwitch.exists {
|
||||
resetControl.tap()
|
||||
} else {
|
||||
// In the English test layout the switch is at the trailing edge of the row.
|
||||
resetControl.coordinate(withNormalizedOffset: CGVector(dx: 0.95, dy: 0.5)).tap()
|
||||
}
|
||||
let resetEnabled = XCTNSPredicateExpectation(predicate: NSPredicate(format: "value == %@", "1"), object: resetControl)
|
||||
guard XCTWaiter.wait(for: [resetEnabled], timeout: 5) == .completed else {
|
||||
let screenshot = XCTAttachment(screenshot: XCUIScreen.main.screenshot())
|
||||
screenshot.name = "Reset setting after tap"
|
||||
screenshot.lifetime = .keepAlways
|
||||
add(screenshot)
|
||||
let hierarchy = XCTAttachment(string: app.debugDescription)
|
||||
hierarchy.name = "Reset setting UI hierarchy"
|
||||
hierarchy.lifetime = .keepAlways
|
||||
add(hierarchy)
|
||||
XCTFail("The reset switch did not become enabled after tapping it.")
|
||||
return
|
||||
}
|
||||
|
||||
backgroundAndActivate()
|
||||
assertTitle("Enter Passcode")
|
||||
for attempt in 1...10 {
|
||||
enter(wrongCode)
|
||||
if attempt.isMultiple(of: 3) {
|
||||
assertLockedOut()
|
||||
XCTAssertTrue(lockout.waitForNonExistence(timeout: TimeInterval(resetTestLockoutSeconds + 5)))
|
||||
XCTAssertTrue(app.buttons["passcode.digit.1"].isEnabled)
|
||||
} else if attempt < 10 {
|
||||
XCTAssertTrue(title.exists, "The app must remain locked until the reset threshold.")
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for real cleanup, then terminate through XCTest to avoid TSan's exit finalizer.
|
||||
XCTAssertTrue(app.otherElements["uiTesting.resetCompleted"].waitForExistence(timeout: 10))
|
||||
currentCode = nil
|
||||
app.terminate()
|
||||
// Relaunch without setup flags so they cannot hide an incomplete reset.
|
||||
app.launchArguments = languageArguments
|
||||
app.launch()
|
||||
XCTAssertTrue(app.buttons["login"].waitForExistence(timeout: TestConstants.controlExistenceTimeout))
|
||||
XCTAssertFalse(title.exists, "The app reset must remove the stored passcode.")
|
||||
}
|
||||
|
||||
private func createPasscode() {
|
||||
lockSetting.tap()
|
||||
assertTitle("Enter a new passcode")
|
||||
enter(originalCode)
|
||||
assertTitle("Confirm new passcode")
|
||||
enter(originalCode)
|
||||
currentCode = originalCode
|
||||
XCTAssertTrue(title.waitForNonExistence(timeout: TestConstants.controlExistenceTimeout))
|
||||
XCTAssertTrue(changeSetting.waitForExistence(timeout: 5))
|
||||
}
|
||||
|
||||
private func openSettings() {
|
||||
let sidebar = app.buttons["openSidebar"].firstMatch
|
||||
XCTAssertTrue(sidebar.waitForExistence(timeout: TestConstants.controlExistenceTimeout))
|
||||
sidebar.tap()
|
||||
let settings = app.buttons["sidebarSettings"]
|
||||
XCTAssertTrue(settings.waitForExistence(timeout: 5))
|
||||
settings.tap()
|
||||
XCTAssertTrue(lockSetting.waitForExistence(timeout: 5))
|
||||
}
|
||||
|
||||
private func scrollTo(_ element: XCUIElement, towardsTop: Bool = false) {
|
||||
for _ in 0..<6 where !element.isHittable {
|
||||
if towardsTop {
|
||||
app.swipeDown()
|
||||
} else {
|
||||
app.swipeUp()
|
||||
}
|
||||
}
|
||||
XCTAssertTrue(element.isHittable)
|
||||
}
|
||||
|
||||
private func enter(_ code: String) {
|
||||
for digit in code {
|
||||
let button = app.buttons["passcode.digit.\(digit)"]
|
||||
XCTAssertTrue(button.waitForExistence(timeout: 5))
|
||||
XCTAssertTrue(button.isEnabled)
|
||||
button.tap()
|
||||
}
|
||||
}
|
||||
|
||||
private func clearPartialCode() {
|
||||
let delete = app.buttons["passcode.delete"]
|
||||
for _ in 0..<6 where delete.exists && delete.isEnabled {
|
||||
delete.tap()
|
||||
}
|
||||
}
|
||||
|
||||
private func assertTitle(_ expected: String) {
|
||||
XCTAssertTrue(title.waitForExistence(timeout: TestConstants.controlExistenceTimeout))
|
||||
XCTAssertEqual(title.label, expected)
|
||||
}
|
||||
|
||||
/// Wait for the Home screen and an actual background state before reactivating the app.
|
||||
private func backgroundAndActivate() {
|
||||
XCUIDevice.shared.press(.home)
|
||||
let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
|
||||
XCTAssertTrue(springboard.wait(for: .runningForeground, timeout: 5))
|
||||
let background = NSPredicate { [app] _, _ in
|
||||
MainActor.assumeIsolated {
|
||||
app?.state == .runningBackground || app?.state == .runningBackgroundSuspended
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: background, object: nil)], timeout: 5), .completed)
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 5))
|
||||
}
|
||||
|
||||
private func assertLockedOut() {
|
||||
XCTAssertTrue(lockout.waitForExistence(timeout: 5))
|
||||
XCTAssertFalse(app.buttons["passcode.digit.1"].isEnabled)
|
||||
}
|
||||
|
||||
private func remainingSeconds() -> Int {
|
||||
guard let first = lockout.label.split(separator: " ").first, let seconds = Int(first) else {
|
||||
XCTFail("Missing lockout countdown: \(lockout.label)")
|
||||
return 0
|
||||
}
|
||||
return seconds
|
||||
}
|
||||
|
||||
private func waitForCountdown(toDropBelow seconds: Int) {
|
||||
let countdown = NSPredicate { [weak self] _, _ in
|
||||
MainActor.assumeIsolated {
|
||||
guard let self else { return false }
|
||||
return self.remainingSeconds() < seconds
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: countdown, object: nil)], timeout: 10), .completed)
|
||||
}
|
||||
|
||||
private func assertOriginalDeadline(_ deadline: Date) {
|
||||
let expected = Int(deadline.timeIntervalSinceNow.rounded(.up))
|
||||
XCTAssertGreaterThan(remainingSeconds(), 0)
|
||||
XCTAssertLessThanOrEqual(remainingSeconds(), expected + 2, "Background, reopening or relaunch must not restart the lockout.")
|
||||
XCTAssertGreaterThanOrEqual(remainingSeconds(), max(0, expected - 2), "The persisted deadline must not be shortened.")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import NextcloudKit
|
||||
import RealmSwift
|
||||
import Testing
|
||||
@testable import Nextcloud
|
||||
|
||||
@Suite("Album persistence")
|
||||
struct NCAlbumsPersistenceTests {
|
||||
private func configuration(fileURL: URL? = nil) -> Realm.Configuration {
|
||||
Realm.Configuration(
|
||||
fileURL: fileURL,
|
||||
inMemoryIdentifier: fileURL == nil ? UUID().uuidString : nil,
|
||||
objectTypes: [TableAlbum.self, tableMetadata.self, tableMetadataTag.self, NCKeyValue.self]
|
||||
)
|
||||
}
|
||||
|
||||
private func makePhoto() -> tableMetadata {
|
||||
let metadata = tableMetadata()
|
||||
metadata.account = "account"
|
||||
metadata.fileId = "42"
|
||||
metadata.ocId = "00000042instance"
|
||||
metadata.fileName = "original.heic"
|
||||
metadata.serverUrl = "https://example.com/remote.php/dav/files/user/Photos"
|
||||
metadata.serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
|
||||
return metadata
|
||||
}
|
||||
|
||||
@Test("References resolve current metadata and ignore another account's files")
|
||||
func metadataReference() throws {
|
||||
let realm = try Realm(configuration: configuration())
|
||||
let original = makePhoto()
|
||||
let album = TableAlbum(album: NKPhotoAlbum(account: original.account, href: "/albums/Holiday/"))
|
||||
album.photos.append(original.ocId)
|
||||
#expect(album.metadatas(in: realm).isEmpty)
|
||||
try realm.write { realm.add(original) }
|
||||
let resolved = try #require(album.metadatas(in: realm).first)
|
||||
#expect(resolved.realm == nil)
|
||||
#expect(resolved.serverUrlFileName == original.serverUrlFileName)
|
||||
try realm.write { original.fileNameView = "renamed.heic" }
|
||||
#expect(album.metadatas(in: realm).first?.fileNameView == "renamed.heic")
|
||||
let other = TableAlbum(album: NKPhotoAlbum(account: "other", href: album.href))
|
||||
other.photos.append(original.ocId)
|
||||
#expect(other.metadatas(in: realm).isEmpty)
|
||||
}
|
||||
|
||||
@Test("Account cleanup deletes only its albums, leaving files and other accounts intact")
|
||||
func accountIsolation() throws {
|
||||
let realm = try Realm(configuration: configuration())
|
||||
let original = makePhoto()
|
||||
let first = TableAlbum(album: NKPhotoAlbum(account: original.account, href: "/albums/Holiday/"))
|
||||
let second = TableAlbum(album: NKPhotoAlbum(account: "other", href: first.href))
|
||||
first.photos.append(original.ocId)
|
||||
try realm.write {
|
||||
realm.add(original)
|
||||
realm.add([first, second])
|
||||
}
|
||||
#expect(first.primaryKey != second.primaryKey)
|
||||
try realm.write {
|
||||
realm.delete(realm.objects(TableAlbum.self).filter("account == %@", original.account))
|
||||
}
|
||||
#expect(first.isInvalidated)
|
||||
#expect(!second.isInvalidated)
|
||||
#expect(!original.isInvalidated)
|
||||
#expect(realm.objects(TableAlbum.self).count == 1)
|
||||
}
|
||||
|
||||
@Test("A renamed album gets a new primary key while keeping its photo references")
|
||||
func renamePreservesReferences() throws {
|
||||
let realm = try Realm(configuration: configuration())
|
||||
let original = NKPhotoAlbum(account: "account", href: "/albums/Old/")
|
||||
let renamed = NKPhotoAlbum(account: original.account, href: "/albums/New%20name/", itemCount: 1)
|
||||
let entry = TableAlbum(album: original)
|
||||
entry.photos.append("00000042instance")
|
||||
entry.photosLoaded = true
|
||||
try realm.write { realm.add(entry) }
|
||||
try realm.write {
|
||||
let replacement = TableAlbum(album: renamed, copyingPhotosFrom: entry)
|
||||
realm.delete(entry)
|
||||
realm.add(replacement, update: .modified)
|
||||
}
|
||||
#expect(realm.object(ofType: TableAlbum.self, forPrimaryKey: original.id) == nil)
|
||||
let saved = try #require(realm.object(ofType: TableAlbum.self, forPrimaryKey: renamed.id))
|
||||
#expect(saved.album == renamed)
|
||||
#expect(saved.photosLoaded)
|
||||
#expect(Array(saved.photos) == ["00000042instance"])
|
||||
try realm.write { saved.update(from: NKPhotoAlbum(account: renamed.account, href: renamed.href, itemCount: 2)) }
|
||||
#expect(saved.itemCount == 2)
|
||||
#expect(saved.photos.count == 1)
|
||||
}
|
||||
|
||||
@Test("Albums and photo references survive reopening the database")
|
||||
func reopenReferences() throws {
|
||||
let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: folder) }
|
||||
let configuration = configuration(fileURL: folder.appendingPathComponent("albums.realm"))
|
||||
let album = NKPhotoAlbum(account: "account", href: "/albums/Holiday%20photos/", lastPhotoId: "42", itemCount: 1)
|
||||
try autoreleasepool {
|
||||
let realm = try Realm(configuration: configuration)
|
||||
let original = makePhoto()
|
||||
let entry = TableAlbum(album: album)
|
||||
entry.photos.append(original.ocId)
|
||||
entry.photosLoaded = true
|
||||
try realm.write {
|
||||
realm.add(original)
|
||||
realm.add(entry)
|
||||
}
|
||||
}
|
||||
try autoreleasepool {
|
||||
let realm = try Realm(configuration: configuration)
|
||||
let entry = try #require(realm.object(ofType: TableAlbum.self, forPrimaryKey: album.id))
|
||||
#expect(entry.album == album)
|
||||
#expect(entry.photosLoaded)
|
||||
#expect(entry.photos.first == "00000042instance")
|
||||
#expect(entry.metadatas(in: realm).first?.fileName == "original.heic")
|
||||
try realm.write { entry.photos.removeAll() }
|
||||
#expect(entry.photosLoaded)
|
||||
#expect(entry.photos.isEmpty)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import GRDB
|
||||
import NextcloudKit
|
||||
import Testing
|
||||
@testable import Nextcloud
|
||||
|
||||
@Suite("Background Upload resource state")
|
||||
@MainActor
|
||||
struct NCAutoUploadAssetTests {
|
||||
private let account = "account"
|
||||
private let destination = "https://example.com/Photos"
|
||||
private let assetIdentifier = "56382E82-3757-4EE9-9216-9342EFE976E0/L0/001"
|
||||
private let imageClass = NKTypeClassFile.image.rawValue
|
||||
private let videoClass = NKTypeClassFile.video.rawValue
|
||||
|
||||
private func makeDatabase() throws -> NCLocalDatabase {
|
||||
let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString).appendingPathExtension("sqlite")
|
||||
return try NCLocalDatabase(databaseURL: url)
|
||||
}
|
||||
|
||||
private func resource(video: Bool = false, session: String = "session", uploaded: Bool = false) -> NCAutoUploadResource {
|
||||
NCAutoUploadResource(account: account, serverUrlBase: destination, assetLocalIdentifier: assetIdentifier, uploadSessionIdentifier: session,
|
||||
classFile: video ? videoClass : imageClass, fileName: video ? "0355.mov" : "0355.heic",
|
||||
uploaded: uploaded, creationDate: Date(timeIntervalSince1970: 100))
|
||||
}
|
||||
|
||||
private func history(_ database: NCLocalDatabase, session: String? = nil) async throws -> [NCAutoUploadResource] {
|
||||
try await database.autoUploadResources(account: account, serverUrlBase: destination, assetLocalIdentifier: assetIdentifier, sessionIdentifier: session)
|
||||
}
|
||||
|
||||
private func metadata(video: Bool = false, identifier: String = "photo-transfer") -> tableMetadata {
|
||||
let metadata = tableMetadata()
|
||||
metadata.account = account
|
||||
metadata.assetLocalIdentifier = assetIdentifier
|
||||
metadata.autoUploadServerUrlBase = destination
|
||||
metadata.sessionSelector = NCGlobal.shared.selectorUploadAutoUpload
|
||||
metadata.ocId = identifier
|
||||
metadata.ocIdTransfer = identifier
|
||||
metadata.classFile = video ? videoClass : imageClass
|
||||
metadata.fileNameView = video ? "0355.mov" : "0355.heic"
|
||||
metadata.fileName = metadata.fileNameView
|
||||
metadata.livePhotoFile = video ? "0355.heic" : "0355.mov"
|
||||
metadata.creationDate = Date(timeIntervalSince1970: 100) as NSDate
|
||||
return metadata
|
||||
}
|
||||
|
||||
@Test("A Live Photo has two independently completed rows", arguments: [false, true])
|
||||
func partialUpload(videoFirst: Bool) async throws {
|
||||
let database = try makeDatabase()
|
||||
_ = try await database.recordAutoUploadResources([resource(), resource(video: true)])
|
||||
let first = metadata(video: videoFirst, identifier: "first")
|
||||
let second = metadata(video: !videoFirst, identifier: "second")
|
||||
try await database.recordAutoUploadTransfer(first, sessionIdentifier: "session", uploaded: true)
|
||||
var rows = try await history(database)
|
||||
#expect(rows.count == 2)
|
||||
#expect(rows.filter(\.uploaded).map(\.classFile) == [first.classFile])
|
||||
#expect(rows.first(where: { $0.classFile == second.classFile })?.uploaded == false)
|
||||
try await database.recordAutoUploadTransfer(second, sessionIdentifier: "session", uploaded: true)
|
||||
rows = try await history(database)
|
||||
#expect(Set(rows.filter(\.uploaded).map(\.classFile)) == [imageClass, videoClass])
|
||||
}
|
||||
|
||||
@Test("A standalone photo has one row; a missing video row is not a completed Live Photo")
|
||||
func expectedComponents() async throws {
|
||||
let database = try makeDatabase()
|
||||
let photo = metadata()
|
||||
try await database.recordAutoUploadTransfer(photo, sessionIdentifier: "session", uploaded: true)
|
||||
let rows = try await history(database)
|
||||
#expect(rows.count == 1)
|
||||
#expect(rows.first?.classFile == imageClass)
|
||||
#expect(rows.first?.fileName == photo.fileNameView)
|
||||
#expect(rows.first?.uploaded == true)
|
||||
#expect(rows.contains { $0.classFile == videoClass && $0.uploaded } == false)
|
||||
try await database.recordAutoUploadTransfer(metadata(video: true), sessionIdentifier: "session")
|
||||
let resumed = try await history(database)
|
||||
#expect(resumed.count == 2)
|
||||
#expect(resumed.first { $0.classFile == imageClass }?.uploaded == true)
|
||||
#expect(resumed.first { $0.classFile == videoClass }?.uploaded == false)
|
||||
}
|
||||
|
||||
@Test("Repeated discovery retains names and completed progress for each component")
|
||||
func repeatedDiscovery() async throws {
|
||||
let database = try makeDatabase()
|
||||
_ = try await database.recordAutoUploadResources([resource(uploaded: true), resource(video: true)])
|
||||
var photo = resource()
|
||||
var video = resource(video: true)
|
||||
photo.fileName = "0356.heic"
|
||||
video.fileName = "0356.mov"
|
||||
let rows = try await database.recordAutoUploadResources([photo, video])
|
||||
#expect(rows.first(where: { $0.classFile == imageClass })?.fileName == "0355.heic")
|
||||
#expect(rows.first(where: { $0.classFile == imageClass })?.uploaded == true)
|
||||
#expect(rows.first(where: { $0.classFile == videoClass })?.fileName == "0355.mov")
|
||||
#expect(rows.first(where: { $0.classFile == videoClass })?.uploaded == false)
|
||||
#expect(try await history(database).count == 2)
|
||||
}
|
||||
|
||||
@Test("Force Reupload isolates the current session; normal discovery sees previous successes")
|
||||
func sessionIsolation() async throws {
|
||||
let database = try makeDatabase()
|
||||
_ = try await database.recordAutoUploadResources([
|
||||
resource(session: "old", uploaded: true), resource(video: true, session: "old", uploaded: true),
|
||||
resource(session: "current"), resource(video: true, session: "current")
|
||||
])
|
||||
let normal = try await history(database)
|
||||
#expect(normal.count == 4)
|
||||
#expect(Set(normal.filter(\.uploaded).map(\.classFile)) == [imageClass, videoClass])
|
||||
let forced = try await history(database, session: "current")
|
||||
#expect(forced.count == 2)
|
||||
#expect(forced.allSatisfy { !$0.uploaded })
|
||||
}
|
||||
|
||||
@Test("History and removal are scoped to account, destination and asset")
|
||||
func destinationIsolation() async throws {
|
||||
let database = try makeDatabase()
|
||||
_ = try await database.recordAutoUploadResources([resource(), resource(video: true)])
|
||||
for scope in [("other", destination, assetIdentifier), (account, "other", assetIdentifier), (account, destination, "other")] {
|
||||
#expect(try await database.autoUploadResources(account: scope.0, serverUrlBase: scope.1, assetLocalIdentifier: scope.2).isEmpty)
|
||||
}
|
||||
try await database.removeAutoUploadResources(account: "other", serverUrlBase: destination)
|
||||
#expect(try await history(database).count == 2)
|
||||
try await database.removeAutoUploadResources(account: account, serverUrlBase: destination)
|
||||
#expect(try await history(database).isEmpty)
|
||||
}
|
||||
|
||||
@Test("Account removal clears every destination without clearing another account")
|
||||
func accountRemoval() async throws {
|
||||
let database = try makeDatabase()
|
||||
let otherDestination = NCAutoUploadResource(account: account, serverUrlBase: "other", assetLocalIdentifier: assetIdentifier,
|
||||
uploadSessionIdentifier: "session", classFile: imageClass, fileName: "0355.heic",
|
||||
uploaded: false, creationDate: Date(timeIntervalSince1970: 100))
|
||||
let otherAccount = NCAutoUploadResource(account: "other", serverUrlBase: destination, assetLocalIdentifier: assetIdentifier,
|
||||
uploadSessionIdentifier: "session", classFile: imageClass, fileName: "0355.heic",
|
||||
uploaded: false, creationDate: otherDestination.creationDate)
|
||||
_ = try await database.recordAutoUploadResources([resource(), otherDestination, otherAccount])
|
||||
try await database.recordPhotoLibraryAssetUpload(account: account, assetLocalIdentifier: assetIdentifier,
|
||||
classFile: imageClass, isLivePhoto: false, creationDate: otherDestination.creationDate)
|
||||
try await database.recordPhotoLibraryAssetUpload(account: "other", assetLocalIdentifier: assetIdentifier,
|
||||
classFile: imageClass, isLivePhoto: false, creationDate: otherDestination.creationDate)
|
||||
try await database.clearDatabase(account: account)
|
||||
#expect(try await database.uploadedPhotoLibraryAssets(account: account).isEmpty)
|
||||
#expect(try await database.uploadedPhotoLibraryAssets(account: "other").count == 1)
|
||||
#expect(try await history(database).isEmpty)
|
||||
#expect(try await database.autoUploadResources(account: account, serverUrlBase: "other", assetLocalIdentifier: assetIdentifier).isEmpty)
|
||||
#expect(try await database.autoUploadResources(account: "other", serverUrlBase: destination, assetLocalIdentifier: assetIdentifier).count == 1)
|
||||
}
|
||||
|
||||
@Test("The transfer identifier confirms completion after server ID replacement and file renaming")
|
||||
func transferConfirmation() async throws {
|
||||
let database = try makeDatabase()
|
||||
let photo = metadata()
|
||||
#expect(try await database.recordAutoUploadTransfer(photo, sessionIdentifier: "session"))
|
||||
photo.ocId = "server-file-id"
|
||||
photo.fileName = "renamed.heic"
|
||||
photo.fileNameView = "renamed.heic"
|
||||
#expect(try await database.recordAutoUploadTransfer(photo, uploaded: true))
|
||||
#expect(try await database.autoUploadTransferIsUploaded(photo))
|
||||
let rows = try await history(database)
|
||||
#expect(rows.count == 1)
|
||||
#expect(rows.first?.transferIdentifier == "photo-transfer")
|
||||
#expect(rows.first?.fileName == "renamed.heic")
|
||||
#expect(rows.first?.uploaded == true)
|
||||
}
|
||||
|
||||
@Test("A late confirmation cannot complete a new forced session with identical file names")
|
||||
func lateConfirmation() async throws {
|
||||
let database = try makeDatabase()
|
||||
let old = metadata(identifier: "old-transfer")
|
||||
let current = metadata(identifier: "new-transfer")
|
||||
try await database.recordAutoUploadTransfer(old, sessionIdentifier: "old")
|
||||
try await database.recordAutoUploadTransfer(current, sessionIdentifier: "current")
|
||||
try await database.recordAutoUploadTransfer(old, sessionIdentifier: "current", uploaded: true)
|
||||
#expect(try await database.autoUploadTransferIsUploaded(old))
|
||||
#expect(try await database.autoUploadTransferIsUploaded(current) == false)
|
||||
#expect(try await history(database, session: "current").first?.uploaded == false)
|
||||
}
|
||||
|
||||
@Test("Ordinary host uploads cannot create or complete extension history")
|
||||
func unregisteredHostUpload() async throws {
|
||||
let database = try makeDatabase()
|
||||
let ordinary = metadata(identifier: "ordinary-transfer")
|
||||
#expect(try await database.recordAutoUploadTransfer(ordinary, uploaded: true) == false)
|
||||
#expect(try await database.autoUploadResource(for: ordinary) == nil)
|
||||
let seed = metadata()
|
||||
try await database.recordAutoUploadTransfer(seed, sessionIdentifier: "session")
|
||||
#expect(try await database.recordAutoUploadTransfer(ordinary, uploaded: true) == false)
|
||||
#expect(try await database.autoUploadTransferIsUploaded(seed) == false)
|
||||
}
|
||||
|
||||
@Test("PhotoKit and chunk components retain independent transfers in the same session")
|
||||
func independentChunkComponents() async throws {
|
||||
let database = try makeDatabase()
|
||||
_ = try await database.recordAutoUploadResources([resource(), resource(video: true)])
|
||||
let photo = metadata(identifier: "photokit-photo")
|
||||
photo.size = 5_000_000
|
||||
photo.backgroundUploadJobIdentifier = "pending"
|
||||
let video = metadata(video: true, identifier: "chunk-video")
|
||||
video.size = 120_000_000
|
||||
video.chunk = 100_000_000
|
||||
try await database.recordAutoUploadTransfer(photo, sessionIdentifier: "session")
|
||||
try await database.recordAutoUploadTransfer(video, sessionIdentifier: "session")
|
||||
let photoResource = try await database.autoUploadResource(for: photo)
|
||||
let videoResource = try await database.autoUploadResource(for: video)
|
||||
#expect(photoResource?.transferIdentifier == "photokit-photo")
|
||||
#expect(videoResource?.transferIdentifier == "chunk-video")
|
||||
#expect(photoResource?.uploadSessionIdentifier == videoResource?.uploadSessionIdentifier)
|
||||
try await database.recordAutoUploadTransfer(photo, uploaded: true)
|
||||
#expect(try await database.autoUploadTransferIsUploaded(photo))
|
||||
#expect(try await database.autoUploadTransferIsUploaded(video) == false)
|
||||
try await database.recordAutoUploadTransfer(video, uploaded: true)
|
||||
#expect(try await history(database).allSatisfy(\.uploaded))
|
||||
#expect(try await history(database).count == 2)
|
||||
}
|
||||
|
||||
@Test("Completed components survive hundreds of incremental naming proposals")
|
||||
func completedPairRediscovery() async throws {
|
||||
let database = try makeDatabase()
|
||||
_ = try await database.recordAutoUploadResources([resource(uploaded: true), resource(video: true, uploaded: true)])
|
||||
for number in 355...617 {
|
||||
var photo = resource()
|
||||
var video = resource(video: true)
|
||||
photo.fileName = "\(number).heic"
|
||||
video.fileName = "\(number).mov"
|
||||
let rows = try await database.recordAutoUploadResources([photo, video])
|
||||
let allUploaded = rows.allSatisfy { $0.uploaded }
|
||||
#expect(allUploaded)
|
||||
#expect(rows.map(\.fileName) == ["0355.heic", "0355.mov"])
|
||||
}
|
||||
#expect(try await history(database).count == 2)
|
||||
}
|
||||
|
||||
@Test("Unavailable history throws instead of appearing empty or accepting a confirmation")
|
||||
func unavailableDatabase() async throws {
|
||||
let database = try makeDatabase()
|
||||
let transfer = metadata()
|
||||
try await database.recordAutoUploadTransfer(transfer, sessionIdentifier: "session")
|
||||
try database.databasePool().close()
|
||||
await #expect(throws: (any Error).self) {
|
||||
try await history(database)
|
||||
}
|
||||
await #expect(throws: (any Error).self) {
|
||||
try await database.recordAutoUploadTransfer(transfer, uploaded: true)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("A success for another file name cannot mark the reserved component complete")
|
||||
func mismatchedReservation() async throws {
|
||||
let database = try makeDatabase()
|
||||
_ = try await database.recordAutoUploadResources([resource()])
|
||||
var completed = resource(uploaded: true)
|
||||
completed.fileName = "other.heic"
|
||||
let stored = try await database.recordAutoUploadResources([completed])
|
||||
#expect(stored.first?.fileName == "0355.heic")
|
||||
#expect(stored.first?.uploaded == false)
|
||||
}
|
||||
|
||||
@Test("The success cache does not suppress a new attempt to the same server path")
|
||||
func cachedSuccessIdentity() async {
|
||||
let cache = NCMetadataUploadTranfersSuccess()
|
||||
let completed = metadata(identifier: "old-attempt")
|
||||
completed.account = "test-cache-" + UUID().uuidString
|
||||
completed.livePhotoFile = ""
|
||||
let path = destination + "/0355.heic"
|
||||
completed.serverUrlFileName = path
|
||||
await cache.append(metadata: completed, ocId: "server-file", date: nil, etag: nil)
|
||||
#expect(completed.ocId == "old-attempt")
|
||||
let cachedMetadatas = await cache.getAll()
|
||||
cachedMetadatas.first?.ocIdTransfer = "changed-outside-cache"
|
||||
#expect(await cache.exists(serverUrlFileName: path))
|
||||
#expect(await cache.exists(serverUrlFileName: path, transferIdentifier: "old-attempt"))
|
||||
#expect(await cache.exists(serverUrlFileName: path, transferIdentifier: "new-attempt") == false)
|
||||
|
||||
let reuploaded = metadata(identifier: "new-attempt")
|
||||
reuploaded.account = completed.account
|
||||
reuploaded.livePhotoFile = ""
|
||||
reuploaded.serverUrlFileName = path
|
||||
await cache.append(metadata: reuploaded, ocId: "server-file", date: nil, etag: nil)
|
||||
#expect(await cache.count() == 2)
|
||||
#expect(await cache.exists(serverUrlFileName: path, transferIdentifier: "old-attempt"))
|
||||
#expect(await cache.exists(serverUrlFileName: path, transferIdentifier: "new-attempt"))
|
||||
await cache.append(metadata: reuploaded, ocId: "server-file", date: nil, etag: nil)
|
||||
#expect(await cache.count() == 2)
|
||||
}
|
||||
|
||||
@Test("The new component table preserves existing photo-library state")
|
||||
func existingSchema() async throws {
|
||||
let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString).appendingPathExtension("sqlite")
|
||||
let oldDatabase = try DatabaseQueue(path: url.path)
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("initialSchema") { database in
|
||||
try database.create(table: "photoLibraryAsset") { table in
|
||||
table.column("account", .text).notNull()
|
||||
table.column("assetLocalIdentifier", .text).notNull()
|
||||
table.column("photoUploaded", .boolean)
|
||||
table.column("videoUploaded", .boolean)
|
||||
table.column("creationDate", .datetime).notNull()
|
||||
table.primaryKey(["account", "assetLocalIdentifier"])
|
||||
}
|
||||
}
|
||||
try migrator.migrate(oldDatabase)
|
||||
let photo = NCPhotoLibraryAsset(account: account, assetLocalIdentifier: "photo", photoUploaded: true,
|
||||
videoUploaded: nil, creationDate: Date(timeIntervalSince1970: 100))
|
||||
try await oldDatabase.write { try photo.insert($0) }
|
||||
let database = try NCLocalDatabase(databaseURL: url)
|
||||
#expect(try await database.uploadedPhotoLibraryAssets(account: account) == [photo])
|
||||
_ = try await database.recordAutoUploadResources([resource(), resource(video: true)])
|
||||
try await database.clearDBCache()
|
||||
#expect(try await history(database).isEmpty)
|
||||
#expect(try await database.uploadedPhotoLibraryAssets(account: account).isEmpty)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import Nextcloud
|
||||
|
||||
@Suite("Auto Upload incremental date backup compatibility")
|
||||
@MainActor
|
||||
struct NCAutoUploadDateTests {
|
||||
@Test("Whole-library discovery stays unfiltered as upload progress advances")
|
||||
func wholeLibraryDiscoveryIgnoresProgress() {
|
||||
let account = tableAccount()
|
||||
account.autoUploadAllPhotos = true
|
||||
for date in [nil, Date(timeIntervalSince1970: 100), Date(timeIntervalSince1970: 200)] {
|
||||
account.autoUploadSinceDate = date
|
||||
#expect(account.autoUploadDatePredicate == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Date-limited discovery includes the boundary and newer assets, and switching to all removes the filter")
|
||||
func dateLimitedDiscovery() throws {
|
||||
let account = tableAccount()
|
||||
account.autoUploadSinceDate = Date(timeIntervalSince1970: 100)
|
||||
let predicate = try #require(account.autoUploadDatePredicate)
|
||||
#expect(!predicate.evaluate(with: ["creationDate": Date(timeIntervalSince1970: 99)]))
|
||||
#expect(predicate.evaluate(with: ["creationDate": Date(timeIntervalSince1970: 100)]))
|
||||
#expect(predicate.evaluate(with: ["creationDate": Date(timeIntervalSince1970: 101)]))
|
||||
|
||||
account.autoUploadAllPhotos = true
|
||||
#expect(account.autoUploadDatePredicate == nil)
|
||||
account.autoUploadAllPhotos = false
|
||||
#expect(account.autoUploadDatePredicate != nil)
|
||||
}
|
||||
|
||||
@Test("Account backup preserves the incremental restart date")
|
||||
func backupRoundTrip() throws {
|
||||
let account = tableAccount()
|
||||
account.autoUploadSinceDate = Date(timeIntervalSince1970: 100)
|
||||
let data = try JSONEncoder().encode(account.tableAccountToCodable())
|
||||
let decoded = try JSONDecoder().decode(tableAccountCodable.self, from: data)
|
||||
#expect(tableAccount(codableObject: decoded).autoUploadSinceDate == account.autoUploadSinceDate)
|
||||
}
|
||||
|
||||
@Test("A whole-library selection remains unfiltered after account restore")
|
||||
func wholeLibraryRoundTrip() throws {
|
||||
let account = tableAccount()
|
||||
account.autoUploadAllPhotos = true
|
||||
let data = try JSONEncoder().encode(account.tableAccountToCodable())
|
||||
let decoded = try JSONDecoder().decode(tableAccountCodable.self, from: data)
|
||||
#expect(tableAccount(codableObject: decoded).autoUploadSinceDate == nil)
|
||||
}
|
||||
|
||||
@Test("Backups with the removed discovery field preserve the restart date")
|
||||
func removedDiscoveryFieldCompatibility() throws {
|
||||
let account = tableAccount()
|
||||
account.autoUploadSinceDate = Date(timeIntervalSince1970: 100)
|
||||
let data = try JSONEncoder().encode(account.tableAccountToCodable())
|
||||
var json = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])
|
||||
// An obsolete discovery cursor must not override a user-selected restart date.
|
||||
json["autoUploadDiscoveryDate"] = Date(timeIntervalSince1970: 200).timeIntervalSinceReferenceDate
|
||||
let oldData = try JSONSerialization.data(withJSONObject: json)
|
||||
let decoded = try JSONDecoder().decode(tableAccountCodable.self, from: oldData)
|
||||
#expect(tableAccount(codableObject: decoded).autoUploadSinceDate == account.autoUploadSinceDate)
|
||||
}
|
||||
|
||||
@Test("Whole-library selection survives backup with a nonempty progress date")
|
||||
func wholeLibrarySelectionWithProgress() throws {
|
||||
let account = tableAccount()
|
||||
account.autoUploadAllPhotos = true
|
||||
account.autoUploadSinceDate = Date(timeIntervalSince1970: 100)
|
||||
let data = try JSONEncoder().encode(account.tableAccountToCodable())
|
||||
let decoded = try JSONDecoder().decode(tableAccountCodable.self, from: data)
|
||||
let restored = tableAccount(codableObject: decoded)
|
||||
#expect(restored.autoUploadAllPhotos)
|
||||
#expect(restored.autoUploadSinceDate == account.autoUploadSinceDate)
|
||||
#expect(restored.autoUploadDatePredicate == nil)
|
||||
}
|
||||
|
||||
@Test("Older backups infer the library selection from their existing date")
|
||||
func previousBackupSelectionCompatibility() throws {
|
||||
let dates: [Date?] = [nil, Date(timeIntervalSince1970: 100)]
|
||||
for date in dates {
|
||||
let account = tableAccount()
|
||||
account.autoUploadSinceDate = date
|
||||
let data = try JSONEncoder().encode(account.tableAccountToCodable())
|
||||
var json = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])
|
||||
json.removeValue(forKey: "autoUploadAllPhotos")
|
||||
let oldData = try JSONSerialization.data(withJSONObject: json)
|
||||
let decoded = try JSONDecoder().decode(tableAccountCodable.self, from: oldData)
|
||||
#expect(tableAccount(codableObject: decoded).autoUploadAllPhotos == (date == nil))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import AVFoundation
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import Nextcloud
|
||||
|
||||
@Suite("NCCameraRoll image format conversion")
|
||||
struct NCCameraRollTests {
|
||||
|
||||
@Test("Animated and lossless formats retain their filenames")
|
||||
func formatsPreserved() {
|
||||
for fileName in ["animation.gif", "image.png", "animation.webp", "image.tiff", "image.jpg"] {
|
||||
let fileExtension = (fileName as NSString).pathExtension
|
||||
|
||||
#expect(!NCCameraRoll.shouldConvertToJPEG(fileExtension: fileExtension, nativeFormat: false))
|
||||
#expect(
|
||||
NCCameraRoll.outputFileName(
|
||||
for: fileName,
|
||||
sourceFileExtension: fileExtension,
|
||||
nativeFormat: false
|
||||
) == fileName
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Compatibility formats are converted to JPEG")
|
||||
func compatibilityFormatsConverted() {
|
||||
for fileName in ["image.heic", "image.heif", "image.dng"] {
|
||||
let fileExtension = (fileName as NSString).pathExtension
|
||||
|
||||
#expect(NCCameraRoll.shouldConvertToJPEG(fileExtension: fileExtension, nativeFormat: false))
|
||||
#expect(
|
||||
NCCameraRoll.outputFileName(
|
||||
for: fileName,
|
||||
sourceFileExtension: fileExtension,
|
||||
nativeFormat: false
|
||||
) == "image.jpg"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Native format preserves HEIC, HEIF and RAW filenames")
|
||||
func nativeFormatsPreserved() {
|
||||
for fileName in ["image.heic", "image.heif", "image.dng"] {
|
||||
let fileExtension = (fileName as NSString).pathExtension
|
||||
|
||||
#expect(!NCCameraRoll.shouldConvertToJPEG(fileExtension: fileExtension, nativeFormat: true))
|
||||
#expect(
|
||||
NCCameraRoll.outputFileName(
|
||||
for: fileName,
|
||||
sourceFileExtension: fileExtension,
|
||||
nativeFormat: true
|
||||
) == fileName
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Generated upload names keep their base name")
|
||||
func generatedNameConverted() {
|
||||
#expect(
|
||||
NCCameraRoll.outputFileName(
|
||||
for: "2026-08-04 09-30-00.heic",
|
||||
sourceFileExtension: "heic",
|
||||
nativeFormat: false
|
||||
) == "2026-08-04 09-30-00.jpg"
|
||||
)
|
||||
}
|
||||
|
||||
@Test("Video passthrough retains its original container")
|
||||
func videoContainerPreserved() {
|
||||
#expect(NCCameraRoll.videoOutputFileType(fileExtension: "mov") == .mov)
|
||||
#expect(NCCameraRoll.videoOutputFileType(fileExtension: "MP4") == .mp4)
|
||||
#expect(NCCameraRoll.videoOutputFileType(fileExtension: "m4v") == .m4v)
|
||||
#expect(NCCameraRoll.videoOutputFileType(fileExtension: "jpg") == nil)
|
||||
}
|
||||
|
||||
@Test("Concurrent extractions use distinct temporary paths")
|
||||
func extractionTemporaryPathsAreUnique() {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
let firstURL = NCCameraRoll.extractionTemporaryURL(
|
||||
fileName: "26-08-04 10-51-42 7473.jpg",
|
||||
ocId: "camera-roll-transfer",
|
||||
directory: directory
|
||||
)
|
||||
let secondURL = NCCameraRoll.extractionTemporaryURL(
|
||||
fileName: "26-08-04 10-51-42 7473.jpg",
|
||||
ocId: "camera-roll-transfer",
|
||||
directory: directory
|
||||
)
|
||||
|
||||
#expect(firstURL != secondURL)
|
||||
#expect(firstURL.deletingLastPathComponent() == directory)
|
||||
#expect(firstURL.pathExtension == "uploading")
|
||||
#expect(firstURL.lastPathComponent.contains("camera-roll-transfer"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import NextcloudKit
|
||||
import Testing
|
||||
@testable import Nextcloud
|
||||
|
||||
@Suite("Document editor MIME type recognition")
|
||||
struct NCDocumentEditorSupportTests {
|
||||
private let word = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||
private let spreadsheet = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
|
||||
@Test("Server MIME types work even without a filename extension")
|
||||
func extensionlessDocument() {
|
||||
#expect(NCDocumentEditorSupport.supportsMimetype([word], contentType: word, fileName: "Document"))
|
||||
}
|
||||
|
||||
@Test("MIME type comparison ignores case, whitespace and parameters")
|
||||
func normalizedServerType() {
|
||||
#expect(NCDocumentEditorSupport.supportsMimetype(
|
||||
["application/pdf"], contentType: " APPLICATION/PDF; charset=binary ", fileName: "document.pdf"
|
||||
))
|
||||
}
|
||||
|
||||
@Test("Apple PDF type identifiers match the server MIME type")
|
||||
func appleTypeIdentifier() {
|
||||
#expect(NCDocumentEditorSupport.supportsMimetype(
|
||||
["application/pdf"], contentType: "com.adobe.pdf", fileName: "Document"
|
||||
))
|
||||
}
|
||||
|
||||
@Test("Office extensions identify files with missing or generic MIME types",
|
||||
arguments: ["", "application/octet-stream", "application/zip"])
|
||||
func genericOfficeType(contentType: String) {
|
||||
#expect(NCDocumentEditorSupport.supportsMimetype([word], contentType: contentType, fileName: "Document.DOCX"))
|
||||
#expect(NCDocumentEditorSupport.supportsMimetype([spreadsheet], contentType: contentType, fileName: "Sheet.xlsx"))
|
||||
}
|
||||
|
||||
@Test("An explicitly supported generic MIME type is retained",
|
||||
arguments: ["application/octet-stream", "application/zip"])
|
||||
func supportedGenericType(contentType: String) {
|
||||
#expect(NCDocumentEditorSupport.supportsMimetype(
|
||||
[contentType], contentType: contentType, fileName: "document.docx"
|
||||
))
|
||||
}
|
||||
|
||||
@Test("A specific server MIME type takes precedence over the filename")
|
||||
func authoritativeServerType() {
|
||||
#expect(!NCDocumentEditorSupport.supportsMimetype([word], contentType: "text/plain", fileName: "document.docx"))
|
||||
}
|
||||
|
||||
@Test("Unsupported and empty MIME types do not match substrings")
|
||||
func unsupportedType() {
|
||||
#expect(!NCDocumentEditorSupport.supportsMimetype([word], contentType: "document", fileName: "file.unknown"))
|
||||
#expect(!NCDocumentEditorSupport.supportsMimetype([word], contentType: "", fileName: "file.unknown"))
|
||||
#expect(!NCDocumentEditorSupport.supportsMimetype([], contentType: word, fileName: "document.docx"))
|
||||
}
|
||||
|
||||
@Test("HTML compatibility does not advertise Office editors without HTML support")
|
||||
func officeHTMLRequiresSupport() throws {
|
||||
for identifier in ["richdocuments", "onlyoffice", "eurooffice"] {
|
||||
let editor = try makeEditor(identifier: identifier, mimetypes: [word])
|
||||
#expect(!NCDocumentEditorSupport.supportsDirectEditingEditor(
|
||||
editor, contentType: "text/html", fileName: "page.html"
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@Test("An Office editor can explicitly advertise optional HTML support")
|
||||
func optionalHTMLSupport() throws {
|
||||
let editor = try makeEditor(identifier: "richdocuments", mimetypes: [word], optionalMimetypes: ["text/html"])
|
||||
#expect(NCDocumentEditorSupport.supportsDirectEditingEditor(
|
||||
editor, contentType: "text/html", fileName: "page.html"
|
||||
))
|
||||
}
|
||||
|
||||
@Test("Nextcloud Text retains HTML and Markdown compatibility")
|
||||
func textCompatibility() throws {
|
||||
let editor = try makeEditor(identifier: "text", mimetypes: ["text/plain", "text/markdown"])
|
||||
#expect(NCDocumentEditorSupport.supportsDirectEditingEditor(
|
||||
editor, contentType: "text/html", fileName: "page.html"
|
||||
))
|
||||
#expect(NCDocumentEditorSupport.supportsDirectEditingEditor(
|
||||
editor, contentType: "text/x-markdown", fileName: "notes.md"
|
||||
))
|
||||
}
|
||||
|
||||
@Test("Editors advertising Markdown retain the existing MIME alias")
|
||||
func advertisedMarkdownAlias() throws {
|
||||
let editor = try makeEditor(identifier: "richdocuments", mimetypes: ["text/markdown"])
|
||||
#expect(NCDocumentEditorSupport.supportsDirectEditingEditor(
|
||||
editor, contentType: "text/x-markdown", fileName: "notes.md"
|
||||
))
|
||||
}
|
||||
|
||||
@Test("Optional Office types and generic MIME inference select the editor")
|
||||
func optionalOfficeSupport() throws {
|
||||
let editor = try makeEditor(identifier: "richdocuments", mimetypes: [], optionalMimetypes: [spreadsheet])
|
||||
#expect(NCDocumentEditorSupport.supportsDirectEditingEditor(
|
||||
editor, contentType: "application/octet-stream", fileName: "sheet.xlsx"
|
||||
))
|
||||
}
|
||||
|
||||
private func makeEditor(identifier: String, mimetypes: [String], optionalMimetypes: [String] = []) throws -> NKDirectEditingEditor {
|
||||
let data = try JSONSerialization.data(withJSONObject: [
|
||||
"id": identifier,
|
||||
"name": identifier,
|
||||
"mimetypes": mimetypes,
|
||||
"optionalMimetypes": optionalMimetypes,
|
||||
"secure": true
|
||||
])
|
||||
return try JSONDecoder().decode(NKDirectEditingEditor.self, from: data)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import Nextcloud
|
||||
|
||||
@Suite("End-to-end key set archive")
|
||||
struct NCEndToEndKeySetArchiveTests {
|
||||
@Test("Archiving does not change the active credentials")
|
||||
func preservesNormalActiveCredentials() throws {
|
||||
let account = "e2ee-archive-\(UUID().uuidString)"
|
||||
let preferences = NCPreferences()
|
||||
defer {
|
||||
preferences.clearAllKeysEndToEnd(account: account)
|
||||
}
|
||||
|
||||
setKeySet(on: preferences, account: account)
|
||||
try preferences.archiveCurrentEndToEndKeySet(account: account)
|
||||
|
||||
#expect(preferences.isEndToEndEnabled(account: account))
|
||||
#expect(preferences.getEndToEndCertificate(account: account) == "certificate")
|
||||
#expect(preferences.getEndToEndPrivateKey(account: account) == "private-key")
|
||||
#expect(preferences.getEndToEndPublicKey(account: account) == "public-key")
|
||||
#expect(preferences.getEndToEndPassphrase(account: account) == "passphrase")
|
||||
}
|
||||
|
||||
@Test("Archiving preserves active credentials after they are cleared")
|
||||
func preservesActiveCredentials() throws {
|
||||
let account = "e2ee-archive-\(UUID().uuidString)"
|
||||
let preferences = NCPreferences()
|
||||
defer {
|
||||
preferences.clearAllKeysEndToEnd(account: account)
|
||||
}
|
||||
|
||||
setKeySet(on: preferences, account: account)
|
||||
let archivedKeySet = try preferences.archiveCurrentEndToEndKeySet(account: account)
|
||||
let snapshot = try #require(archivedKeySet)
|
||||
|
||||
preferences.clearCurrentKeysEndToEnd(account: account)
|
||||
|
||||
#expect(preferences.getEndToEndCertificate(account: account) == nil)
|
||||
#expect(preferences.getEndToEndPrivateKey(account: account) == nil)
|
||||
#expect(preferences.getEndToEndPublicKey(account: account) == nil)
|
||||
#expect(preferences.getEndToEndPassphrase(account: account) == nil)
|
||||
|
||||
let archivedKeySets = try preferences.getArchivedEndToEndKeySets(account: account)
|
||||
#expect(archivedKeySets == [snapshot])
|
||||
#expect(snapshot.certificate == "certificate")
|
||||
#expect(snapshot.privateKey == "private-key")
|
||||
#expect(snapshot.publicKey == "public-key")
|
||||
#expect(snapshot.passphrase == "passphrase")
|
||||
}
|
||||
|
||||
@Test("Explicit local removal also clears stale server-key state")
|
||||
func removalClearsStaleState() {
|
||||
let account = "e2ee-archive-\(UUID().uuidString)"
|
||||
let preferences = NCPreferences()
|
||||
|
||||
preferences.setEndToEndServerKeyStale(account: account, stale: true)
|
||||
preferences.clearAllKeysEndToEnd(account: account)
|
||||
|
||||
#expect(!preferences.isEndToEndServerKeyStale(account: account))
|
||||
}
|
||||
|
||||
@Test("Archiving the same credentials does not create duplicates")
|
||||
func avoidsDuplicates() throws {
|
||||
let account = "e2ee-archive-\(UUID().uuidString)"
|
||||
let preferences = NCPreferences()
|
||||
defer {
|
||||
preferences.clearAllKeysEndToEnd(account: account)
|
||||
}
|
||||
|
||||
setKeySet(on: preferences, account: account)
|
||||
let firstArchivedKeySet = try preferences.archiveCurrentEndToEndKeySet(account: account)
|
||||
let secondArchivedKeySet = try preferences.archiveCurrentEndToEndKeySet(account: account)
|
||||
let firstSnapshot = try #require(firstArchivedKeySet)
|
||||
let secondSnapshot = try #require(secondArchivedKeySet)
|
||||
|
||||
#expect(secondSnapshot.identifier == firstSnapshot.identifier)
|
||||
#expect(try preferences.getArchivedEndToEndKeySets(account: account).count == 1)
|
||||
}
|
||||
|
||||
@Test("A partial setup is archived when it contains usable key material")
|
||||
func preservesPartialKeyMaterial() throws {
|
||||
let account = "e2ee-archive-\(UUID().uuidString)"
|
||||
let preferences = NCPreferences()
|
||||
defer {
|
||||
preferences.clearAllKeysEndToEnd(account: account)
|
||||
}
|
||||
|
||||
preferences.setEndToEndPrivateKey(account: account, privateKey: "private-key")
|
||||
|
||||
let archivedKeySet = try preferences.archiveCurrentEndToEndKeySet(account: account)
|
||||
let snapshot = try #require(archivedKeySet)
|
||||
|
||||
#expect(snapshot.privateKey == "private-key")
|
||||
#expect(snapshot.certificate == nil)
|
||||
#expect(snapshot.publicKey == nil)
|
||||
#expect(snapshot.passphrase == nil)
|
||||
}
|
||||
|
||||
private func setKeySet(on preferences: NCPreferences, account: String) {
|
||||
preferences.setEndToEndCertificate(account: account, certificate: "certificate")
|
||||
preferences.setEndToEndPrivateKey(account: account, privateKey: "private-key")
|
||||
preferences.setEndToEndPublicKey(account: account, publicKey: "public-key")
|
||||
preferences.setEndToEndPassphrase(account: account, passphrase: "passphrase")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import Nextcloud
|
||||
|
||||
@Suite("End-to-end key set resolver")
|
||||
struct NCEndToEndKeySetResolverTests {
|
||||
@Test("The active key set has priority over archived key sets")
|
||||
func activeKeySetHasPriority() throws {
|
||||
let active = try #require(makeKeySet(identifier: "active"))
|
||||
let archived = try #require(makeKeySet(identifier: "archived"))
|
||||
|
||||
let access = NCEndToEndKeySetResolver().select(
|
||||
currentKeySet: active,
|
||||
archivedKeySets: [archived],
|
||||
canDecrypt: { _ in true }
|
||||
)
|
||||
|
||||
#expect(access == .active(active))
|
||||
#expect(access.canWrite)
|
||||
#expect(access.writeAccessError == .success)
|
||||
}
|
||||
|
||||
@Test("Equivalent PEM formatting identifies the same public key")
|
||||
func equivalentPublicKeysMatch() {
|
||||
let compact = "-----BEGIN PUBLIC KEY-----\nYWJjZA==\n-----END PUBLIC KEY-----"
|
||||
let wrapped = "-----BEGIN PUBLIC KEY-----\nYWJj\nZA==\n-----END PUBLIC KEY-----\n"
|
||||
let empty = "-----BEGIN PUBLIC KEY-----\n-----END PUBLIC KEY-----"
|
||||
|
||||
#expect(NCNetworkingE2EE().publicKeysMatch(compact, wrapped))
|
||||
#expect(!NCNetworkingE2EE().publicKeysMatch(compact, "different-key"))
|
||||
#expect(!NCNetworkingE2EE().publicKeysMatch(empty, empty))
|
||||
}
|
||||
|
||||
@Test("A stale local key is excluded from active write access")
|
||||
func staleKeyIsNotActive() throws {
|
||||
let account = "e2ee-stale-\(UUID().uuidString)"
|
||||
let preferences = NCPreferences()
|
||||
defer {
|
||||
preferences.clearAllKeysEndToEnd(account: account)
|
||||
}
|
||||
|
||||
preferences.setEndToEndCertificate(account: account, certificate: "certificate")
|
||||
preferences.setEndToEndPrivateKey(account: account, privateKey: "private-key")
|
||||
preferences.setEndToEndPublicKey(account: account, publicKey: "public-key")
|
||||
preferences.setEndToEndPassphrase(account: account, passphrase: "passphrase")
|
||||
try preferences.archiveCurrentEndToEndKeySet(account: account)
|
||||
preferences.setEndToEndServerKeyStale(account: account, stale: true)
|
||||
|
||||
let resolver = NCEndToEndKeySetResolver(preferences: preferences)
|
||||
let archivedKeySets = try preferences.getArchivedEndToEndKeySets(account: account)
|
||||
let archivedKeySet = try #require(archivedKeySets.last)
|
||||
let access = resolver.select(
|
||||
currentKeySet: resolver.currentKeySet(account: account),
|
||||
archivedKeySets: archivedKeySets,
|
||||
canDecrypt: { _ in true }
|
||||
)
|
||||
|
||||
#expect(access == .archived(archivedKeySet))
|
||||
#expect(!access.canWrite)
|
||||
}
|
||||
|
||||
@Test("The most recently archived matching key set is selected")
|
||||
func newestArchivedKeySetHasPriority() throws {
|
||||
let oldest = try #require(makeKeySet(identifier: "oldest"))
|
||||
let newest = try #require(makeKeySet(identifier: "newest"))
|
||||
|
||||
let access = NCEndToEndKeySetResolver().select(
|
||||
currentKeySet: nil,
|
||||
archivedKeySets: [oldest, newest],
|
||||
canDecrypt: { _ in true }
|
||||
)
|
||||
|
||||
#expect(access == .archived(newest))
|
||||
#expect(access.isReadOnly)
|
||||
#expect(access.writeAccessError.errorCode == NCGlobal.shared.errorE2EEReadOnly)
|
||||
}
|
||||
|
||||
@Test("Access is unavailable when no key set can decrypt metadata")
|
||||
func unavailableWithoutMatchingKeySet() throws {
|
||||
let active = try #require(makeKeySet(identifier: "active"))
|
||||
let archived = try #require(makeKeySet(identifier: "archived"))
|
||||
|
||||
let access = NCEndToEndKeySetResolver().select(
|
||||
currentKeySet: active,
|
||||
archivedKeySets: [archived],
|
||||
canDecrypt: { _ in false }
|
||||
)
|
||||
|
||||
#expect(access == .unavailable)
|
||||
#expect(!access.canWrite)
|
||||
#expect(!access.isReadOnly)
|
||||
#expect(access.writeAccessError.errorCode == NCGlobal.shared.errorE2EENoUserFound)
|
||||
}
|
||||
|
||||
@Test("A V2 child folder inherits its encrypted root metadata key")
|
||||
func childFolderUsesRootEncryptedMetadataKey() {
|
||||
let encryptedMetadataKey = NCEndToEndKeySetResolver().encryptedMetadataKey(
|
||||
users: nil,
|
||||
userId: "user",
|
||||
rootEncryptedMetadataKey: "root-key"
|
||||
)
|
||||
|
||||
#expect(encryptedMetadataKey == "root-key")
|
||||
}
|
||||
|
||||
@Test("A V2 child folder with an empty users array inherits its encrypted root metadata key")
|
||||
func childFolderWithEmptyUsersUsesRootEncryptedMetadataKey() {
|
||||
let encryptedMetadataKey = NCEndToEndKeySetResolver().encryptedMetadataKey(
|
||||
users: [],
|
||||
userId: "user",
|
||||
rootEncryptedMetadataKey: "root-key"
|
||||
)
|
||||
|
||||
#expect(encryptedMetadataKey == "root-key")
|
||||
}
|
||||
|
||||
@Test("A V2 root never falls back to a previously saved user key")
|
||||
func rootWithoutCurrentUserDoesNotUseSavedKey() {
|
||||
let otherUser = NCEndToEndMetadata.E2eeV2.Users(
|
||||
userId: "other-user",
|
||||
certificate: "certificate",
|
||||
encryptedMetadataKey: "other-key"
|
||||
)
|
||||
|
||||
let encryptedMetadataKey = NCEndToEndKeySetResolver().encryptedMetadataKey(
|
||||
users: [otherUser],
|
||||
userId: "user",
|
||||
rootEncryptedMetadataKey: "saved-root-key"
|
||||
)
|
||||
|
||||
#expect(encryptedMetadataKey == nil)
|
||||
}
|
||||
|
||||
private func makeKeySet(identifier: String) -> NCEndToEndKeySet? {
|
||||
NCEndToEndKeySet(
|
||||
certificate: "certificate-" + identifier,
|
||||
privateKey: "private-key-" + identifier,
|
||||
publicKey: "public-key-" + identifier,
|
||||
passphrase: "passphrase-" + identifier,
|
||||
identifier: identifier,
|
||||
archivedAt: Date(timeIntervalSince1970: 0)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Testing
|
||||
import UIKit
|
||||
@testable import Nextcloud
|
||||
|
||||
@Suite("Image zoom view")
|
||||
@MainActor
|
||||
struct NCImageZoomViewTests {
|
||||
@Test("Replacing an image preserves its zoom scale and focal point")
|
||||
func preservesZoomStateWhenImageChanges() throws {
|
||||
let (coordinator, scrollView, imageView) = makeZoomView(
|
||||
imageSize: CGSize(width: 400, height: 300)
|
||||
)
|
||||
|
||||
scrollView.setZoomScale(3, animated: false)
|
||||
scrollView.contentOffset = CGPoint(x: 220, y: 70)
|
||||
|
||||
let zoomState = try #require(coordinator.zoomState())
|
||||
|
||||
imageView.image = makeImage(
|
||||
size: CGSize(width: 300, height: 400)
|
||||
)
|
||||
coordinator.layoutImageView(preserving: zoomState)
|
||||
|
||||
let restoredZoomState = try #require(coordinator.zoomState())
|
||||
|
||||
#expect(abs(restoredZoomState.zoomScale - zoomState.zoomScale) < 0.001)
|
||||
#expect(abs(restoredZoomState.normalizedCenter.x - zoomState.normalizedCenter.x) < 0.001)
|
||||
#expect(abs(restoredZoomState.normalizedCenter.y - zoomState.normalizedCenter.y) < 0.001)
|
||||
}
|
||||
|
||||
@Test("Relayout without a saved state resets zoom")
|
||||
func resetsZoomWithoutSavedState() {
|
||||
let (coordinator, scrollView, imageView) = makeZoomView(
|
||||
imageSize: CGSize(width: 400, height: 300)
|
||||
)
|
||||
|
||||
scrollView.setZoomScale(3, animated: false)
|
||||
imageView.image = makeImage(
|
||||
size: CGSize(width: 800, height: 600)
|
||||
)
|
||||
|
||||
coordinator.layoutImageViewResettingZoom()
|
||||
|
||||
#expect(scrollView.zoomScale == scrollView.minimumZoomScale)
|
||||
#expect(coordinator.zoomState() == nil)
|
||||
}
|
||||
|
||||
@Test("A full orientation round trip preserves zoom and focal point")
|
||||
func preservesZoomStateAfterOrientationRoundTrip() throws {
|
||||
let (coordinator, scrollView, _) = makeZoomView(
|
||||
imageSize: CGSize(width: 400, height: 300)
|
||||
)
|
||||
|
||||
scrollView.setZoomScale(3, animated: false)
|
||||
scrollView.contentOffset = CGPoint(x: 0, y: 70)
|
||||
coordinator.recordCurrentZoomState()
|
||||
|
||||
let zoomState = try #require(coordinator.zoomState())
|
||||
|
||||
for _ in 0..<3 {
|
||||
scrollView.bounds = CGRect(
|
||||
origin: scrollView.bounds.origin,
|
||||
size: CGSize(width: 480, height: 320)
|
||||
)
|
||||
coordinator.layoutImageViewPreservingOnBoundsChange()
|
||||
|
||||
// UIKit can deliver automatic scrolling after a rotation finishes.
|
||||
scrollView.contentOffset = .zero
|
||||
coordinator.scrollViewDidScroll(scrollView)
|
||||
|
||||
scrollView.bounds = CGRect(
|
||||
origin: scrollView.bounds.origin,
|
||||
size: CGSize(width: 320, height: 480)
|
||||
)
|
||||
coordinator.layoutImageViewPreservingOnBoundsChange()
|
||||
|
||||
let restoredZoomState = try #require(coordinator.zoomState())
|
||||
#expect(abs(restoredZoomState.zoomScale - zoomState.zoomScale) < 0.001)
|
||||
#expect(abs(restoredZoomState.normalizedCenter.x - zoomState.normalizedCenter.x) < 0.001)
|
||||
#expect(abs(restoredZoomState.normalizedCenter.y - zoomState.normalizedCenter.y) < 0.001)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Images remain fitted and centered through an upper-region round trip", arguments: [
|
||||
CGSize(width: 400, height: 300),
|
||||
CGSize(width: 300, height: 400),
|
||||
CGSize(width: 400, height: 400)
|
||||
])
|
||||
func centersImageThroughFoldRoundTrip(imageSize: CGSize) {
|
||||
let (coordinator, scrollView, imageView) = makeZoomView(imageSize: imageSize)
|
||||
// UIScrollView rounds offsets to physical pixels; an exact center can fall halfway between them.
|
||||
let centeringTolerance = 0.5 / max(scrollView.traitCollection.displayScale, 1) + 0.001
|
||||
|
||||
for size in [CGSize(width: 320, height: 480), CGSize(width: 320, height: 220), CGSize(width: 320, height: 480)] {
|
||||
scrollView.bounds.size = size
|
||||
coordinator.layoutImageViewPreservingOnBoundsChange()
|
||||
|
||||
let scale = min(size.width / imageSize.width, size.height / imageSize.height)
|
||||
#expect(abs(imageView.frame.width - imageSize.width * scale) < 0.001)
|
||||
#expect(abs(imageView.frame.height - imageSize.height * scale) < 0.001)
|
||||
let visibleCenter = imageView.convert(
|
||||
CGPoint(x: imageView.bounds.midX, y: imageView.bounds.midY),
|
||||
to: scrollView
|
||||
)
|
||||
#expect(abs(visibleCenter.x - scrollView.bounds.midX) < centeringTolerance)
|
||||
#expect(abs(visibleCenter.y - scrollView.bounds.midY) < centeringTolerance)
|
||||
#expect(coordinator.zoomState() == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Folding and unfolding retain the zoomed image focal point")
|
||||
func preservesImageZoomThroughFoldRoundTrip() throws {
|
||||
let (coordinator, scrollView, _) = makeZoomView(imageSize: CGSize(width: 400, height: 300))
|
||||
scrollView.setZoomScale(3, animated: false)
|
||||
scrollView.contentOffset = CGPoint(x: 320, y: 120)
|
||||
coordinator.recordCurrentZoomState()
|
||||
let savedState = try #require(coordinator.zoomState())
|
||||
|
||||
for size in [CGSize(width: 320, height: 220), CGSize(width: 320, height: 480)] {
|
||||
scrollView.bounds.size = size
|
||||
coordinator.layoutImageViewPreservingOnBoundsChange()
|
||||
let restoredState = try #require(coordinator.zoomState())
|
||||
#expect(abs(restoredState.zoomScale - savedState.zoomScale) < 0.001)
|
||||
#expect(abs(restoredState.normalizedCenter.x - savedState.normalizedCenter.x) < 0.001)
|
||||
#expect(abs(restoredState.normalizedCenter.y - savedState.normalizedCenter.y) < 0.001)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Double-tap zoom survives view recreation and rotation")
|
||||
func preservesDoubleTapZoomAfterViewRecreation() throws {
|
||||
var persistedZoomState: NCImageZoomView.ZoomState?
|
||||
let (firstCoordinator, firstScrollView, firstImageView) = makeZoomView(
|
||||
imageSize: CGSize(width: 400, height: 300),
|
||||
onZoomStateChanged: { persistedZoomState = $0 }
|
||||
)
|
||||
|
||||
firstCoordinator.toggleZoom(
|
||||
at: CGPoint(
|
||||
x: firstImageView.bounds.midX,
|
||||
y: firstImageView.bounds.midY
|
||||
),
|
||||
animated: false
|
||||
)
|
||||
|
||||
let expectedZoomState = try #require(persistedZoomState)
|
||||
#expect(abs(firstScrollView.zoomScale - expectedZoomState.zoomScale) < 0.001)
|
||||
|
||||
let (restoredCoordinator, restoredScrollView, _) = makeZoomView(
|
||||
imageSize: CGSize(width: 400, height: 300),
|
||||
initialZoomState: expectedZoomState
|
||||
)
|
||||
|
||||
restoredScrollView.bounds = CGRect(
|
||||
origin: restoredScrollView.bounds.origin,
|
||||
size: CGSize(width: 480, height: 320)
|
||||
)
|
||||
restoredCoordinator.layoutImageViewPreservingOnBoundsChange()
|
||||
|
||||
let restoredZoomState = try #require(restoredCoordinator.zoomState())
|
||||
#expect(abs(restoredZoomState.zoomScale - expectedZoomState.zoomScale) < 0.001)
|
||||
#expect(abs(restoredZoomState.normalizedCenter.x - expectedZoomState.normalizedCenter.x) < 0.001)
|
||||
#expect(abs(restoredZoomState.normalizedCenter.y - expectedZoomState.normalizedCenter.y) < 0.001)
|
||||
}
|
||||
|
||||
@Test("Live Photo playback uses the still image zoom and focal point")
|
||||
func livePhotoPlaybackPreservesZoomState() {
|
||||
let zoomState = NCImageZoomView.ZoomState(
|
||||
zoomScale: 3,
|
||||
normalizedCenter: CGPoint(x: 0.6, y: 0.55)
|
||||
)
|
||||
let layout = NCLivePhotoPlaybackLayout(
|
||||
containerSize: CGSize(width: 320, height: 480),
|
||||
photoSize: CGSize(width: 400, height: 300),
|
||||
zoomState: zoomState
|
||||
)
|
||||
|
||||
#expect(abs(layout.frame.width - 960) < 0.001)
|
||||
#expect(abs(layout.frame.height - 720) < 0.001)
|
||||
#expect(abs(
|
||||
layout.frame.origin.x + layout.frame.width * zoomState.normalizedCenter.x - 160
|
||||
) < 0.001)
|
||||
#expect(abs(
|
||||
layout.frame.origin.y + layout.frame.height * zoomState.normalizedCenter.y - 240
|
||||
) < 0.001)
|
||||
}
|
||||
|
||||
@Test("Live Photo playback remains aspect-fit without zoom")
|
||||
func livePhotoPlaybackUsesAspectFitWithoutZoom() {
|
||||
let layout = NCLivePhotoPlaybackLayout(
|
||||
containerSize: CGSize(width: 320, height: 480),
|
||||
photoSize: CGSize(width: 400, height: 300),
|
||||
zoomState: nil
|
||||
)
|
||||
|
||||
#expect(layout.frame == CGRect(x: 0, y: 120, width: 320, height: 240))
|
||||
}
|
||||
|
||||
@Test("Live Photo playback clamps transient elastic zoom")
|
||||
func livePhotoPlaybackClampsElasticZoom() {
|
||||
let layout = NCLivePhotoPlaybackLayout(
|
||||
containerSize: CGSize(width: 320, height: 480),
|
||||
photoSize: CGSize(width: 400, height: 300),
|
||||
zoomState: NCImageZoomView.ZoomState(
|
||||
zoomScale: 20,
|
||||
normalizedCenter: CGPoint(x: 0.5, y: 0.5)
|
||||
)
|
||||
)
|
||||
|
||||
#expect(layout.frame == CGRect(x: -640, y: -360, width: 1_600, height: 1_200))
|
||||
}
|
||||
|
||||
@Test("Persisted zoom state clamps transient elastic zoom")
|
||||
func persistedZoomStateClampsElasticZoom() throws {
|
||||
var persistedZoomState: NCImageZoomView.ZoomState?
|
||||
let (coordinator, scrollView, _) = makeZoomView(
|
||||
imageSize: CGSize(width: 400, height: 300),
|
||||
onZoomStateChanged: { persistedZoomState = $0 }
|
||||
)
|
||||
|
||||
// Allow the test scroll view to reproduce the temporary value that
|
||||
// UIScrollView can report while bouncesZoom is active.
|
||||
scrollView.maximumZoomScale = 20
|
||||
scrollView.setZoomScale(20, animated: false)
|
||||
coordinator.scrollViewDidEndZooming(
|
||||
scrollView,
|
||||
with: nil,
|
||||
atScale: scrollView.zoomScale
|
||||
)
|
||||
|
||||
let zoomState = try #require(persistedZoomState)
|
||||
|
||||
#expect(zoomState.zoomScale == coordinator.maximumZoomScale)
|
||||
}
|
||||
|
||||
private func makeZoomView(
|
||||
imageSize: CGSize,
|
||||
initialZoomState: NCImageZoomView.ZoomState? = nil,
|
||||
onZoomStateChanged: @escaping (NCImageZoomView.ZoomState?) -> Void = { _ in }
|
||||
) -> (
|
||||
NCImageZoomView.Coordinator,
|
||||
NCImageZoomView.NCZoomScrollView,
|
||||
UIImageView
|
||||
) {
|
||||
let coordinator = NCImageZoomView.Coordinator()
|
||||
let scrollView = NCImageZoomView.NCZoomScrollView(
|
||||
frame: CGRect(x: 0, y: 0, width: 320, height: 480)
|
||||
)
|
||||
let imageView = UIImageView(
|
||||
image: makeImage(size: imageSize)
|
||||
)
|
||||
|
||||
scrollView.minimumZoomScale = 1
|
||||
scrollView.maximumZoomScale = 5
|
||||
scrollView.delegate = coordinator
|
||||
scrollView.addSubview(imageView)
|
||||
|
||||
coordinator.minimumZoomScale = 1
|
||||
coordinator.maximumZoomScale = 5
|
||||
coordinator.scrollView = scrollView
|
||||
coordinator.imageView = imageView
|
||||
coordinator.onZoomStateChanged = onZoomStateChanged
|
||||
coordinator.restorePersistedZoomState(initialZoomState)
|
||||
coordinator.layoutImageView(preserving: initialZoomState)
|
||||
|
||||
return (coordinator, scrollView, imageView)
|
||||
}
|
||||
|
||||
private func makeImage(size: CGSize) -> UIImage {
|
||||
UIGraphicsImageRenderer(size: size).image { context in
|
||||
UIColor.black.setFill()
|
||||
context.fill(CGRect(origin: .zero, size: size))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,555 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import SwiftUI
|
||||
import Testing
|
||||
import UIKit
|
||||
import NextcloudKit
|
||||
@testable import Nextcloud
|
||||
|
||||
@Suite("Adaptive media layout")
|
||||
@MainActor
|
||||
struct NCMediaAdaptiveLayoutViewTests {
|
||||
@Test("Adaptive navigation remains within the available middle area", arguments: [CGFloat(-1), 0, 20, 49, 100, 330, 500])
|
||||
func navigationFitsSmallAndLargeRegions(height: CGFloat) {
|
||||
let navigationHeight = NCMediaAdaptiveControlsLayout.navigationHeight(availableHeight: height)
|
||||
#expect(navigationHeight >= 0)
|
||||
#expect(navigationHeight <= max(0, height - NCMediaAdaptiveControlsLayout.spacing))
|
||||
#expect(navigationHeight <= NCMediaAdaptiveControlsLayout.actionsHeight)
|
||||
if height >= NCMediaAdaptiveControlsLayout.actionsHeight + NCMediaAdaptiveControlsLayout.spacing {
|
||||
#expect(navigationHeight == NCMediaAdaptiveControlsLayout.actionsHeight)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Folded video playback stays black and unfolded playback retains its policy", arguments: [false, true])
|
||||
func videoPlaybackBackground(isChromeHidden: Bool) {
|
||||
let folded = ncViewerVideoPlaybackBackgroundStyle(for: nil, isChromeHidden: isChromeHidden, isFoldedLayout: true)
|
||||
let unfolded = ncViewerVideoPlaybackBackgroundStyle(for: nil, isChromeHidden: isChromeHidden, isFoldedLayout: false)
|
||||
for appearance in [UIUserInterfaceStyle.light, .dark] {
|
||||
let traits = UITraitCollection(userInterfaceStyle: appearance)
|
||||
#expect(UIColor.ncViewerBackground(folded).resolvedColor(with: traits).isEqual(UIColor.black))
|
||||
let expected = UIColor.ncViewerBackground(ncViewerBackgroundStyle(for: nil, isChromeHidden: isChromeHidden)).resolvedColor(with: traits)
|
||||
#expect(UIColor.ncViewerBackground(unfolded).resolvedColor(with: traits).isEqual(expected))
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Control appearance follows the viewer background", arguments: [ColorScheme.light, .dark])
|
||||
func controlAppearanceMatchesBackground(inherited: ColorScheme) {
|
||||
#expect(ncViewerAdaptiveControlsColorScheme(for: .system, inherited: inherited) == inherited)
|
||||
#expect(ncViewerAdaptiveControlsColorScheme(for: .black, inherited: inherited) == .dark)
|
||||
#expect(ncViewerAdaptiveControlsColorScheme(for: .white, inherited: inherited) == .light)
|
||||
}
|
||||
|
||||
@Test("Normal and adaptive media share the standard appearance and tap behavior", arguments: [false, true])
|
||||
func normalBackgroundPreservesAppearanceAndChrome(isChromeHidden: Bool) {
|
||||
let style = ncViewerBackgroundStyle(for: nil, isChromeHidden: isChromeHidden)
|
||||
let panelStyle = ncViewerAdaptivePanelBackgroundStyle(contentStyle: style)
|
||||
for appearance in [UIUserInterfaceStyle.light, .dark] {
|
||||
let traits = UITraitCollection(userInterfaceStyle: appearance)
|
||||
let expected = (isChromeHidden ? UIColor.black : UIColor.systemBackground).resolvedColor(with: traits)
|
||||
#expect(UIColor.ncViewerBackground(style).resolvedColor(with: traits).isEqual(expected))
|
||||
#expect(UIColor.ncViewerBackground(panelStyle).resolvedColor(with: traits).isEqual(expected))
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Adaptive video footer retains its host and reserves the shared bottom lane")
|
||||
func videoFooterPreservesHostOnResize() throws {
|
||||
let metadata = tableMetadata()
|
||||
metadata.ocId = "video-footer"
|
||||
metadata.classFile = NKTypeClassFile.video.rawValue
|
||||
let model = NCMediaViewerModel(
|
||||
currentMetadata: metadata, ocIds: [metadata.ocId],
|
||||
session: NCSession().getSession(account: ""), loader: NCMediaViewerLoader()
|
||||
)
|
||||
let controls = NCVideoAdaptiveControlsView(state: NCVideoControlsState())
|
||||
// Give Auto Layout a fixed container; the hosted SwiftUI content must not size the test root.
|
||||
let container = UIView(frame: CGRect(x: 0, y: 0, width: 430, height: 330))
|
||||
container.addSubview(controls)
|
||||
NSLayoutConstraint.activate([
|
||||
controls.leadingAnchor.constraint(equalTo: container.leadingAnchor),
|
||||
controls.trailingAnchor.constraint(equalTo: container.trailingAnchor),
|
||||
controls.topAnchor.constraint(equalTo: container.topAnchor),
|
||||
controls.bottomAnchor.constraint(equalTo: container.bottomAnchor)
|
||||
])
|
||||
controls.configurePaging(model: model, onSelectPage: { _ in })
|
||||
let host = try #require(controls.pagingFooterView.subviews.first)
|
||||
for height in [CGFloat(330), 500] {
|
||||
container.frame.size.height = height
|
||||
container.setNeedsLayout()
|
||||
container.layoutIfNeeded()
|
||||
#expect(controls.bounds.size == CGSize(width: 430, height: height))
|
||||
let middleHeight = max(
|
||||
0, height - NCMediaAdaptiveActionsView.preferredHeight - NCMediaViewerThumbnail.preferredHeight - 20 - NCMediaAdaptiveControlsLayout.thumbnailBottomInset
|
||||
)
|
||||
let navigationHeight = min(max(0, middleHeight - 5), NCMediaAdaptiveControlsLayout.actionsHeight)
|
||||
#expect(controls.pagingFooterView.frame.maxY == height)
|
||||
#expect(controls.pagingFooterView.frame.height == navigationHeight + NCMediaViewerThumbnail.preferredHeight + 15 + NCMediaAdaptiveControlsLayout.thumbnailBottomInset)
|
||||
#expect(controls.pagingFooterView.subviews.first === host)
|
||||
#expect(controls.bottomControlsView.frame.maxY <= controls.pagingFooterView.frame.minY)
|
||||
}
|
||||
controls.configurePaging(model: nil, onSelectPage: { _ in })
|
||||
container.layoutIfNeeded()
|
||||
#expect(controls.pagingFooterView.subviews.isEmpty)
|
||||
#expect(controls.pagingFooterView.frame == .zero)
|
||||
}
|
||||
|
||||
@Test("Adaptive controls share playback state without adding a navigation bar")
|
||||
func separateAdaptiveControls() throws {
|
||||
let normalControls = NCVideoControlsView()
|
||||
let adaptiveControls = NCVideoAdaptiveControlsView(state: normalControls.state)
|
||||
adaptiveControls.configureAdaptiveActions(closeAction: UIAction { _ in }, moreButton: UIButton(type: .system))
|
||||
#expect(adaptiveControls.actionsContainerView.superview === adaptiveControls)
|
||||
#expect(!adaptiveControls.subviews.contains { $0 is UINavigationBar })
|
||||
#expect(!normalControls.subviews.contains { $0 is UINavigationBar })
|
||||
|
||||
normalControls.updateProgress(progress: 0.5, elapsedText: "1:00", remainingText: "−1:00")
|
||||
adaptiveControls.updatePlaybackOptions(isRepeatEnabled: true, isAutoAdvanceEnabled: true)
|
||||
#expect(adaptiveControls.state.progress == 0.5)
|
||||
#expect(normalControls.state.isRepeatEnabled)
|
||||
#expect(normalControls.state.isAutoAdvanceEnabled)
|
||||
#expect(normalControls.state === adaptiveControls.state)
|
||||
}
|
||||
|
||||
@Test("Standalone adaptive buttons preserve Close and Info actions")
|
||||
func adaptiveButtonsInvokeActions() throws {
|
||||
var closed = false
|
||||
var informationRequested = false
|
||||
let moreButton = UIButton(type: .system)
|
||||
let actions = NCMediaAdaptiveActionsView(
|
||||
closeAction: UIAction { _ in closed = true },
|
||||
moreButton: moreButton,
|
||||
infoAction: UIAction { _ in informationRequested = true }
|
||||
)
|
||||
let closeButton = try #require(actions.arrangedSubviews.first as? UIButton)
|
||||
let informationButton = try #require(actions.informationButton)
|
||||
let visibleButtons = actions.arrangedSubviews.compactMap { $0 as? UIButton }.filter { !$0.isHidden }
|
||||
#expect(visibleButtons.count == 3)
|
||||
#expect(visibleButtons.contains { $0 === closeButton })
|
||||
#expect(visibleButtons.contains { $0 === informationButton })
|
||||
closeButton.sendActions(for: .touchUpInside)
|
||||
informationButton.sendActions(for: .touchUpInside)
|
||||
#expect(closed)
|
||||
#expect(informationRequested)
|
||||
#expect(actions.arrangedSubviews.last === moreButton)
|
||||
#expect(!actions.arrangedSubviews.contains { $0 is UINavigationBar })
|
||||
}
|
||||
|
||||
@Test("Reused or neighboring video covers cannot remove the selected cover actions")
|
||||
func videoCoverActionsKeepTheirOwner() throws {
|
||||
let state = NCMediaAdaptiveControlsState()
|
||||
let oldOwner = UUID()
|
||||
let currentOwner = UUID()
|
||||
let neighborOwner = UUID()
|
||||
var played: [String] = []
|
||||
var cancelled = false
|
||||
let oldControls = NCVideoPlaybackCoverPresentation(
|
||||
isPlayEnabled: true,
|
||||
isLoading: false,
|
||||
isLaunchingPlayback: false,
|
||||
statusMessage: nil,
|
||||
onCancel: nil,
|
||||
onPlay: { played.append("old") }
|
||||
)
|
||||
let currentControls = NCVideoPlaybackCoverPresentation(
|
||||
isPlayEnabled: false,
|
||||
isLoading: true,
|
||||
isLaunchingPlayback: false,
|
||||
statusMessage: "Downloading",
|
||||
onCancel: { cancelled = true },
|
||||
onPlay: { played.append("current") }
|
||||
)
|
||||
state.setVideoCoverControls(oldControls, for: "selected", owner: oldOwner)
|
||||
state.setVideoCoverControls(currentControls, for: "selected", owner: currentOwner)
|
||||
state.setVideoCoverControls(oldControls, for: "neighbor", owner: neighborOwner)
|
||||
state.removeVideoCoverControls(for: "selected", owner: oldOwner)
|
||||
state.removeVideoCoverControls(for: "neighbor", owner: neighborOwner)
|
||||
|
||||
let controls = try #require(state.videoCoverControls(for: "selected"))
|
||||
#expect(controls.isLoading)
|
||||
#expect(!controls.isPlayEnabled)
|
||||
#expect(controls.statusMessage == "Downloading")
|
||||
controls.onPlay()
|
||||
controls.onCancel?()
|
||||
#expect(played == ["current"])
|
||||
#expect(cancelled)
|
||||
#expect(state.videoCoverControls(for: "neighbor") == nil)
|
||||
|
||||
state.removeVideoCoverControls(for: "selected", owner: currentOwner)
|
||||
#expect(state.videoCoverControls(for: "selected") == nil)
|
||||
}
|
||||
|
||||
@Test("Media folding retains the paging host and uses independent controls", arguments: [NKTypeClassFile.image.rawValue, NKTypeClassFile.audio.rawValue])
|
||||
func mediaFoldingPreservesPagingHost(classFile: String) throws {
|
||||
let metadata = tableMetadata()
|
||||
metadata.ocId = "image"
|
||||
metadata.classFile = classFile
|
||||
let model = NCMediaViewerModel(
|
||||
currentMetadata: metadata,
|
||||
ocIds: [metadata.ocId],
|
||||
session: NCSession().getSession(account: ""),
|
||||
loader: NCMediaViewerLoader()
|
||||
)
|
||||
let state = NCMediaAdaptiveControlsState()
|
||||
let controller = NCMediaAdaptiveLayoutController(
|
||||
mediaView: NCMediaViewerPagingView(
|
||||
model: model,
|
||||
contextMenuController: nil,
|
||||
navigationBar: nil,
|
||||
onVisibleMetadataChanged: { _ in },
|
||||
onZoomChanged: { _ in },
|
||||
onClose: { _ in }
|
||||
),
|
||||
normalControlsView: NCImageControlsView(model: model),
|
||||
adaptiveControlsView: NCMediaAdaptiveControlsView(
|
||||
model: model,
|
||||
state: state,
|
||||
makeActionsView: { UIView() }
|
||||
),
|
||||
onLayoutModeChanged: { _ in }
|
||||
)
|
||||
controller.loadViewIfNeeded()
|
||||
let view = controller.layoutView
|
||||
view.isLayoutEnabled = false
|
||||
let mediaView = try #require(controller.mediaController.view)
|
||||
view.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
|
||||
view.layoutIfNeeded()
|
||||
#expect(!view.isLayoutEnabled)
|
||||
#expect(controller.adaptiveControlsController == nil)
|
||||
|
||||
view.isLayoutEnabled = true
|
||||
view.updateLayout(divisionFrames: [CGRect(x: 0, y: 280, width: 800, height: 40)])
|
||||
let adaptiveController = try #require(controller.adaptiveControlsController)
|
||||
#expect(adaptiveController.rootView.state === state)
|
||||
#expect(adaptiveController.parent === controller)
|
||||
#expect(mediaView.frame.height == 280)
|
||||
#expect(controller.normalControlsController.view.superview?.isHidden == true)
|
||||
|
||||
// Updating the lower presentation must reach the retained host, not create a new one.
|
||||
let updatedState = NCMediaAdaptiveControlsState()
|
||||
controller.adaptiveControlsView = NCMediaAdaptiveControlsView(
|
||||
model: model,
|
||||
state: updatedState,
|
||||
makeActionsView: { UIView() }
|
||||
)
|
||||
#expect(adaptiveController.rootView.state === updatedState)
|
||||
#expect(controller.adaptiveControlsController === adaptiveController)
|
||||
|
||||
view.updateLayout(divisionFrames: [])
|
||||
#expect(controller.mediaController.view === mediaView)
|
||||
#expect(mediaView.frame == view.bounds)
|
||||
#expect(controller.adaptiveControlsController === adaptiveController)
|
||||
#expect(adaptiveController.view.isHidden)
|
||||
#expect(controller.normalControlsController.view.superview?.isHidden == false)
|
||||
}
|
||||
|
||||
@Test("A disabled container can be enabled and turned off again")
|
||||
func experimentalLayoutRequiresEnabling() {
|
||||
let videoView = UIView()
|
||||
let normalControlsView = UIView()
|
||||
let adaptiveControlsView = UIView()
|
||||
let view = NCMediaAdaptiveLayoutView(
|
||||
mediaView: videoView,
|
||||
normalControlsView: normalControlsView,
|
||||
isLayoutEnabled: false,
|
||||
adaptiveControlsView: { adaptiveControlsView }
|
||||
)
|
||||
view.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
|
||||
let fold = CGRect(x: 0, y: 280, width: 800, height: 40)
|
||||
var modes: [Bool] = []
|
||||
view.onLayoutModeChanged = { modes.append($0) }
|
||||
|
||||
#expect(!view.isLayoutEnabled)
|
||||
view.layoutIfNeeded()
|
||||
view.updateLayout(divisionFrames: [fold])
|
||||
#expect(!view.isFoldedLayout)
|
||||
#expect(videoView.frame == view.bounds)
|
||||
#expect(!normalControlsView.isHidden)
|
||||
#expect(adaptiveControlsView.superview == nil)
|
||||
#expect(view.subviews.count == 2)
|
||||
#expect(!videoView.translatesAutoresizingMaskIntoConstraints)
|
||||
#expect(!normalControlsView.translatesAutoresizingMaskIntoConstraints)
|
||||
#expect(view.constraints.count == 8)
|
||||
#expect(view.constraints.allSatisfy { $0.isActive })
|
||||
#expect(modes.isEmpty)
|
||||
|
||||
view.isLayoutEnabled = true
|
||||
view.updateLayout(divisionFrames: [fold])
|
||||
#expect(view.isFoldedLayout)
|
||||
#expect(normalControlsView.isHidden)
|
||||
#expect(!adaptiveControlsView.isHidden)
|
||||
|
||||
view.isLayoutEnabled = false
|
||||
view.layoutIfNeeded()
|
||||
view.updateLayout(divisionFrames: [fold])
|
||||
#expect(!view.isFoldedLayout)
|
||||
#expect(videoView.frame == view.bounds)
|
||||
#expect(!normalControlsView.isHidden)
|
||||
#expect(adaptiveControlsView.isHidden)
|
||||
#expect(modes == [true, false])
|
||||
}
|
||||
|
||||
@Test("A container can start enabled without activating normal layout constraints")
|
||||
func startsWithAdaptiveLayoutEnabled() {
|
||||
let mediaView = UIView()
|
||||
let normalControlsView = UIView()
|
||||
let adaptiveControlsView = UIView()
|
||||
let view = NCMediaAdaptiveLayoutView(
|
||||
mediaView: mediaView,
|
||||
normalControlsView: normalControlsView,
|
||||
isLayoutEnabled: true,
|
||||
adaptiveControlsView: { adaptiveControlsView }
|
||||
)
|
||||
view.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
|
||||
#expect(mediaView.translatesAutoresizingMaskIntoConstraints)
|
||||
#expect(normalControlsView.translatesAutoresizingMaskIntoConstraints)
|
||||
#expect(view.constraints.isEmpty)
|
||||
|
||||
view.updateLayout(divisionFrames: [CGRect(x: 0, y: 280, width: 800, height: 40)])
|
||||
#expect(view.isFoldedLayout)
|
||||
#expect(mediaView.frame.height == 280)
|
||||
#expect(adaptiveControlsView.frame.minY == 320)
|
||||
|
||||
view.isLayoutEnabled = false
|
||||
view.layoutIfNeeded()
|
||||
#expect(view.constraints.count == 8)
|
||||
#expect(view.constraints.allSatisfy { $0.isActive })
|
||||
#expect(!view.isFoldedLayout)
|
||||
#expect(mediaView.frame == view.bounds)
|
||||
}
|
||||
|
||||
@Test("Disabled mode does not create adaptive controls and preserves normal visibility")
|
||||
func disabledModePreservesNormalControls() {
|
||||
let videoView = UIView()
|
||||
let normalControlsView = UIView()
|
||||
var creationCount = 0
|
||||
var modes: [Bool] = []
|
||||
let view = NCMediaAdaptiveLayoutView(
|
||||
mediaView: videoView,
|
||||
normalControlsView: normalControlsView,
|
||||
isLayoutEnabled: false,
|
||||
adaptiveControlsView: {
|
||||
creationCount += 1
|
||||
return UIView()
|
||||
}
|
||||
)
|
||||
view.onLayoutModeChanged = { modes.append($0) }
|
||||
normalControlsView.isHidden = true
|
||||
normalControlsView.alpha = 0
|
||||
view.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
|
||||
view.layoutIfNeeded()
|
||||
view.updateLayout(divisionFrames: [CGRect(x: 0, y: 280, width: 800, height: 40)])
|
||||
|
||||
#expect(creationCount == 0)
|
||||
#expect(modes.isEmpty)
|
||||
#expect(normalControlsView.isHidden)
|
||||
#expect(normalControlsView.alpha == 0)
|
||||
#expect(videoView.frame == view.bounds)
|
||||
#expect(normalControlsView.frame == view.bounds)
|
||||
|
||||
normalControlsView.isHidden = false
|
||||
normalControlsView.alpha = 1
|
||||
view.frame = CGRect(x: 0, y: 0, width: 600, height: 800)
|
||||
view.layoutIfNeeded()
|
||||
|
||||
#expect(creationCount == 0)
|
||||
#expect(modes.isEmpty)
|
||||
#expect(!normalControlsView.isHidden)
|
||||
#expect(normalControlsView.alpha == 1)
|
||||
#expect(videoView.frame == view.bounds)
|
||||
#expect(normalControlsView.frame == view.bounds)
|
||||
}
|
||||
|
||||
@Test("Folding and unfolding preserve the video surface and controls")
|
||||
func foldingPreservesViews() {
|
||||
let videoView = UIView()
|
||||
let controlsView = UIView()
|
||||
let adaptiveControlsView = UIView()
|
||||
let view = NCMediaAdaptiveLayoutView(
|
||||
mediaView: videoView,
|
||||
normalControlsView: controlsView,
|
||||
adaptiveControlsView: { adaptiveControlsView }
|
||||
)
|
||||
view.isLayoutEnabled = true
|
||||
view.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
|
||||
var modes: [Bool] = []
|
||||
view.onLayoutModeChanged = { modes.append($0) }
|
||||
|
||||
view.updateLayout(divisionFrames: [])
|
||||
#expect(videoView.frame == view.bounds)
|
||||
#expect(controlsView.frame == view.bounds)
|
||||
|
||||
let fold = CGRect(x: -10, y: 280, width: 820, height: 40)
|
||||
view.updateLayout(divisionFrames: [fold])
|
||||
#expect(view.isFoldedLayout)
|
||||
#expect(videoView.frame == CGRect(x: 0, y: 0, width: 800, height: 280))
|
||||
#expect(adaptiveControlsView.frame == CGRect(x: 0, y: 320, width: 800, height: 280))
|
||||
#expect(controlsView.isHidden)
|
||||
#expect(!adaptiveControlsView.isHidden)
|
||||
|
||||
view.updateLayout(divisionFrames: [fold])
|
||||
#expect(modes == [true])
|
||||
|
||||
view.updateLayout(divisionFrames: [])
|
||||
#expect(!view.isFoldedLayout)
|
||||
#expect(videoView.frame == view.bounds)
|
||||
#expect(controlsView.frame == view.bounds)
|
||||
#expect(modes == [true, false])
|
||||
#expect(!controlsView.isHidden)
|
||||
#expect(adaptiveControlsView.isHidden)
|
||||
#expect(view.subviews.count == 3)
|
||||
#expect(view.subviews[0] === videoView)
|
||||
#expect(view.subviews[1] === controlsView)
|
||||
#expect(view.subviews[2] === adaptiveControlsView)
|
||||
}
|
||||
|
||||
@Test("An enabled experiment creates lower controls only when a fold becomes active")
|
||||
func unfoldedExperimentDoesNotCreateLowerControls() {
|
||||
var creationCount = 0
|
||||
let lowerControls = UIView()
|
||||
let normalControls = UIView()
|
||||
let view = NCMediaAdaptiveLayoutView(
|
||||
mediaView: UIView(),
|
||||
normalControlsView: normalControls,
|
||||
isLayoutEnabled: true,
|
||||
adaptiveControlsView: {
|
||||
creationCount += 1
|
||||
return lowerControls
|
||||
}
|
||||
)
|
||||
view.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
|
||||
view.updateLayout(divisionFrames: [])
|
||||
view.updateLayout(divisionFrames: [CGRect(x: 380, y: 0, width: 40, height: 600)])
|
||||
#expect(creationCount == 0)
|
||||
#expect(!normalControls.isHidden)
|
||||
|
||||
let fold = CGRect(x: 0, y: 280, width: 800, height: 40)
|
||||
view.updateLayout(divisionFrames: [fold])
|
||||
view.updateLayout(divisionFrames: [])
|
||||
view.updateLayout(divisionFrames: [fold])
|
||||
#expect(creationCount == 1)
|
||||
#expect(view.isFoldedLayout)
|
||||
#expect(lowerControls.superview === view)
|
||||
}
|
||||
|
||||
@Test("Enabled mode without a fold preserves normal chrome while resizing", arguments: [
|
||||
CGSize(width: 390, height: 844),
|
||||
CGSize(width: 844, height: 390),
|
||||
CGSize(width: 1024, height: 1366),
|
||||
CGSize(width: 420, height: 600)
|
||||
])
|
||||
func resizingWithoutFoldPreservesNormalChrome(size: CGSize) {
|
||||
let mediaView = UIView()
|
||||
let normalControls = UIView()
|
||||
normalControls.isHidden = true
|
||||
var creationCount = 0
|
||||
var modes: [Bool] = []
|
||||
let view = NCMediaAdaptiveLayoutView(
|
||||
mediaView: mediaView,
|
||||
normalControlsView: normalControls,
|
||||
isLayoutEnabled: true,
|
||||
adaptiveControlsView: {
|
||||
creationCount += 1
|
||||
return UIView()
|
||||
}
|
||||
)
|
||||
view.onLayoutModeChanged = { modes.append($0) }
|
||||
|
||||
for boundsSize in [CGSize(width: 800, height: 600), size, CGSize(width: 800, height: 600)] {
|
||||
view.frame = CGRect(origin: .zero, size: boundsSize)
|
||||
view.updateLayout(divisionFrames: [])
|
||||
#expect(mediaView.frame == view.bounds)
|
||||
#expect(normalControls.frame == view.bounds)
|
||||
#expect(normalControls.isHidden)
|
||||
#expect(!view.isFoldedLayout)
|
||||
}
|
||||
|
||||
#expect(creationCount == 0)
|
||||
#expect(modes.isEmpty)
|
||||
#expect(mediaView.superview === view)
|
||||
#expect(normalControls.superview === view)
|
||||
}
|
||||
|
||||
@Test("Unavailable adaptive controls preserve the normal layout and can recover")
|
||||
func unavailableLowerControlsKeepNormalLayout() {
|
||||
let mediaView = UIView()
|
||||
let normalControls = UIView()
|
||||
let lowerControls = UIView()
|
||||
var available = false
|
||||
var modes: [Bool] = []
|
||||
let view = NCMediaAdaptiveLayoutView(
|
||||
mediaView: mediaView,
|
||||
normalControlsView: normalControls,
|
||||
isLayoutEnabled: true,
|
||||
adaptiveControlsView: { available ? lowerControls : nil }
|
||||
)
|
||||
view.onLayoutModeChanged = { modes.append($0) }
|
||||
view.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
|
||||
let fold = CGRect(x: 0, y: 280, width: 800, height: 40)
|
||||
view.updateLayout(divisionFrames: [fold])
|
||||
#expect(!view.isFoldedLayout)
|
||||
#expect(mediaView.frame == view.bounds)
|
||||
#expect(!normalControls.isHidden)
|
||||
#expect(modes.isEmpty)
|
||||
|
||||
available = true
|
||||
view.updateLayout(divisionFrames: [fold])
|
||||
#expect(view.isFoldedLayout)
|
||||
#expect(mediaView.frame.height == 280)
|
||||
#expect(!lowerControls.isHidden)
|
||||
#expect(normalControls.isHidden)
|
||||
#expect(modes == [true])
|
||||
}
|
||||
|
||||
@Test("Other regions retain the normal layout", arguments: [
|
||||
CGRect(x: 380, y: 0, width: 40, height: 600),
|
||||
CGRect(x: 0, y: 300, width: 800, height: 0),
|
||||
CGRect(x: 0, y: 700, width: 800, height: 40),
|
||||
CGRect(x: 0, y: 0, width: 800, height: 40),
|
||||
CGRect(x: 0, y: 560, width: 800, height: 40),
|
||||
CGRect(x: 200, y: 280, width: 100, height: 40)
|
||||
])
|
||||
func ignoresNonHorizontalDivisions(frame: CGRect) {
|
||||
let videoView = UIView()
|
||||
let controlsView = UIView()
|
||||
let adaptiveControlsView = UIView()
|
||||
let view = NCMediaAdaptiveLayoutView(
|
||||
mediaView: videoView,
|
||||
normalControlsView: controlsView,
|
||||
adaptiveControlsView: { adaptiveControlsView }
|
||||
)
|
||||
view.isLayoutEnabled = true
|
||||
view.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
|
||||
|
||||
view.updateLayout(divisionFrames: [frame])
|
||||
|
||||
#expect(!view.isFoldedLayout)
|
||||
#expect(videoView.frame == view.bounds)
|
||||
#expect(controlsView.frame == view.bounds)
|
||||
}
|
||||
|
||||
@Test("The layout follows changing fold geometry and view size")
|
||||
func followsFoldGeometry() {
|
||||
let videoView = UIView()
|
||||
let controlsView = UIView()
|
||||
let adaptiveControlsView = UIView()
|
||||
let view = NCMediaAdaptiveLayoutView(
|
||||
mediaView: videoView,
|
||||
normalControlsView: controlsView,
|
||||
adaptiveControlsView: { adaptiveControlsView }
|
||||
)
|
||||
view.isLayoutEnabled = true
|
||||
view.frame = CGRect(x: 0, y: 0, width: 600, height: 800)
|
||||
|
||||
view.updateLayout(divisionFrames: [CGRect(x: 0, y: 370, width: 600, height: 60)])
|
||||
|
||||
#expect(videoView.frame == CGRect(x: 0, y: 0, width: 600, height: 370))
|
||||
#expect(adaptiveControlsView.frame == CGRect(x: 0, y: 430, width: 600, height: 370))
|
||||
|
||||
view.updateLayout(divisionFrames: [CGRect(x: 0, y: 350, width: 600, height: 100)])
|
||||
|
||||
#expect(videoView.frame.height == 350)
|
||||
#expect(adaptiveControlsView.frame.minY == 450)
|
||||
#expect(adaptiveControlsView.frame.height == 350)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Testing
|
||||
@testable import Nextcloud
|
||||
|
||||
@Suite("Media playback completion options")
|
||||
@MainActor
|
||||
struct NCMediaPlaybackOptionsTests {
|
||||
@Test("Playback stops when no completion option is enabled")
|
||||
func stopsByDefault() {
|
||||
let options = NCMediaPlaybackOptions(preferences: nil)
|
||||
|
||||
#expect(options.completionAction == .stop)
|
||||
}
|
||||
|
||||
@Test("Automatic advance plays the next compatible item")
|
||||
func advancesAutomatically() {
|
||||
let options = NCMediaPlaybackOptions(preferences: nil)
|
||||
|
||||
options.toggleAutoAdvance()
|
||||
|
||||
#expect(options.completionAction == .playNextItem)
|
||||
}
|
||||
|
||||
@Test("Disabling repeat restores normal stop behavior")
|
||||
func disablingRepeatRestoresStop() {
|
||||
let options = NCMediaPlaybackOptions(preferences: nil)
|
||||
|
||||
options.toggleRepeat()
|
||||
#expect(options.completionAction == .repeatCurrentItem)
|
||||
|
||||
options.toggleRepeat()
|
||||
#expect(options.completionAction == .stop)
|
||||
}
|
||||
|
||||
@Test("Repeat takes precedence over automatic advance")
|
||||
func repeatTakesPrecedence() {
|
||||
let options = NCMediaPlaybackOptions(preferences: nil)
|
||||
|
||||
options.toggleAutoAdvance()
|
||||
options.toggleRepeat()
|
||||
|
||||
#expect(options.completionAction == .repeatCurrentItem)
|
||||
|
||||
options.toggleRepeat()
|
||||
|
||||
#expect(options.completionAction == .playNextItem)
|
||||
}
|
||||
|
||||
@Test("Playback options restore and save their preferences")
|
||||
func persistsPlaybackOptions() {
|
||||
let preferences = NCPreferences()
|
||||
let originalRepeat = preferences.mediaViewerRepeatCurrentItem
|
||||
let originalAutoAdvance = preferences.mediaViewerAutoAdvance
|
||||
|
||||
defer {
|
||||
preferences.mediaViewerRepeatCurrentItem = originalRepeat
|
||||
preferences.mediaViewerAutoAdvance = originalAutoAdvance
|
||||
}
|
||||
|
||||
preferences.mediaViewerRepeatCurrentItem = true
|
||||
preferences.mediaViewerAutoAdvance = false
|
||||
|
||||
let options = NCMediaPlaybackOptions(preferences: preferences)
|
||||
|
||||
#expect(options.isRepeatEnabled)
|
||||
#expect(!options.isAutoAdvanceEnabled)
|
||||
|
||||
options.toggleRepeat()
|
||||
options.toggleAutoAdvance()
|
||||
|
||||
#expect(!preferences.mediaViewerRepeatCurrentItem)
|
||||
#expect(preferences.mediaViewerAutoAdvance)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Testing
|
||||
import UIKit
|
||||
@testable import Nextcloud
|
||||
|
||||
@Suite("Media viewer floating title")
|
||||
@MainActor
|
||||
struct NCMediaViewerFloatingTitleViewTests {
|
||||
@Test("Preserves the system foreground color")
|
||||
func preservesSystemForegroundColor() throws {
|
||||
let titleView = NCMediaViewerFloatingTitleView()
|
||||
|
||||
titleView.update(
|
||||
primaryText: "Photo.jpg",
|
||||
secondaryText: "13 Aug 2026 at 09:17"
|
||||
)
|
||||
|
||||
let titleButton = try #require(
|
||||
titleView.subviews.first as? UIButton
|
||||
)
|
||||
titleView.frame = CGRect(x: 0, y: 0, width: 300, height: 44)
|
||||
titleView.layoutIfNeeded()
|
||||
|
||||
let configuration = try #require(titleButton.configuration)
|
||||
let transformer = try #require(
|
||||
configuration.titleTextAttributesTransformer
|
||||
)
|
||||
var incoming = AttributeContainer()
|
||||
incoming.uiKit.foregroundColor = .white
|
||||
let outgoing = transformer(incoming)
|
||||
|
||||
#expect(configuration.baseForegroundColor == nil)
|
||||
#expect(titleButton.isEnabled)
|
||||
#expect(titleButton.isUserInteractionEnabled)
|
||||
#expect(titleButton.state == .normal)
|
||||
#expect(titleButton.tintAdjustmentMode == .normal)
|
||||
#expect(
|
||||
titleView.hitTest(
|
||||
CGPoint(x: titleView.bounds.midX, y: titleView.bounds.midY),
|
||||
with: nil
|
||||
) == nil
|
||||
)
|
||||
#expect(titleButton.titleLabel?.text == "Photo.jpg")
|
||||
#expect(titleButton.subtitleLabel?.text == "13 Aug 2026 at 09:17")
|
||||
#expect(outgoing.uiKit.foregroundColor == .white)
|
||||
#expect(
|
||||
outgoing.uiKit.font == UIFont.systemFont(
|
||||
ofSize: 13,
|
||||
weight: .semibold
|
||||
)
|
||||
)
|
||||
|
||||
let normalTextColor = titleButton.titleLabel?.textColor
|
||||
titleView.tintAdjustmentMode = .dimmed
|
||||
titleView.layoutIfNeeded()
|
||||
|
||||
#expect(titleButton.isEnabled)
|
||||
#expect(titleButton.state == .normal)
|
||||
#expect(titleButton.tintAdjustmentMode == .normal)
|
||||
#expect(titleButton.titleLabel?.text == "Photo.jpg")
|
||||
#expect(titleButton.titleLabel?.textColor == normalTextColor)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Testing
|
||||
import NextcloudKit
|
||||
@testable import Nextcloud
|
||||
|
||||
@Suite("Media viewer model")
|
||||
@MainActor
|
||||
struct NCMediaViewerModelTests {
|
||||
@Test("Duplicate media identifiers produce a single viewer page")
|
||||
func removesDuplicateIdentifiers() {
|
||||
let metadata = tableMetadata()
|
||||
metadata.ocId = "current"
|
||||
|
||||
let model = NCMediaViewerInitialModel(
|
||||
currentMetadata: metadata,
|
||||
ocIds: ["first", "current", "current", "last", "first"]
|
||||
)
|
||||
|
||||
#expect(model.normalizedOcIds == ["first", "current", "last"])
|
||||
#expect(model.currentSelectedIndex == 1)
|
||||
}
|
||||
|
||||
@Test("Missing current media is inserted before the supplied identifiers")
|
||||
func insertsMissingCurrentIdentifier() {
|
||||
let metadata = tableMetadata()
|
||||
metadata.ocId = "current"
|
||||
|
||||
let model = NCMediaViewerInitialModel(
|
||||
currentMetadata: metadata,
|
||||
ocIds: ["next", "next"]
|
||||
)
|
||||
|
||||
#expect(model.normalizedOcIds == ["current", "next"])
|
||||
#expect(model.currentSelectedIndex == 0)
|
||||
}
|
||||
|
||||
@Test("Programmatic paging deactivates media until the target settles")
|
||||
func programmaticPagingActivatesOnlySettledTarget() {
|
||||
let model = makeViewerModel()
|
||||
|
||||
#expect(model.activePageIndex == 0)
|
||||
|
||||
model.beginPageTransition(
|
||||
to: 1,
|
||||
shouldAutoPlay: true
|
||||
)
|
||||
|
||||
#expect(model.pageTransition == .programmatic(targetIndex: 1))
|
||||
#expect(model.selectedIndex == 0)
|
||||
#expect(model.activePageIndex == nil)
|
||||
#expect(model.autoPlayTargetIndex == 1)
|
||||
|
||||
model.finishPageTransition(at: 1)
|
||||
|
||||
#expect(model.pageTransition == .idle)
|
||||
#expect(model.selectedIndex == 1)
|
||||
#expect(model.activePageIndex == 1)
|
||||
#expect(model.autoPlayTargetIndex == 1)
|
||||
}
|
||||
|
||||
@Test("Interactive paging keeps intermediate pages inactive")
|
||||
func interactivePagingKeepsIntermediatePagesInactive() {
|
||||
let model = makeViewerModel()
|
||||
|
||||
model.beginPageTransition(
|
||||
to: nil,
|
||||
shouldAutoPlay: false
|
||||
)
|
||||
model.updateSelectedIndexDuringTransition(1)
|
||||
|
||||
#expect(model.pageTransition == .interactive)
|
||||
#expect(model.selectedIndex == 1)
|
||||
#expect(model.activePageIndex == nil)
|
||||
|
||||
model.finishPageTransition(at: 1)
|
||||
|
||||
#expect(model.pageTransition == .idle)
|
||||
#expect(model.activePageIndex == 1)
|
||||
}
|
||||
|
||||
@Test("Settling on an unexpected page cancels pending autoplay")
|
||||
func unexpectedSettledPageCancelsAutoPlay() {
|
||||
let model = makeViewerModel()
|
||||
|
||||
model.beginPageTransition(
|
||||
to: 2,
|
||||
shouldAutoPlay: true
|
||||
)
|
||||
model.finishPageTransition(at: 1)
|
||||
|
||||
#expect(model.pageTransition == .idle)
|
||||
#expect(model.activePageIndex == 1)
|
||||
#expect(model.autoPlayTargetIndex == nil)
|
||||
}
|
||||
|
||||
@Test("Selection updates are ignored outside an interactive transition")
|
||||
func ignoresTransitionUpdatesWhileIdle() {
|
||||
let model = makeViewerModel()
|
||||
|
||||
model.updateSelectedIndexDuringTransition(1)
|
||||
|
||||
#expect(model.selectedIndex == 0)
|
||||
#expect(model.activePageIndex == 0)
|
||||
}
|
||||
|
||||
@Test("Loading a page does not implicitly change the selection")
|
||||
func loadingDoesNotSelectPage() async {
|
||||
let model = makeViewerModel()
|
||||
|
||||
await model.displayPage(at: 1)
|
||||
|
||||
#expect(model.selectedIndex == 0)
|
||||
#expect(model.activePageIndex == 0)
|
||||
}
|
||||
|
||||
@Test("Regular image previews do not require the original file")
|
||||
func regularImagePreviewDoesNotRequireOriginal() {
|
||||
let metadata = imageMetadata(fileName: "photo.HEIC")
|
||||
let policy = NCMediaViewerLoadingPolicy.standard
|
||||
|
||||
#expect(!policy.shouldDownloadOriginalImage(
|
||||
for: metadata,
|
||||
hasUsablePreview: true
|
||||
))
|
||||
}
|
||||
|
||||
@Test("GIF and SVG images always require the original file")
|
||||
func specialImageFormatsRequireOriginal() {
|
||||
let policy = NCMediaViewerLoadingPolicy.standard
|
||||
|
||||
#expect(policy.shouldDownloadOriginalImage(
|
||||
for: imageMetadata(fileName: "animation.GIF"),
|
||||
hasUsablePreview: true
|
||||
))
|
||||
#expect(policy.shouldDownloadOriginalImage(
|
||||
for: imageMetadata(fileName: "drawing.svg"),
|
||||
hasUsablePreview: true
|
||||
))
|
||||
}
|
||||
|
||||
@Test("A missing preview falls back to the original file")
|
||||
func missingPreviewRequiresOriginal() {
|
||||
let metadata = imageMetadata(fileName: "photo.jpg")
|
||||
let policy = NCMediaViewerLoadingPolicy.standard
|
||||
|
||||
#expect(policy.shouldDownloadOriginalImage(
|
||||
for: metadata,
|
||||
hasUsablePreview: false
|
||||
))
|
||||
}
|
||||
|
||||
@Test("The internal switch restores automatic original downloads")
|
||||
func internalSwitchEnablesOriginalDownloads() {
|
||||
let metadata = imageMetadata(fileName: "photo.jpg")
|
||||
let policy = NCMediaViewerLoadingPolicy(
|
||||
automaticallyDownloadsOriginalImages: true,
|
||||
automaticallyDownloadsLivePhotoResources: false
|
||||
)
|
||||
|
||||
#expect(policy.shouldDownloadOriginalImage(
|
||||
for: metadata,
|
||||
hasUsablePreview: true
|
||||
))
|
||||
}
|
||||
|
||||
@Test("Live Photo resources remain on demand unless their switch is enabled")
|
||||
func livePhotoResourcesRespectInternalSwitch() {
|
||||
let metadata = imageMetadata(fileName: "live-photo.heic")
|
||||
metadata.livePhotoFile = "live-photo.mov"
|
||||
|
||||
#expect(!NCMediaViewerLoadingPolicy.standard.shouldDownloadLivePhotoResources(
|
||||
for: metadata
|
||||
))
|
||||
|
||||
let automaticPolicy = NCMediaViewerLoadingPolicy(
|
||||
automaticallyDownloadsOriginalImages: false,
|
||||
automaticallyDownloadsLivePhotoResources: true
|
||||
)
|
||||
|
||||
#expect(automaticPolicy.shouldDownloadLivePhotoResources(for: metadata))
|
||||
#expect(automaticPolicy.shouldDownloadOriginalImage(
|
||||
for: metadata,
|
||||
hasUsablePreview: true
|
||||
))
|
||||
}
|
||||
|
||||
private func makeViewerModel() -> NCMediaViewerModel {
|
||||
let metadata = tableMetadata()
|
||||
metadata.ocId = "first"
|
||||
|
||||
return NCMediaViewerModel(
|
||||
currentMetadata: metadata,
|
||||
ocIds: ["first", "second", "third"],
|
||||
session: NCSession().getSession(account: ""),
|
||||
loader: NCMediaViewerLoader()
|
||||
)
|
||||
}
|
||||
|
||||
private func imageMetadata(fileName: String) -> tableMetadata {
|
||||
let metadata = tableMetadata()
|
||||
metadata.classFile = NKTypeClassFile.image.rawValue
|
||||
metadata.fileName = fileName
|
||||
metadata.fileNameView = fileName
|
||||
return metadata
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import NextcloudKit
|
||||
import Testing
|
||||
@testable import Nextcloud
|
||||
|
||||
@Suite("Photo library assets")
|
||||
struct NCPhotoLibraryAssetTests {
|
||||
@Test("A photo is complete after its component is uploaded")
|
||||
func photoUpload() async throws {
|
||||
let database = try makeDatabase()
|
||||
try await database.recordPhotoLibraryAssetUpload(
|
||||
account: "account",
|
||||
assetLocalIdentifier: "photo",
|
||||
classFile: NKTypeClassFile.image.rawValue,
|
||||
isLivePhoto: false,
|
||||
creationDate: Date()
|
||||
)
|
||||
|
||||
#expect(try await database.uploadedPhotoLibraryAssets(account: "account").map(\.assetLocalIdentifier) == ["photo"])
|
||||
}
|
||||
|
||||
@Test("A Live Photo requires both components")
|
||||
func livePhotoUpload() async throws {
|
||||
let database = try makeDatabase()
|
||||
try await database.recordPhotoLibraryAssetUpload(
|
||||
account: "account",
|
||||
assetLocalIdentifier: "live-photo",
|
||||
classFile: NKTypeClassFile.image.rawValue,
|
||||
isLivePhoto: true,
|
||||
creationDate: Date()
|
||||
)
|
||||
|
||||
#expect(try await database.uploadedPhotoLibraryAssets(account: "account").isEmpty)
|
||||
try await database.recordPhotoLibraryAssetUpload(
|
||||
account: "account",
|
||||
assetLocalIdentifier: "live-photo",
|
||||
classFile: NKTypeClassFile.video.rawValue,
|
||||
isLivePhoto: true,
|
||||
creationDate: Date()
|
||||
)
|
||||
#expect(try await database.uploadedPhotoLibraryAssets(account: "account").map(\.assetLocalIdentifier) == ["live-photo"])
|
||||
}
|
||||
|
||||
@Test("Repeated discovery and upload confirmation are idempotent")
|
||||
func repeatedUpdates() async throws {
|
||||
let database = try makeDatabase()
|
||||
let creationDate = Date()
|
||||
try await database.recordPhotoLibraryAssetUpload(
|
||||
account: "account",
|
||||
assetLocalIdentifier: "asset",
|
||||
classFile: NKTypeClassFile.image.rawValue,
|
||||
isLivePhoto: false,
|
||||
creationDate: creationDate
|
||||
)
|
||||
|
||||
try await database.recordPhotoLibraryAssetUpload(
|
||||
account: "account",
|
||||
assetLocalIdentifier: "asset",
|
||||
classFile: NKTypeClassFile.image.rawValue,
|
||||
isLivePhoto: false,
|
||||
creationDate: creationDate
|
||||
)
|
||||
#expect(try await database.uploadedPhotoLibraryAssets(account: "account").count == 1)
|
||||
}
|
||||
|
||||
@Test("Assets are isolated by account and removed after Photos cleanup")
|
||||
func accountIsolationAndRemoval() async throws {
|
||||
let database = try makeDatabase()
|
||||
for account in ["first", "second"] {
|
||||
try await database.recordPhotoLibraryAssetUpload(
|
||||
account: account,
|
||||
assetLocalIdentifier: "shared-identifier",
|
||||
classFile: NKTypeClassFile.video.rawValue,
|
||||
isLivePhoto: false,
|
||||
creationDate: Date()
|
||||
)
|
||||
}
|
||||
|
||||
try await database.removePhotoLibraryAssets(account: "first", assetLocalIdentifiers: ["shared-identifier"])
|
||||
#expect(try await database.uploadedPhotoLibraryAssets(account: "first").isEmpty)
|
||||
#expect(try await database.uploadedPhotoLibraryAssets(account: "second").map(\.assetLocalIdentifier) == ["shared-identifier"])
|
||||
}
|
||||
|
||||
@Test("Clearing the local database removes uploaded asset state")
|
||||
func clearDatabase() async throws {
|
||||
let database = try makeDatabase()
|
||||
try await database.recordPhotoLibraryAssetUpload(
|
||||
account: "account",
|
||||
assetLocalIdentifier: "photo",
|
||||
classFile: NKTypeClassFile.image.rawValue,
|
||||
isLivePhoto: false,
|
||||
creationDate: Date()
|
||||
)
|
||||
|
||||
try await database.clearDBCache()
|
||||
|
||||
#expect(try await database.uploadedPhotoLibraryAssets(account: "account").isEmpty)
|
||||
}
|
||||
|
||||
@Test("A Live Photo can complete when its video is uploaded first")
|
||||
func livePhotoVideoFirst() async throws {
|
||||
let database = try makeDatabase()
|
||||
try await database.recordPhotoLibraryAssetUpload(
|
||||
account: "account",
|
||||
assetLocalIdentifier: "live-photo",
|
||||
classFile: NKTypeClassFile.video.rawValue,
|
||||
isLivePhoto: true,
|
||||
creationDate: Date()
|
||||
)
|
||||
|
||||
#expect(try await database.uploadedPhotoLibraryAssets(account: "account").isEmpty)
|
||||
try await database.recordPhotoLibraryAssetUpload(
|
||||
account: "account",
|
||||
assetLocalIdentifier: "live-photo",
|
||||
classFile: NKTypeClassFile.image.rawValue,
|
||||
isLivePhoto: true,
|
||||
creationDate: Date()
|
||||
)
|
||||
#expect(try await database.uploadedPhotoLibraryAssets(account: "account").map(\.assetLocalIdentifier) == ["live-photo"])
|
||||
}
|
||||
|
||||
private func makeDatabase() throws -> NCLocalDatabase {
|
||||
let databaseURL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString)
|
||||
.appendingPathExtension("sqlite")
|
||||
return try NCLocalDatabase(databaseURL: databaseURL)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Testing
|
||||
@testable import Nextcloud
|
||||
|
||||
@Suite("Video playback presentation context")
|
||||
struct NCVideoPlaybackPresentationContextTests {
|
||||
@Test("User-initiated playback starts with visible controls")
|
||||
func userInitiatedPlaybackShowsControls() {
|
||||
var context = NCVideoPlaybackPresentationContext(
|
||||
startReason: .userInitiated
|
||||
)
|
||||
|
||||
context.prepareForPlaybackStart()
|
||||
|
||||
#expect(context.shouldShowControlsOnStart)
|
||||
#expect(context.playbackTransition == .idle)
|
||||
#expect(!context.shouldSuppressAutomaticControlsPresentation)
|
||||
}
|
||||
|
||||
@Test("Automatic advancement starts without presenting controls")
|
||||
func automaticAdvanceSuppressesControls() {
|
||||
var context = NCVideoPlaybackPresentationContext(
|
||||
startReason: .automaticAdvance
|
||||
)
|
||||
|
||||
context.prepareForPlaybackStart()
|
||||
|
||||
#expect(!context.shouldShowControlsOnStart)
|
||||
#expect(context.playbackTransition == .automaticStart)
|
||||
#expect(context.shouldSuppressAutomaticControlsPresentation)
|
||||
|
||||
context.finishPlaybackTransition()
|
||||
|
||||
#expect(context.playbackTransition == .idle)
|
||||
#expect(!context.shouldSuppressAutomaticControlsPresentation)
|
||||
#expect(context.shouldShowControlsOnStart)
|
||||
}
|
||||
|
||||
@Test("Repeat restart suppresses automatic control presentation")
|
||||
func repeatRestartSuppressesControls() {
|
||||
var context = NCVideoPlaybackPresentationContext(
|
||||
startReason: .userInitiated
|
||||
)
|
||||
|
||||
context.beginRepeatRestart()
|
||||
|
||||
#expect(context.playbackTransition == .repeatRestart)
|
||||
#expect(context.shouldSuppressAutomaticControlsPresentation)
|
||||
|
||||
context.finishPlaybackTransition()
|
||||
|
||||
#expect(context.playbackTransition == .idle)
|
||||
#expect(!context.shouldSuppressAutomaticControlsPresentation)
|
||||
}
|
||||
|
||||
@Test("Seeking is represented by the shared transition state")
|
||||
func seekingUsesSharedTransition() {
|
||||
var context = NCVideoPlaybackPresentationContext(
|
||||
startReason: .userInitiated
|
||||
)
|
||||
|
||||
context.beginSeeking()
|
||||
|
||||
#expect(context.interaction == .seeking)
|
||||
#expect(context.isSeeking)
|
||||
#expect(context.shouldSuppressAutomaticControlsPresentation)
|
||||
|
||||
context.finishSeeking()
|
||||
|
||||
#expect(!context.isSeeking)
|
||||
}
|
||||
|
||||
@Test("Playback callbacks preserve seeking and complete automatic start")
|
||||
func playbackCallbackPreservesSeekingAndCompletesAutomaticStart() {
|
||||
var context = NCVideoPlaybackPresentationContext(
|
||||
startReason: .automaticAdvance
|
||||
)
|
||||
|
||||
context.prepareForPlaybackStart()
|
||||
context.beginSeeking()
|
||||
context.finishPlaybackTransition()
|
||||
|
||||
#expect(context.isSeeking)
|
||||
#expect(context.playbackTransition == .idle)
|
||||
#expect(context.shouldShowControlsOnStart)
|
||||
#expect(context.shouldSuppressAutomaticControlsPresentation)
|
||||
|
||||
context.finishSeeking()
|
||||
|
||||
#expect(!context.shouldSuppressAutomaticControlsPresentation)
|
||||
}
|
||||
|
||||
@Test("Reset clears playback and interaction transitions")
|
||||
func resetClearsAllTransitions() {
|
||||
var context = NCVideoPlaybackPresentationContext(
|
||||
startReason: .automaticAdvance
|
||||
)
|
||||
|
||||
context.prepareForPlaybackStart()
|
||||
context.beginSeeking()
|
||||
context.reset()
|
||||
|
||||
#expect(context.playbackTransition == .idle)
|
||||
#expect(context.interaction == .idle)
|
||||
#expect(!context.shouldSuppressAutomaticControlsPresentation)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2026 Milen Pivchev
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import NextcloudKit
|
||||
import Testing
|
||||
@testable import Nextcloud
|
||||
|
||||
@Suite("Error messages shown to people")
|
||||
struct NKErrorUserFriendlyMessageTests {
|
||||
static let shownKinds = NKError.Kind.allCases.filter { $0 != .cancelled }
|
||||
|
||||
private func localized(_ key: String) -> String {
|
||||
NSLocalizedString(key, comment: "")
|
||||
}
|
||||
|
||||
@Test("Nothing is shown for success or cancellation")
|
||||
func silentErrors() {
|
||||
#expect(NKError.success.userFriendlyMessage() == nil)
|
||||
#expect(NKError.cancelled.userFriendlyMessage(for: .upload(fileName: "a.jpg")) == nil)
|
||||
#expect(NKError(errorCode: NCGlobal.shared.errorTaskCancelled, errorDescription: "Task cancelled").userFriendlyMessage() == nil)
|
||||
}
|
||||
|
||||
@Test("Keeps text the app wrote itself")
|
||||
func appMessages() {
|
||||
#expect(NKError(errorCode: NCGlobal.shared.errorOfflineNotAllowed, errorDescription: "_offline_not_allowed_").userFriendlyMessage() == localized("_offline_not_allowed_"))
|
||||
#expect(NKError(errorCode: NCGlobal.shared.errorE2EELock, errorDescription: "Already translated").userFriendlyMessage() == "Already translated")
|
||||
}
|
||||
|
||||
@Test("Replaces technical server text")
|
||||
func technicalServerText() throws {
|
||||
let error = NKError(errorCode: 409, errorDescription: "Parent node does not exist")
|
||||
let generic = try #require(error.userFriendlyMessage())
|
||||
|
||||
#expect(error.userFriendlyMessage(for: .createFolder(folderName: "a/b")) == generic)
|
||||
#expect(generic != error.errorDescription)
|
||||
#expect(!generic.contains("409"))
|
||||
}
|
||||
|
||||
@Test("Uses the generic message unless the operation needs its own")
|
||||
func operationMessages() {
|
||||
let forbidden = NKError(errorCode: 403, errorDescription: "403: Forbidden")
|
||||
let generic = forbidden.userFriendlyMessage()
|
||||
|
||||
#expect(generic != nil)
|
||||
#expect(forbidden.userFriendlyMessage(for: .delete(fileName: "a.jpg")) == generic)
|
||||
#expect(forbidden.userFriendlyMessage(for: .rename) == generic)
|
||||
#expect(forbidden.userFriendlyMessage(for: .upload(fileName: "a.jpg")) == generic)
|
||||
}
|
||||
|
||||
@Test("Doesn't guess the cause of a document failure")
|
||||
func documentMessages() {
|
||||
let forbidden = NKError(errorCode: 403, errorDescription: "403: Forbidden")
|
||||
let notFound = NKError(errorCode: 404, errorDescription: "404: Not found")
|
||||
|
||||
#expect(forbidden.userFriendlyMessage(for: .createDocument(fileName: "a.md")) == localized("_error_occurred_"))
|
||||
#expect(forbidden.userFriendlyMessage(for: .openDocument(fileName: "a.md")) == localized("_error_occurred_"))
|
||||
#expect(notFound.userFriendlyMessage(for: .openDocument(fileName: "a.md")) == notFound.userFriendlyMessage())
|
||||
#expect(NKError(error: CancellationError()).userFriendlyMessage() == nil)
|
||||
}
|
||||
|
||||
@Test("Words different kinds of failure differently")
|
||||
func kindMessages() {
|
||||
let timeout = NKError(errorCode: NSURLErrorTimedOut, errorDescription: "The request timed out.").userFriendlyMessage()
|
||||
let quota = NKError(errorCode: 507, errorDescription: "507: Storage quota is reached").userFriendlyMessage()
|
||||
let unknown = NKError(errorCode: 418, errorDescription: "418: I'm a teapot").userFriendlyMessage()
|
||||
|
||||
#expect(Set([timeout, quota, unknown]).count == 3)
|
||||
#expect(quota != "507: Storage quota is reached")
|
||||
}
|
||||
|
||||
@Test("Every kind has a translated message", arguments: NKErrorUserFriendlyMessageTests.shownKinds)
|
||||
func everyKind(kind: NKError.Kind) {
|
||||
let message = NKError(errorCode: -1, errorDescription: "Technical", kind: kind).userFriendlyMessage()
|
||||
|
||||
#expect(message != nil)
|
||||
#expect(message != "Technical")
|
||||
}
|
||||
|
||||
@Test("Maps transfer events and saved statuses to operations")
|
||||
func contexts() {
|
||||
let global = NCGlobal.shared
|
||||
|
||||
#expect(NCErrorContext(networkingStatus: global.networkingStatusUploaded, fileName: "a.jpg") == .upload(fileName: "a.jpg"))
|
||||
#expect(NCErrorContext(networkingStatus: global.networkingStatusCopyMove, fileName: "a.jpg") == .moveOrCopy(fileName: "a.jpg"))
|
||||
#expect(NCErrorContext(networkingStatus: global.networkingStatusReloadAvatar, fileName: "") == .generic)
|
||||
#expect(NCErrorContext(metadataStatus: global.metadataStatusWaitCreateFolder, fileName: "Photos") == .createFolder(folderName: "Photos"))
|
||||
#expect(NCErrorContext(metadataStatus: global.metadataStatusDownloadError, fileName: "a.jpg") == .download(fileName: "a.jpg"))
|
||||
}
|
||||
|
||||
@Test("Titles say what failed")
|
||||
func failureTitles() throws {
|
||||
let contexts: [NCErrorContext] = [.upload(fileName: "f"), .download(fileName: "f"), .delete(fileName: "f"), .rename, .moveOrCopy(fileName: "f"), .createFolder(folderName: "f"), .favorite(fileName: "f"), .createDocument(fileName: "f"), .openDocument(fileName: "f")]
|
||||
|
||||
#expect(NCErrorContext.generic.failureTitle == nil)
|
||||
#expect(NCErrorContext.upload(fileName: "IMG_0042.jpg").failureTitle?.contains("IMG_0042.jpg") == true)
|
||||
|
||||
for context in contexts {
|
||||
let title = try #require(context.failureTitle)
|
||||
|
||||
#expect(!title.hasPrefix("_"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Words saved transfer errors")
|
||||
func savedErrors() {
|
||||
let metadata = tableMetadata()
|
||||
metadata.fileNameView = "a.jpg"
|
||||
metadata.status = NCGlobal.shared.metadataStatusUploadError
|
||||
metadata.errorCode = 507
|
||||
metadata.sessionError = "507: Storage quota is reached"
|
||||
|
||||
#expect(metadata.sessionErrorMessage == NKError(errorCode: 507, errorDescription: "").userFriendlyMessage())
|
||||
|
||||
metadata.errorCode = 412
|
||||
metadata.errorKind = NKError.Kind.alreadyExists.rawValue
|
||||
|
||||
#expect(metadata.sessionErrorMessage == NKError(errorCode: 412, errorDescription: "", kind: .alreadyExists).userFriendlyMessage())
|
||||
|
||||
metadata.errorKind = "notAKind"
|
||||
|
||||
#expect(metadata.sessionErrorMessage == NKError(errorCode: 412, errorDescription: "").userFriendlyMessage())
|
||||
|
||||
metadata.errorCode = NSURLErrorCancelled
|
||||
metadata.sessionError = "Transfer was cancelled."
|
||||
|
||||
#expect(metadata.sessionErrorMessage != "Transfer was cancelled.")
|
||||
#expect(!metadata.sessionErrorMessage.isEmpty)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2025 Iva Horn
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// There are no unit tests yet.
|
||||
// This is an empty placeholder file.
|
||||
// The compiler requires at least an empty file for every target.
|
||||
@@ -1,5 +1,8 @@
|
||||
#!/usr/bin/env zsh
|
||||
|
||||
# SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
# The fixed Docker container name for the Nextcloud server.
|
||||
CONTAINER_NAME="xcode-test-server"
|
||||
|
||||
@@ -22,6 +25,9 @@ docker run \
|
||||
echo "Please wait until the server is provisioned…"
|
||||
sleep 20
|
||||
|
||||
# Keep web authentication labels consistent with the UI tests.
|
||||
docker exec --user www-data $CONTAINER_NAME php /var/www/html/occ config:system:set force_language --value=en
|
||||
|
||||
# Enable File Download Limit App.
|
||||
docker exec $CONTAINER_NAME su www-data -c "git clone --depth 1 -b $SERVER_VERSION https://github.com/nextcloud/files_downloadlimit.git /var/www/html/apps/files_downloadlimit/"
|
||||
docker exec $CONTAINER_NAME su www-data -c "php /var/www/html/occ app:enable files_downloadlimit"
|
||||
|
||||
|
Before Width: | Height: | Size: 3.6 KiB |
@@ -99,7 +99,12 @@ func getDashboardDataEntry(configuration: DashboardIntent?, isPreview: Bool, dis
|
||||
|
||||
// LOG
|
||||
let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, utility.getVersionBuild())
|
||||
NextcloudKit.configureLogger(logLevel: (NCBrandOptions.shared.disable_log ? .disabled : NCPreferences().log))
|
||||
NextcloudKit.configureLogger(
|
||||
logLevel: NCBrandOptions.shared.disable_log ? .disabled : NCPreferences().log,
|
||||
logDirectory: NCPreferences.sharedLogDirectory
|
||||
)
|
||||
defer { NextcloudKit.flushLogger() }
|
||||
|
||||
nkLog(debug: "Start \(NCBrandOptions.shared.brand) dashboard widget session " + versionNextcloudiOS)
|
||||
|
||||
// Widget
|
||||
@@ -200,7 +205,7 @@ func getDashboardDataEntry(configuration: DashboardIntent?, isPreview: Bool, dis
|
||||
let footerText = "Dashboard " + NSLocalizedString("_of_", comment: "") + " " + activeTableAccount.displayName + alias
|
||||
|
||||
if resultsDashboardWidget.error != .success {
|
||||
return(DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: tableDashboard, buttons: buttons, isPlaceholder: true, isEmpty: false, titleImage: titleImage, title: title, footerImage: "xmark.icloud", footerText: resultsDashboardWidget.error.errorDescription, account: activeTableAccount.account))
|
||||
return(DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: tableDashboard, buttons: buttons, isPlaceholder: true, isEmpty: false, titleImage: titleImage, title: title, footerImage: "xmark.icloud", footerText: resultsDashboardWidget.error.localizedGenericMessage, account: activeTableAccount.account))
|
||||
} else {
|
||||
return(DashboardDataEntry(date: Date(), datas: datas, dashboard: tableDashboard, buttons: buttons, isPlaceholder: false, isEmpty: datas.isEmpty, titleImage: titleImage, title: title, footerImage: "checkmark.icloud", footerText: footerText, account: activeTableAccount.account))
|
||||
}
|
||||
|
||||
@@ -162,7 +162,12 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi
|
||||
|
||||
// LOG
|
||||
let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, utility.getVersionBuild())
|
||||
NextcloudKit.configureLogger(logLevel: (NCBrandOptions.shared.disable_log ? .disabled : NCPreferences().log))
|
||||
NextcloudKit.configureLogger(
|
||||
logLevel: NCBrandOptions.shared.disable_log ? .disabled : NCPreferences().log,
|
||||
logDirectory: NCPreferences.sharedLogDirectory
|
||||
)
|
||||
defer { NextcloudKit.flushLogger() }
|
||||
|
||||
nkLog(debug: "Start \(NCBrandOptions.shared.brand) widget session " + versionNextcloudiOS)
|
||||
|
||||
let options = NKRequestOptions(timeout: 30, queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
|
||||
@@ -233,7 +238,7 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi
|
||||
let footerText = "Files " + NSLocalizedString("_of_", comment: "") + " " + activeTableAccount.displayName + alias
|
||||
|
||||
if results.error != .success {
|
||||
return(FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, userId: activeTableAccount.userId, url: activeTableAccount.urlBase, account: activeTableAccount.account, tile: title, footerImage: "xmark.icloud", footerText: results.error.errorDescription))
|
||||
return(FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, userId: activeTableAccount.userId, url: activeTableAccount.urlBase, account: activeTableAccount.account, tile: title, footerImage: "xmark.icloud", footerText: results.error.localizedGenericMessage))
|
||||
} else {
|
||||
return(FilesDataEntry(date: Date(), datas: datas, isPlaceholder: false, isEmpty: datas.isEmpty, userId: activeTableAccount.userId, url: activeTableAccount.urlBase, account: activeTableAccount.account, tile: title, footerImage: "checkmark.icloud", footerText: footerText))
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@ struct FilesWidgetView: View {
|
||||
.frame(maxWidth: .infinity)
|
||||
|
||||
Link(destination: entry.isPlaceholder ? linkNoAction : linkActionVoiceMemo) {
|
||||
Image("microphone")
|
||||
Image(systemName: "mic.fill")
|
||||
.resizable()
|
||||
.renderingMode(.template)
|
||||
.scaledToFit()
|
||||
|
||||
@@ -67,13 +67,15 @@ struct ToolbarWidgetView: View {
|
||||
})
|
||||
|
||||
Link(destination: entry.isPlaceholder ? linkNoAction : linkActionVoiceMemo, label: {
|
||||
Image("microphone")
|
||||
Image(systemName: "mic.fill")
|
||||
.resizable()
|
||||
.renderingMode(.template)
|
||||
.scaledToFit()
|
||||
.foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account)))
|
||||
.padding()
|
||||
.frame(width: sizeButton - 32, height: sizeButton - 32)
|
||||
.padding(16)
|
||||
.background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account)))
|
||||
.clipShape(Circle())
|
||||
.scaledToFit()
|
||||
.frame(width: geo.size.width / 4, height: sizeButton)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2016 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
// Use this file to import your target's public headers that you would like to expose to Swift.
|
||||
//
|
||||
// Use this file to import your target's public headers that you would like to expose to Swift.
|
||||
|
||||
#import "UIImage+animatedGIF.h"
|
||||
@@ -1,25 +1,6 @@
|
||||
//
|
||||
// IntentHandler.swift
|
||||
// WidgetDashboardIntentHandler
|
||||
//
|
||||
// Created by Marino Faggiana on 08/10/22.
|
||||
// Copyright © 2022 Marino Faggiana. All rights reserved.
|
||||
//
|
||||
// Author Marino Faggiana <marino.faggiana@nextcloud.com>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
//
|
||||
// SPDX-FileCopyrightText: Nextcloud GmbH
|
||||
// SPDX-FileCopyrightText: 2022 Marino Faggiana
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Intents
|
||||
import RealmSwift
|
||||
|
||||
@@ -36,7 +36,8 @@ struct NCAccountSettingsView: View {
|
||||
Image(uiImage: avatar)
|
||||
.resizable()
|
||||
.scaledToFit()
|
||||
.frame(width: UIScreen.main.bounds.width, height: 65)
|
||||
.frame(height: 65)
|
||||
.frame(maxWidth: .infinity)
|
||||
if let statusImage = status.statusImage {
|
||||
ZStack {
|
||||
Circle()
|
||||
@@ -137,7 +138,7 @@ struct NCAccountSettingsView: View {
|
||||
if let account = model.tblAccount?.account {
|
||||
NavigationLink(destination: NCUserStatusView(account: account, controller: model.controller)) {
|
||||
HStack {
|
||||
Image(systemName: "moon.fill")
|
||||
Image(systemName: "moon")
|
||||
.font(.icon())
|
||||
.foregroundStyle(Color(NCBrandColor.shared.iconImageColor))
|
||||
.frame(width: 26)
|
||||
@@ -151,7 +152,7 @@ struct NCAccountSettingsView: View {
|
||||
if let account = model.tblAccount?.account {
|
||||
NavigationLink(destination: NCStatusMessageView(account: account, controller: model.controller)) {
|
||||
HStack {
|
||||
Image(systemName: "message.fill")
|
||||
Image(systemName: "message")
|
||||
.font(.icon())
|
||||
.foregroundStyle(Color(NCBrandColor.shared.iconImageColor))
|
||||
.frame(width: 26)
|
||||
|
||||
@@ -8,6 +8,7 @@ import NextcloudKit
|
||||
|
||||
@MainActor
|
||||
class NCAccount: NSObject {
|
||||
private static var accountsCheckingRemoteUser: Set<String> = []
|
||||
let database = NCManageDatabase.shared
|
||||
let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
|
||||
let global = NCGlobal.shared
|
||||
@@ -33,16 +34,16 @@ class NCAccount: NSObject {
|
||||
httpMaximumConnectionsPerHostInDownload: NCBrandOptions.shared.httpMaximumConnectionsPerHostInDownload,
|
||||
httpMaximumConnectionsPerHostInUpload: NCBrandOptions.shared.httpMaximumConnectionsPerHostInUpload,
|
||||
groupIdentifier: NCBrandOptions.shared.capabilitiesGroup)
|
||||
let resultsGetUserProfile = await NextcloudKit.shared.getUserProfileAsync(account: account) { task in
|
||||
Task {
|
||||
let identifier = await NCNetworking.shared.networkingTasks.createIdentifier(account: account,
|
||||
name: "getUserProfile")
|
||||
await NCNetworking.shared.networkingTasks.track(identifier: identifier, task: task)
|
||||
}
|
||||
}
|
||||
let resultsGetUserProfile = await NextcloudKit.shared.getUserProfileAsync(account: account)
|
||||
|
||||
guard resultsGetUserProfile.error == .success, let userProfile = resultsGetUserProfile.userProfile else {
|
||||
NextcloudKit.shared.nkCommonInstance.nksessions.remove(account: account)
|
||||
let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: resultsGetUserProfile.error.errorDescription, preferredStyle: .alert)
|
||||
|
||||
let error = resultsGetUserProfile.error == .success ? NKError.invalidData : resultsGetUserProfile.error
|
||||
|
||||
nkLog(error: "Getting the user profile failed: \(error.logDescription)")
|
||||
|
||||
let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: error.userFriendlyMessage() ?? error.localizedGenericMessage, preferredStyle: .alert)
|
||||
alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
|
||||
viewController.present(alertController, animated: true)
|
||||
|
||||
@@ -89,20 +90,10 @@ class NCAccount: NSObject {
|
||||
|
||||
func changeAccount(_ account: String, userProfile: NKUserProfile?, controller: NCMainTabBarController?) async {
|
||||
if let tblAccount = await database.setAccountActiveAsync(account) {
|
||||
// Set account
|
||||
controller?.account = account
|
||||
// Set User Profile
|
||||
if let userProfile {
|
||||
await database.setAccountUserProfileAsync(account: account, userProfile: userProfile)
|
||||
}
|
||||
// Networking Certificate
|
||||
NCNetworking.shared.activeAccountCertificate(account: account)
|
||||
// Subscribing Push Notification
|
||||
await NCPushNotification.shared.subscribingNextcloudServerPushNotification(account: tblAccount.account, urlBase: tblAccount.urlBase)
|
||||
// Start the service
|
||||
Task(priority: .utility) {
|
||||
await NCService().startRequestServicesServer(account: account, controller: controller)
|
||||
}
|
||||
// Capabilities
|
||||
if let capabilities = await self.database.getCapabilities(account: account) {
|
||||
// set theming color
|
||||
@@ -111,13 +102,24 @@ class NCAccount: NSObject {
|
||||
// Networking Process
|
||||
await NCNetworkingProcess.shared.setCurrentAccount(account)
|
||||
|
||||
// Update the account and the file context together, before starting network requests.
|
||||
controller?.account = account
|
||||
NCNetworking.shared.activeAccountCertificate(account: account)
|
||||
|
||||
// Color
|
||||
NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterChangeTheming, userInfo: ["account": account])
|
||||
// Notification
|
||||
if let controller {
|
||||
NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterChangeUser, userInfo: ["account": account, "controller": controller])
|
||||
NotificationCenter.default.post(name: Notification.Name(self.global.notificationCenterChangeUser), object: nil, userInfo: ["account": account, "controller": controller])
|
||||
} else {
|
||||
NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterChangeUser, userInfo: ["account": account])
|
||||
NotificationCenter.default.post(name: Notification.Name(self.global.notificationCenterChangeUser), object: nil, userInfo: ["account": account])
|
||||
}
|
||||
|
||||
// Subscribing Push Notification
|
||||
await NCPushNotification.shared.subscribingNextcloudServerPushNotification(account: tblAccount.account, urlBase: tblAccount.urlBase)
|
||||
// Start the service
|
||||
Task(priority: .utility) {
|
||||
await NCService().startRequestServicesServer(account: account, controller: controller)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -145,11 +147,21 @@ class NCAccount: NSObject {
|
||||
}
|
||||
// Remove account in all database
|
||||
database.clearDatabase(account: account)
|
||||
do {
|
||||
try await NCLocalDatabase.shared.clearDatabase(account: account)
|
||||
} catch {
|
||||
nkLog(error: "Unable to clear GRDB data for account \(account): \(error)")
|
||||
}
|
||||
} else {
|
||||
// Remove account
|
||||
await database.clearTableAsync(tableAccount.self, account: account)
|
||||
// Remove autoupload
|
||||
await database.clearTableAsync(tableAutoUploadTransfer.self, account: account)
|
||||
do {
|
||||
try await NCLocalDatabase.shared.removeAutoUploadResources(account: account)
|
||||
} catch {
|
||||
nkLog(error: "Unable to remove background upload history for account \(account): \(error)")
|
||||
}
|
||||
}
|
||||
// Remove session in NextcloudKit
|
||||
NextcloudKit.shared.nkCommonInstance.nksessions.remove(account: account)
|
||||
@@ -189,40 +201,72 @@ class NCAccount: NSObject {
|
||||
}
|
||||
|
||||
func checkRemoteUser(account: String, controller: NCMainTabBarController?) async {
|
||||
guard Self.accountsCheckingRemoteUser.insert(account).inserted else {
|
||||
return
|
||||
}
|
||||
defer { Self.accountsCheckingRemoteUser.remove(account) }
|
||||
|
||||
let token = NCPreferences().getPassword(account: account)
|
||||
guard let tblAccount = await NCManageDatabase.shared.getTableAccountAsync(predicate: NSPredicate(format: "account == %@", account)) else {
|
||||
return
|
||||
}
|
||||
let windowScene = SceneManager.shared.getWindowScene(controller: controller)
|
||||
await showErrorBanner(windowScene: windowScene, text: String(format: NSLocalizedString("_account_unauthorized_", comment: ""), account), errorCode: NCGlobal.shared.errorUnauthorized401)
|
||||
|
||||
let resultsWipe = await NextcloudKit.shared.getRemoteWipeStatusAsync(serverUrl: tblAccount.urlBase, token: token, account: account) { task in
|
||||
Task {
|
||||
let identifier = await NCNetworking.shared.networkingTasks.createIdentifier(account: account,
|
||||
path: tblAccount.urlBase,
|
||||
name: "getRemoteWipeStatus")
|
||||
await NCNetworking.shared.networkingTasks.track(identifier: identifier, task: task)
|
||||
}
|
||||
guard let session = NextcloudKit.shared.nkCommonInstance.nksessions.session(forAccount: account),
|
||||
session.password == token else {
|
||||
return
|
||||
}
|
||||
|
||||
// A stored 401 may belong to an inconsistent or outdated request. Verify with the server.
|
||||
let result = await NextcloudKit.shared.getUserProfileAsync(account: account, options: NKRequestOptions(checkInterceptor: false))
|
||||
guard !Task.isCancelled,
|
||||
remoteUserCredentialsMatch(session, token: token) else {
|
||||
return
|
||||
}
|
||||
if result.error == .success, result.userProfile?.userId == session.userId {
|
||||
NCNetworking.shared.removeUnauthorizedAccount(account)
|
||||
return
|
||||
}
|
||||
guard result.responseData?.response?.statusCode == NCGlobal.shared.errorUnauthorized else {
|
||||
// Network failures and other responses do not confirm invalid credentials.
|
||||
return
|
||||
}
|
||||
|
||||
let windowScene = SceneManager.shared.getWindowScene(controller: controller)
|
||||
await showErrorBanner(windowScene: windowScene, text: String(format: NSLocalizedString("_account_unauthorized_", comment: ""), account), errorCode: NCGlobal.shared.errorUnauthorized)
|
||||
|
||||
let resultsWipe = await NextcloudKit.shared.getRemoteWipeStatusAsync(serverUrl: tblAccount.urlBase, token: token, account: account)
|
||||
|
||||
// REMOVE ACCOUNT
|
||||
guard !Task.isCancelled,
|
||||
remoteUserCredentialsMatch(session, token: token) else {
|
||||
return
|
||||
}
|
||||
await NCAccount().deleteAccount(account, wipe: resultsWipe.wipe)
|
||||
if resultsWipe.wipe {
|
||||
let resultsSetWipe = await NextcloudKit.shared.setRemoteWipeCompletitionAsync(serverUrl: tblAccount.urlBase, token: token, account: tblAccount.account) { task in
|
||||
Task {
|
||||
let identifier = await NCNetworking.shared.networkingTasks.createIdentifier(account: tblAccount.account,
|
||||
path: tblAccount.urlBase,
|
||||
name: "setRemoteWipeCompletition")
|
||||
await NCNetworking.shared.networkingTasks.track(identifier: identifier, task: task)
|
||||
}
|
||||
}
|
||||
nkLog(debug: "Set Remote Wipe Completition error code: \(resultsSetWipe.error.errorCode)")
|
||||
let resultsSetWipe = await NextcloudKit.shared.setRemoteWipeCompletitionAsync(serverUrl: tblAccount.urlBase, token: token, account: tblAccount.account)
|
||||
nkLog(debug: "Set Remote Wipe Completition result: \(resultsSetWipe.error.logDescription)")
|
||||
}
|
||||
|
||||
if !account.isEmpty, controller == nil || controller?.account == account {
|
||||
await switchToFirstAvailableAccount(controller: controller)
|
||||
}
|
||||
}
|
||||
|
||||
private func remoteUserCredentialsMatch(_ session: NKSession, token: String) -> Bool {
|
||||
guard let currentSession = NextcloudKit.shared.nkCommonInstance.nksessions.session(forAccount: session.account) else {
|
||||
return false
|
||||
}
|
||||
return currentSession.urlBase == session.urlBase
|
||||
&& currentSession.user == session.user
|
||||
&& currentSession.userId == session.userId
|
||||
&& currentSession.password == session.password
|
||||
&& NCPreferences().getPassword(account: session.account) == token
|
||||
}
|
||||
|
||||
/// Presents the login (or intro) screen if no account remains.
|
||||
func switchToFirstAvailableAccount(controller: NCMainTabBarController?) async {
|
||||
let accounts = await NCManageDatabase.shared.getAccountsAsync()
|
||||
|
||||
if let accounts,
|
||||
account.count > 0,
|
||||
let account = accounts.first {
|
||||
await changeAccount(account, userProfile: nil, controller: controller)
|
||||
} else {
|
||||
|
||||
@@ -41,12 +41,7 @@ import NextcloudKit
|
||||
|
||||
func getStatus(account: String) {
|
||||
Task {
|
||||
let result = await NextcloudKit.shared.getUserStatusAsync(account: account) { task in
|
||||
Task {
|
||||
let identifier = await NCNetworking.shared.networkingTasks.createIdentifier(account: account, name: "getUserStatus")
|
||||
await NCNetworking.shared.networkingTasks.track(identifier: identifier, task: task)
|
||||
}
|
||||
}
|
||||
let result = await NextcloudKit.shared.getUserStatusAsync(account: account)
|
||||
|
||||
if result.error == .success {
|
||||
emojiText = result.icon ?? "😀"
|
||||
@@ -58,12 +53,7 @@ import NextcloudKit
|
||||
|
||||
func clearStatus(account: String) {
|
||||
Task {
|
||||
let result = await NextcloudKit.shared.clearMessageAsync(account: account) { task in
|
||||
Task {
|
||||
let identifier = await NCNetworking.shared.networkingTasks.createIdentifier(account: account, name: "clearMessage")
|
||||
await NCNetworking.shared.networkingTasks.track(identifier: identifier, task: task)
|
||||
}
|
||||
}
|
||||
let result = await NextcloudKit.shared.clearMessageAsync(account: account)
|
||||
|
||||
if result.error != .success {
|
||||
await showErrorBanner(windowScene: self.windowScene, error: result.error)
|
||||
@@ -73,12 +63,7 @@ import NextcloudKit
|
||||
|
||||
func getPredefinedStatusTexts(account: String) {
|
||||
Task {
|
||||
let result = await NextcloudKit.shared.getUserStatusPredefinedStatusesAsync(account: account) { task in
|
||||
Task {
|
||||
let identifier = await NCNetworking.shared.networkingTasks.createIdentifier(account: account, name: "getUserStatusPredefinedStatuses")
|
||||
await NCNetworking.shared.networkingTasks.track(identifier: identifier, task: task)
|
||||
}
|
||||
}
|
||||
let result = await NextcloudKit.shared.getUserStatusPredefinedStatusesAsync(account: account)
|
||||
|
||||
if result.error == .success {
|
||||
predefinedStatuses = isXcodeRunningForPreviews ? createStatusesForPreview() : result.userStatuses ?? []
|
||||
@@ -90,12 +75,7 @@ import NextcloudKit
|
||||
|
||||
func submitStatus(account: String) {
|
||||
Task {
|
||||
let result = await NextcloudKit.shared.setCustomMessageUserDefinedAsync(statusIcon: emojiText, message: statusText, clearAt: getClearAt(clearAfterString), account: account) { task in
|
||||
Task {
|
||||
let identifier = await NCNetworking.shared.networkingTasks.createIdentifier(account: account, name: "setCustomMessageUserDefined")
|
||||
await NCNetworking.shared.networkingTasks.track(identifier: identifier, task: task)
|
||||
}
|
||||
}
|
||||
let result = await NextcloudKit.shared.setCustomMessageUserDefinedAsync(statusIcon: emojiText, message: statusText, clearAt: getClearAt(clearAfterString), account: account)
|
||||
|
||||
if result.error != .success {
|
||||
await showErrorBanner(windowScene: self.windowScene, error: result.error)
|
||||
@@ -105,13 +85,7 @@ import NextcloudKit
|
||||
|
||||
func setAccountUserStatus(account: String) {
|
||||
Task {
|
||||
let result = await NextcloudKit.shared.getUserStatusAsync(account: account) { task in
|
||||
Task {
|
||||
let identifier = await NCNetworking.shared.networkingTasks.createIdentifier(account: account,
|
||||
name: "getUserStatus")
|
||||
await NCNetworking.shared.networkingTasks.track(identifier: identifier, task: task)
|
||||
}
|
||||
}
|
||||
let result = await NextcloudKit.shared.getUserStatusAsync(account: account)
|
||||
|
||||
if result.error == .success {
|
||||
await NCManageDatabase.shared.setAccountUserStatusAsync(userStatusClearAt: result.clearAt,
|
||||
|
||||
@@ -43,12 +43,7 @@ import NextcloudKit
|
||||
|
||||
func getStatus(account: String) {
|
||||
Task {
|
||||
let result = await NextcloudKit.shared.getUserStatusAsync(account: account) { task in
|
||||
Task {
|
||||
let identifier = await NCNetworking.shared.networkingTasks.createIdentifier(account: self.account, name: "getUserStatus")
|
||||
await NCNetworking.shared.networkingTasks.track(identifier: identifier, task: task)
|
||||
}
|
||||
}
|
||||
let result = await NextcloudKit.shared.getUserStatusAsync(account: account)
|
||||
|
||||
if result.error == .success {
|
||||
selectedStatus = result.status
|
||||
@@ -60,10 +55,8 @@ import NextcloudKit
|
||||
|
||||
func setStatus(account: String) {
|
||||
Task {
|
||||
let result = await NextcloudKit.shared.setUserStatusAsync(status: selectedStatus ?? "", account: account) { task in
|
||||
Task {
|
||||
let identifier = await NCNetworking.shared.networkingTasks.createIdentifier(account: self.account, name: "setUserStatus")
|
||||
await NCNetworking.shared.networkingTasks.track(identifier: identifier, task: task)
|
||||
let result = await NextcloudKit.shared.setUserStatusAsync(status: selectedStatus ?? "", account: account) { _ in
|
||||
Task { @MainActor in
|
||||
self.canDismiss = true
|
||||
}
|
||||
}
|
||||
@@ -76,12 +69,7 @@ import NextcloudKit
|
||||
|
||||
func setAccountUserStatus(account: String) {
|
||||
Task {
|
||||
let result = await NextcloudKit.shared.getUserStatusAsync(account: account) { task in
|
||||
Task {
|
||||
let identifier = await NCNetworking.shared.networkingTasks.createIdentifier(account: self.account, name: "getUserStatus")
|
||||
await NCNetworking.shared.networkingTasks.track(identifier: identifier, task: task)
|
||||
}
|
||||
}
|
||||
let result = await NextcloudKit.shared.getUserStatusAsync(account: account)
|
||||
|
||||
if result.error != .success {
|
||||
await showErrorBanner(windowScene: windowScene, error: result.error)
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<subviews>
|
||||
<tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="20" sectionFooterHeight="1" translatesAutoresizingMaskIntoConstraints="NO" id="X49-xg-JXO">
|
||||
<rect key="frame" x="0.0" y="48" width="414" height="848"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
|
||||
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<prototypes>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" reuseIdentifier="tableCell" rowHeight="50" id="ggj-aE-fnh" customClass="NCActivityTableViewCell" customModule="Nextcloud" customModuleProvider="target">
|
||||
@@ -59,6 +59,7 @@
|
||||
<constraint firstItem="fcO-YL-MuT" firstAttribute="top" secondItem="i35-U4-bEk" secondAttribute="top" constant="3" id="faC-by-km5"/>
|
||||
</constraints>
|
||||
</tableViewCellContentView>
|
||||
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<connections>
|
||||
<outlet property="avatar" destination="LQ8-cO-794" id="2PE-uD-pug"/>
|
||||
<outlet property="icon" destination="xNG-sf-PnA" id="hxb-Vr-oQX"/>
|
||||
@@ -78,7 +79,7 @@
|
||||
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<constraints>
|
||||
<constraint firstItem="X49-xg-JXO" firstAttribute="trailing" secondItem="USa-eR-a1s" secondAttribute="trailing" id="5we-Fh-GVu"/>
|
||||
<constraint firstItem="X49-xg-JXO" firstAttribute="top" secondItem="USa-eR-a1s" secondAttribute="top" id="E1U-4Q-6uu"/>
|
||||
<constraint firstItem="X49-xg-JXO" firstAttribute="top" secondItem="vOO-VC-ekK" secondAttribute="top" id="E1U-4Q-6uu"/>
|
||||
<constraint firstAttribute="bottom" secondItem="X49-xg-JXO" secondAttribute="bottom" id="aHq-g4-dUG"/>
|
||||
<constraint firstItem="X49-xg-JXO" firstAttribute="leading" secondItem="USa-eR-a1s" secondAttribute="leading" id="pfF-ag-f7x"/>
|
||||
</constraints>
|
||||
|
||||
@@ -15,6 +15,8 @@ class NCActivity: UIViewController, NCSharePagingContent {
|
||||
var height: CGFloat = 0
|
||||
var metadata: tableMetadata?
|
||||
var showComments: Bool = false
|
||||
var usesGroupedBackground: Bool = false
|
||||
private var activityTasks: [URLSessionTask] = []
|
||||
|
||||
let utilityFileSystem = NCUtilityFileSystem()
|
||||
let utility = NCUtility()
|
||||
@@ -55,13 +57,14 @@ class NCActivity: UIViewController, NCSharePagingContent {
|
||||
super.viewDidLoad()
|
||||
|
||||
navigationController?.setNavigationBarAppearance()
|
||||
view.backgroundColor = .systemBackground
|
||||
view.backgroundColor = usesGroupedBackground ? .systemGroupedBackground : .systemBackground
|
||||
self.title = NSLocalizedString("_activity_", comment: "")
|
||||
|
||||
tableView.allowsSelection = false
|
||||
tableView.separatorColor = UIColor.clear
|
||||
tableView.contentInset = insets
|
||||
tableView.backgroundColor = .systemBackground
|
||||
tableView.backgroundColor = usesGroupedBackground ? .systemGroupedBackground : .systemBackground
|
||||
tableView.hideTopScrollEdgeEffect()
|
||||
|
||||
if showComments {
|
||||
setupComments()
|
||||
@@ -75,13 +78,7 @@ class NCActivity: UIViewController, NCSharePagingContent {
|
||||
commentView = Bundle.main.loadNibNamed("NCActivityCommentView", owner: self, options: nil)?.first as? NCActivityCommentView
|
||||
commentView?.setup(account: metadata.account) { newComment in
|
||||
guard let newComment = newComment, !newComment.isEmpty, let metadata = self.metadata else { return }
|
||||
NextcloudKit.shared.putComments(fileId: metadata.fileId, message: newComment, account: metadata.account) { task in
|
||||
Task {
|
||||
let identifier = await NCNetworking.shared.networkingTasks.createIdentifier(account: metadata.account,
|
||||
path: metadata.fileId,
|
||||
name: "putComments")
|
||||
await NCNetworking.shared.networkingTasks.track(identifier: identifier, task: task)
|
||||
}
|
||||
NextcloudKit.shared.putComments(fileId: metadata.fileId, message: newComment, account: metadata.account) { _ in
|
||||
} completion: { _, _, error in
|
||||
if error == .success {
|
||||
self.commentView?.newCommentField.text?.removeAll()
|
||||
@@ -89,8 +86,7 @@ class NCActivity: UIViewController, NCSharePagingContent {
|
||||
} else {
|
||||
Task {
|
||||
await showErrorBanner(windowScene: self.windowScene,
|
||||
text: error.errorDescription,
|
||||
errorCode: error.errorCode)
|
||||
error: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -106,12 +102,8 @@ class NCActivity: UIViewController, NCSharePagingContent {
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
|
||||
Task {
|
||||
await NCNetworking.shared.networkingTasks.cancel(identifier: "NCActivity")
|
||||
}
|
||||
|
||||
// Cancel Queue & Retrieves Properties
|
||||
NCNetworking.shared.downloadThumbnailActivityQueue.cancelAll()
|
||||
activityTasks.forEach { $0.cancel() }
|
||||
activityTasks.removeAll()
|
||||
}
|
||||
|
||||
override func viewWillLayoutSubviews() {
|
||||
@@ -120,7 +112,7 @@ class NCActivity: UIViewController, NCSharePagingContent {
|
||||
tableView.tableHeaderView = commentView
|
||||
commentView?.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
|
||||
commentView?.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
|
||||
viewContainerConstraint.constant = height - 10
|
||||
viewContainerConstraint.constant = height
|
||||
}
|
||||
|
||||
func makeTableFooterView() -> UIView {
|
||||
@@ -164,25 +156,25 @@ extension NCActivity: UITableViewDelegate {
|
||||
label.text = utility.getTitleFromDate(sectionDates[section])
|
||||
label.textAlignment = .center
|
||||
|
||||
let blur = UIBlurEffect(style: .systemMaterial)
|
||||
let blurredEffectView = UIVisualEffectView(effect: blur)
|
||||
blurredEffectView.layer.cornerRadius = 11
|
||||
blurredEffectView.layer.masksToBounds = true
|
||||
let pill = UIView()
|
||||
pill.backgroundColor = .systemGray5
|
||||
pill.layer.cornerRadius = 11
|
||||
pill.layer.masksToBounds = true
|
||||
|
||||
view.addSubview(blurredEffectView)
|
||||
view.addSubview(pill)
|
||||
view.addSubview(label)
|
||||
|
||||
blurredEffectView.translatesAutoresizingMaskIntoConstraints = false
|
||||
pill.translatesAutoresizingMaskIntoConstraints = false
|
||||
label.translatesAutoresizingMaskIntoConstraints = false
|
||||
|
||||
NSLayoutConstraint.activate([
|
||||
blurredEffectView.topAnchor.constraint(equalTo: view.topAnchor),
|
||||
blurredEffectView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
|
||||
blurredEffectView.widthAnchor.constraint(equalToConstant: label.intrinsicContentSize.width + 30),
|
||||
blurredEffectView.heightAnchor.constraint(equalToConstant: 22),
|
||||
pill.topAnchor.constraint(equalTo: view.topAnchor),
|
||||
pill.centerXAnchor.constraint(equalTo: view.centerXAnchor),
|
||||
pill.widthAnchor.constraint(equalToConstant: label.intrinsicContentSize.width + 30),
|
||||
pill.heightAnchor.constraint(equalToConstant: 22),
|
||||
label.topAnchor.constraint(equalTo: view.topAnchor),
|
||||
label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
|
||||
label.centerYAnchor.constraint(equalTo: blurredEffectView.centerYAnchor)
|
||||
label.centerYAnchor.constraint(equalTo: pill.centerYAnchor)
|
||||
])
|
||||
|
||||
return view
|
||||
@@ -225,6 +217,8 @@ extension NCActivity: UITableViewDataSource {
|
||||
cell.delegate = self
|
||||
cell.configureAvatarMenu()
|
||||
|
||||
/*
|
||||
|
||||
// Avatar
|
||||
let fileName = NCSession.shared.getFileName(urlBase: metadata.urlBase, user: comment.actorId)
|
||||
let results = NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName)
|
||||
@@ -235,11 +229,13 @@ extension NCActivity: UITableViewDataSource {
|
||||
cell.avatarImage?.image = results.image
|
||||
}
|
||||
|
||||
|
||||
if let tblAvatar = results.tblAvatar,
|
||||
!tblAvatar.loaded,
|
||||
NCNetworking.shared.downloadAvatarQueue.operations.filter({ ($0 as? NCOperationDownloadAvatar)?.fileName == fileName }).isEmpty {
|
||||
NCNetworking.shared.downloadAvatarQueue.addOperation(NCOperationDownloadAvatar(user: comment.actorId, fileName: fileName, account: account, view: tableView))
|
||||
}
|
||||
*/
|
||||
|
||||
// Username
|
||||
cell.labelUser.text = comment.actorDisplayName
|
||||
@@ -300,17 +296,41 @@ extension NCActivity: UITableViewDataSource {
|
||||
cell.configureAvatarMenu()
|
||||
|
||||
let fileName = NCSession.shared.getFileName(urlBase: session.urlBase, user: activity.user)
|
||||
let results = NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName)
|
||||
|
||||
if results.image == nil {
|
||||
cell.avatar?.image = utility.loadUserImage(for: activity.user, displayName: nil, urlBase: session.urlBase)
|
||||
} else {
|
||||
cell.avatar?.image = results.image
|
||||
let fileNameLocalPath = self.utilityFileSystem.createServerUrl(serverUrl: utilityFileSystem.directoryUserData, fileName: fileName)
|
||||
if let image = UIImage(contentsOfFile: fileNameLocalPath) {
|
||||
cell.avatar?.image = image
|
||||
}
|
||||
let user = activity.user
|
||||
let idActivity = activity.idActivity
|
||||
let account = session.account
|
||||
|
||||
if !(results.tblAvatar?.loaded ?? false),
|
||||
NCNetworking.shared.downloadAvatarQueue.operations.filter({ ($0 as? NCOperationDownloadAvatar)?.fileName == fileName }).isEmpty {
|
||||
NCNetworking.shared.downloadAvatarQueue.addOperation(NCOperationDownloadAvatar(user: activity.user, fileName: fileName, account: session.account, view: tableView))
|
||||
Task {
|
||||
let etagResource = await database.getTableAvatarAsync(fileName: fileName)?.etag
|
||||
await NCTransferCoordinator.shared.start(identifier: fileName,
|
||||
priority: .userInitiated) {
|
||||
let results = await NextcloudKit.shared.downloadAvatarAsync(
|
||||
user: user,
|
||||
fileNameLocalPath: fileNameLocalPath,
|
||||
sizeImage: NCGlobal.shared.avatarSize,
|
||||
avatarSizeRounded: NCGlobal.shared.avatarSizeRounded,
|
||||
etagResource: etagResource,
|
||||
account: account)
|
||||
|
||||
if results.error == .success,
|
||||
let image = results.imageAvatar,
|
||||
let etag = results.etag,
|
||||
etag != etagResource {
|
||||
await self.database.addAvatarAsync(fileName: fileName, etag: etag)
|
||||
await MainActor.run {
|
||||
guard
|
||||
let cell = self.tableView.cellForRow(at: indexPath) as? NCActivityTableViewCell,
|
||||
cell.idActivity == idActivity else {
|
||||
return
|
||||
}
|
||||
cell.avatar?.image = image
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
cell.subjectLeadingConstraint.constant = -30
|
||||
@@ -419,21 +439,14 @@ extension NCActivity {
|
||||
guard showComments, let metadata = metadata else { return }
|
||||
disptachGroup?.enter()
|
||||
|
||||
NextcloudKit.shared.getComments(fileId: metadata.fileId, account: metadata.account) { task in
|
||||
Task {
|
||||
let identifier = await NCNetworking.shared.networkingTasks.createIdentifier(account: metadata.account,
|
||||
path: metadata.fileId,
|
||||
name: "getComments")
|
||||
await NCNetworking.shared.networkingTasks.track(identifier: identifier, task: task)
|
||||
}
|
||||
NextcloudKit.shared.getComments(fileId: metadata.fileId, account: metadata.account) { _ in
|
||||
} completion: { _, comments, _, error in
|
||||
if error == .success, let comments = comments {
|
||||
self.database.addComments(comments, account: metadata.account, objectId: metadata.fileId)
|
||||
} else if error.errorCode != NCGlobal.shared.errorResourceNotFound {
|
||||
Task {
|
||||
await showErrorBanner(windowScene: self.windowScene,
|
||||
text: error.errorDescription,
|
||||
errorCode: error.errorCode)
|
||||
error: error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -447,11 +460,14 @@ extension NCActivity {
|
||||
|
||||
/// Check if most recent activivities are loaded, if not trigger reload
|
||||
func checkRecentActivity(disptachGroup: DispatchGroup) {
|
||||
Task {
|
||||
// If is already in-flight, do nothing
|
||||
if await NCNetworking.shared.networkingTasks.isReading(identifier: "NCActivity") {
|
||||
return
|
||||
}
|
||||
activityTasks.removeAll {
|
||||
$0.state == .completed || $0.state == .canceling
|
||||
}
|
||||
|
||||
if activityTasks.contains(where: {
|
||||
$0.state == .running || $0.state == .suspended
|
||||
}) {
|
||||
return
|
||||
}
|
||||
|
||||
guard let result = database.getLatestActivityId(account: session.account), metadata == nil, hasActivityToLoad else {
|
||||
@@ -467,8 +483,11 @@ extension NCActivity {
|
||||
objectType: objectType,
|
||||
previews: true,
|
||||
account: session.account) { task in
|
||||
Task {
|
||||
await NCNetworking.shared.networkingTasks.track(identifier: "NCActivity", task: task)
|
||||
Task { @MainActor in
|
||||
self.activityTasks.removeAll {
|
||||
$0.state == .completed || $0.state == .canceling
|
||||
}
|
||||
self.activityTasks.append(task)
|
||||
}
|
||||
} completion: { account, _, activityFirstKnown, activityLastGiven, _, error in
|
||||
defer { disptachGroup.leave() }
|
||||
@@ -499,8 +518,11 @@ extension NCActivity {
|
||||
objectType: objectType,
|
||||
previews: true,
|
||||
account: session.account) { task in
|
||||
Task {
|
||||
await NCNetworking.shared.networkingTasks.track(identifier: "NCActivity", task: task)
|
||||
Task { @MainActor in
|
||||
self.activityTasks.removeAll {
|
||||
$0.state == .completed || $0.state == .canceling
|
||||
}
|
||||
self.activityTasks.append(task)
|
||||
}
|
||||
} completion: { account, activities, activityFirstKnown, activityLastGiven, _, error in
|
||||
defer { disptachGroup.leave() }
|
||||
|
||||