Эх сурвалжийг харах

Merge branch 'develop' of https://github.com/nextcloud/ios into 2444-onlyoffice-ios-app-hides-ui-elements-on-newer-devices

Milen Pivchev 1 жил өмнө
parent
commit
b345522392
54 өөрчлөгдсөн 1619 нэмэгдсэн , 165 устгасан
  1. 68 0
      .github/workflows/additional-targets.yml
  2. 2 2
      .github/workflows/lint.yml
  3. 35 32
      .github/workflows/xcode.yml
  4. 2 0
      .gitignore
  5. 3 0
      .slather.yml
  6. 1 0
      .swiftlint.yml
  7. 3 0
      Gemfile
  8. 632 35
      Nextcloud.xcodeproj/project.pbxproj
  9. 46 2
      Nextcloud.xcodeproj/xcshareddata/xcschemes/File Provider Extension.xcscheme
  10. 46 3
      Nextcloud.xcodeproj/xcshareddata/xcschemes/Nextcloud.xcscheme
  11. 44 0
      Nextcloud.xcodeproj/xcshareddata/xcschemes/Notification Service Extension.xcscheme
  12. 46 2
      Nextcloud.xcodeproj/xcshareddata/xcschemes/Share.xcscheme
  13. 44 0
      Nextcloud.xcodeproj/xcshareddata/xcschemes/Widget.xcscheme
  14. 50 0
      README.md
  15. 13 7
      Share/NCShareExtension+Files.swift
  16. 18 0
      Sourcery/EnvVars.stencil
  17. BIN
      Sourcery/bin/sourcery
  18. 81 0
      Tests/NextcloudIntegrationTests/FilesIntegrationTests.swift
  19. 83 0
      Tests/NextcloudIntegrationTests/LoginIntegrationTests.swift
  20. 18 0
      Tests/NextcloudSnapshotTests/Extensions/SwiftUIView+Extensions.swift
  21. 24 0
      Tests/NextcloudSnapshotTests/NextcloudSnapshotTests.swift
  22. BIN
      Tests/NextcloudSnapshotTests/__Snapshots__/NextcloudSnapshotTests/test_CapalitiesView.DefaultPreviewConfiguration.heic
  23. BIN
      Tests/NextcloudSnapshotTests/__Snapshots__/NextcloudSnapshotTests/test_HUDView.DefaultPreviewConfiguration.heic
  24. 35 0
      Tests/NextcloudUITests/BaseUIXCTestCase.swift
  25. 64 0
      Tests/NextcloudUITests/LoginUITests.swift
  26. 1 1
      Tests/NextcloudUnitTests/NextcloudUnitTests.swift
  27. 49 0
      create-docker-test-server.sh
  28. 16 0
      iOSClient/AppDelegate.swift
  29. 72 59
      iOSClient/Diagnostics/NCCapabilitiesView.swift
  30. 0 0
      iOSClient/Extensions/Optional+Extension.swift
  31. 1 1
      iOSClient/Extensions/PHAsset+Extension.swift
  32. 6 1
      iOSClient/Extensions/View+Extension.swift
  33. 12 1
      iOSClient/GUI/HUDView.swift
  34. 3 0
      iOSClient/NCGlobal.swift
  35. 3 0
      iOSClient/Notification/NCNotification.storyboard
  36. 4 2
      iOSClient/Notification/NCNotification.swift
  37. BIN
      iOSClient/Supporting Files/ar.lproj/InfoPlist.strings
  38. BIN
      iOSClient/Supporting Files/cs-CZ.lproj/Localizable.strings
  39. BIN
      iOSClient/Supporting Files/de.lproj/Localizable.strings
  40. BIN
      iOSClient/Supporting Files/es.lproj/Localizable.strings
  41. BIN
      iOSClient/Supporting Files/fr.lproj/Localizable.strings
  42. BIN
      iOSClient/Supporting Files/gl.lproj/InfoPlist.strings
  43. BIN
      iOSClient/Supporting Files/gl.lproj/Localizable.strings
  44. BIN
      iOSClient/Supporting Files/hu.lproj/Localizable.strings
  45. BIN
      iOSClient/Supporting Files/pt-BR.lproj/Localizable.strings
  46. BIN
      iOSClient/Supporting Files/sr.lproj/Localizable.strings
  47. BIN
      iOSClient/Supporting Files/sv.lproj/Localizable.strings
  48. BIN
      iOSClient/Supporting Files/tr.lproj/Localizable.strings
  49. BIN
      iOSClient/Supporting Files/uk.lproj/Localizable.strings
  50. BIN
      iOSClient/Supporting Files/zh-Hans.lproj/Localizable.strings
  51. BIN
      iOSClient/Supporting Files/zh_HK.lproj/Localizable.strings
  52. 1 0
      iOSClient/Viewer/NCViewer.swift
  53. 58 3
      iOSClient/Viewer/NCViewerMedia/NCPlayer/NCPlayer.swift
  54. 35 14
      iOSClient/Viewer/NCViewerPDF/NCViewerPDF.swift

+ 68 - 0
.github/workflows/additional-targets.yml

@@ -0,0 +1,68 @@
+name: Build additional targets
+
+on:
+  push:
+    branches:
+      - master
+      - develop
+  pull_request:
+    types: [synchronize, opened, reopened, ready_for_review]
+    branches:
+      - master
+      - develop
+
+jobs:
+  build-and-test:
+    name: Build and Test
+    runs-on: macOS-latest
+    if: github.event.pull_request.draft == false
+    env:
+      PROJECT: Nextcloud.xcodeproj
+      DESTINATION: platform=iOS Simulator,name=iPhone 14
+    steps:
+    - name: Set env var
+      run: echo "DEVELOPER_DIR=$(xcode-select --print-path)" >> $GITHUB_ENV
+    - uses: actions/checkout@v3
+    - name: Setup Bundler and Install Gems
+      run: |
+        gem install bundler
+        bundle install
+        bundle update
+    - name: Restore Carhage Cache
+      uses: actions/cache@v3
+      id: carthage-cache
+      with:
+        path: Carthage
+        key: ${{ runner.os }}-carthage-${{ hashFiles('**/Cartfile.resolved') }}
+        restore-keys: |
+          ${{ runner.os }}-carthage-
+    - name: Carthage
+      if: steps.carthage-cache.outputs.cache-hit != 'true'
+      run: carthage bootstrap --use-xcframeworks --platform iOS
+    - name: Download GoogleService-Info.plist
+      run: wget "https://raw.githubusercontent.com/firebase/quickstart-ios/master/mock-GoogleService-Info.plist" -O GoogleService-Info.plist
+    - name: Build iOS Share
+      run: |
+        xcodebuild build -project $PROJECT -scheme "$SCHEME" -destination "$DESTINATION"
+      env:
+          SCHEME: Share
+    - name: Build iOS File Extension
+      run: |
+        xcodebuild build -project $PROJECT -scheme "$SCHEME" -destination "$DESTINATION"
+      env:
+          SCHEME: File Provider Extension
+    - name: Build iOS Notification Extension
+      run: |
+        xcodebuild build -project $PROJECT -scheme "$SCHEME" -destination "$DESTINATION"
+      env:
+          SCHEME: Notification Service Extension
+    - name: Build iOS Widget
+      run: |
+        xcodebuild build -project $PROJECT -scheme "$SCHEME" -destination "$DESTINATION"
+      env:
+          SCHEME: Widget
+    - name: Build iOS Widget Dashboard IntentHandler
+      run: |
+        xcodebuild build -project $PROJECT -scheme "$SCHEME" -destination "$DESTINATION"
+      env:
+          SCHEME: WidgetDashboardIntentHandler

+ 2 - 2
.github/workflows/lint.yml

@@ -20,7 +20,7 @@ jobs:
     if: github.event.pull_request.draft == false
 
     steps:
-     - uses: actions/checkout@v2
+     - uses: actions/checkout@v3
 
      - name: GitHub Action for SwiftLint
-       uses: norio-nomura/action-swiftlint@3.1.0
+       uses: norio-nomura/action-swiftlint@3.2.1

+ 35 - 32
.github/workflows/xcode.yml

@@ -1,4 +1,4 @@
-name: Build
+name: Build main target
 
 on:
   push:
@@ -7,23 +7,30 @@ on:
       - develop
   pull_request:
     types: [synchronize, opened, reopened, ready_for_review]
-    branches: 
+    branches:
       - master
       - develop
 
 jobs:
-  XCBuild:
+  build-and-test:
+    name: Build and Test
     runs-on: macOS-latest
     if: github.event.pull_request.draft == false
     env:
       PROJECT: Nextcloud.xcodeproj
       DESTINATION: platform=iOS Simulator,name=iPhone 14
+      SCHEME: Nextcloud
     steps:
     - name: Set env var
       run: echo "DEVELOPER_DIR=$(xcode-select --print-path)" >> $GITHUB_ENV
-    - uses: actions/checkout@v2
+    - uses: actions/checkout@v3
+    - name: Setup Bundler and Install Gems
+      run: |
+        gem install bundler
+        bundle install
+        bundle update
     - name: Restore Carhage Cache
-      uses: actions/cache@v2
+      uses: actions/cache@v3
       id: carthage-cache
       with:
         path: Carthage
@@ -35,34 +42,30 @@ jobs:
       run: carthage bootstrap --use-xcframeworks --platform iOS
     - name: Download GoogleService-Info.plist
       run: wget "https://raw.githubusercontent.com/firebase/quickstart-ios/master/mock-GoogleService-Info.plist" -O GoogleService-Info.plist
-    - name: Build & Test Nextcloud iOS
-      run: |
-        xcodebuild clean build test -project $PROJECT -scheme "$SCHEME" -destination "$DESTINATION"
-      env:
-          SCHEME: Nextcloud
-    - name: Build iOS Share
+    - name: Install docker
       run: |
-        xcodebuild build -project $PROJECT -scheme "$SCHEME" -destination "$DESTINATION"
-      env:
-          SCHEME: Share
-    - name: Build iOS File Extension
+        brew install docker
+        colima start
+    - name: Create docker test server and export enviroment variables
       run: |
-        xcodebuild build -project $PROJECT -scheme "$SCHEME" -destination "$DESTINATION"
-      env:
-          SCHEME: File Provider Extension
-    - name: Build iOS Notification Extension
-      run: |
-        xcodebuild build -project $PROJECT -scheme "$SCHEME" -destination "$DESTINATION"
-      env:
-          SCHEME: Notification Service Extension
-    - name: Build iOS Widget
+        source ./create-docker-test-server.sh
+        if [ ! -f ".env-vars" ]; then
+            touch .env-vars
+            echo "export TEST_SERVER_URL=$TEST_SERVER_URL" >> .env-vars
+            echo "export TEST_USER=$TEST_USER" >> .env-vars
+            echo "export TEST_APP_PASSWORD=$TEST_APP_PASSWORD" >> .env-vars
+        fi
+    - name: Build & Test Nextcloud iOS
       run: |
-        xcodebuild build -project $PROJECT -scheme "$SCHEME" -destination "$DESTINATION"
-      env:
-          SCHEME: Widget
-    - name: Build iOS Widget Dashboard IntentHandler
+        set -o pipefail && xcodebuild test -project $PROJECT \
+        -scheme "$SCHEME" \
+        -destination "$DESTINATION" \
+        -enableCodeCoverage YES \
+        -test-iterations 3 \
+        -retry-tests-on-failure \
+        | xcpretty
+    - name: Upload coverage to codecov
       run: |
-        xcodebuild build -project $PROJECT -scheme "$SCHEME" -destination "$DESTINATION"
-      env:
-          SCHEME: WidgetDashboardIntentHandler
-          
+        bundle exec slather
+        bash <(curl -s https://codecov.io/bash) -f ./cobertura.xml -X coveragepy -X gcov -X xcode -t ${{ secrets.CODECOV_TOKEN }}
+

+ 2 - 0
.gitignore

@@ -42,3 +42,5 @@ Carthage/
 .swiftpm
 Package.resolved
 
+*.generated.swift
+/.env-vars

+ 3 - 0
.slather.yml

@@ -0,0 +1,3 @@
+coverage_service: cobertura_xml
+xcodeproj: Nextcloud.xcodeproj
+scheme: Nextcloud

+ 1 - 0
.swiftlint.yml

@@ -42,6 +42,7 @@ disabled_rules:
 excluded:
   - Carthage
   - Pods
+  - Tests
 
   # iOS Files Quarantine
 

+ 3 - 0
Gemfile

@@ -0,0 +1,3 @@
+source 'https://rubygems.org'
+gem 'slather'
+gem 'xcpretty' 

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 632 - 35
Nextcloud.xcodeproj/project.pbxproj


+ 46 - 2
Nextcloud.xcodeproj/xcshareddata/xcschemes/File Provider Extension.xcscheme

@@ -57,8 +57,52 @@
             <BuildableReference
                BuildableIdentifier = "primary"
                BlueprintIdentifier = "AF8ED1F82757821000B8DBC4"
-               BuildableName = "NextcloudTests.xctest"
-               BlueprintName = "NextcloudTests"
+               BuildableName = "NextcloudUnitTests.xctest"
+               BlueprintName = "NextcloudUnitTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "C0046CD92A17B98400D87C9D"
+               BuildableName = "NextcloudUITests.xctest"
+               BlueprintName = "NextcloudUITests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "C04E2F1F2A17BB4D001BAD85"
+               BuildableName = "NextcloudIntegrationTests.xctest"
+               BlueprintName = "NextcloudIntegrationTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "C04E2F2C2A17BB77001BAD85"
+               BuildableName = "NextcloudEndToEndTests.xctest"
+               BlueprintName = "NextcloudEndToEndTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "F31F69412A2F6D4500162F76"
+               BuildableName = "NextcloudSnapshotTests.xctest"
+               BlueprintName = "NextcloudSnapshotTests"
                ReferencedContainer = "container:Nextcloud.xcodeproj">
             </BuildableReference>
          </TestableReference>

+ 46 - 3
Nextcloud.xcodeproj/xcshareddata/xcschemes/Nextcloud.xcscheme

@@ -26,7 +26,8 @@
       buildConfiguration = "Debug"
       selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
       selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
-      shouldUseLaunchSchemeArgsEnv = "YES"
+      shouldUseLaunchSchemeArgsEnv = "NO"
+      enableThreadSanitizer = "YES"
       codeCoverageEnabled = "YES">
       <MacroExpansion>
          <BuildableReference
@@ -43,8 +44,49 @@
             <BuildableReference
                BuildableIdentifier = "primary"
                BlueprintIdentifier = "AF8ED1F82757821000B8DBC4"
-               BuildableName = "NextcloudTests.xctest"
-               BlueprintName = "NextcloudTests"
+               BuildableName = "NextcloudUnitTests.xctest"
+               BlueprintName = "NextcloudUnitTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "C0046CD92A17B98400D87C9D"
+               BuildableName = "NextcloudUITests.xctest"
+               BlueprintName = "NextcloudUITests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "C04E2F1F2A17BB4D001BAD85"
+               BuildableName = "NextcloudIntegrationTests.xctest"
+               BlueprintName = "NextcloudIntegrationTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "C04E2F2C2A17BB77001BAD85"
+               BuildableName = "NextcloudEndToEndTests.xctest"
+               BlueprintName = "NextcloudEndToEndTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "F31F69412A2F6D4500162F76"
+               BuildableName = "NextcloudSnapshotTests.xctest"
+               BlueprintName = "NextcloudSnapshotTests"
                ReferencedContainer = "container:Nextcloud.xcodeproj">
             </BuildableReference>
          </TestableReference>
@@ -54,6 +96,7 @@
       buildConfiguration = "Debug"
       selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
       selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+      enableThreadSanitizer = "YES"
       launchStyle = "0"
       useCustomWorkingDirectory = "NO"
       ignoresPersistentStateOnLaunch = "NO"

+ 44 - 0
Nextcloud.xcodeproj/xcshareddata/xcschemes/Notification Service Extension.xcscheme

@@ -43,6 +43,50 @@
       selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
       shouldUseLaunchSchemeArgsEnv = "YES">
       <Testables>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "C0046CD92A17B98400D87C9D"
+               BuildableName = "NextcloudUITests.xctest"
+               BlueprintName = "NextcloudUITests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "C04E2F1F2A17BB4D001BAD85"
+               BuildableName = "NextcloudIntegrationTests.xctest"
+               BlueprintName = "NextcloudIntegrationTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "C04E2F2C2A17BB77001BAD85"
+               BuildableName = "NextcloudEndToEndTests.xctest"
+               BlueprintName = "NextcloudEndToEndTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "F31F69412A2F6D4500162F76"
+               BuildableName = "NextcloudSnapshotTests.xctest"
+               BlueprintName = "NextcloudSnapshotTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
       </Testables>
    </TestAction>
    <LaunchAction

+ 46 - 2
Nextcloud.xcodeproj/xcshareddata/xcschemes/Share.xcscheme

@@ -57,8 +57,52 @@
             <BuildableReference
                BuildableIdentifier = "primary"
                BlueprintIdentifier = "AF8ED1F82757821000B8DBC4"
-               BuildableName = "NextcloudTests.xctest"
-               BlueprintName = "NextcloudTests"
+               BuildableName = "NextcloudUnitTests.xctest"
+               BlueprintName = "NextcloudUnitTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "C0046CD92A17B98400D87C9D"
+               BuildableName = "NextcloudUITests.xctest"
+               BlueprintName = "NextcloudUITests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "C04E2F1F2A17BB4D001BAD85"
+               BuildableName = "NextcloudIntegrationTests.xctest"
+               BlueprintName = "NextcloudIntegrationTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "C04E2F2C2A17BB77001BAD85"
+               BuildableName = "NextcloudEndToEndTests.xctest"
+               BlueprintName = "NextcloudEndToEndTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "F31F69412A2F6D4500162F76"
+               BuildableName = "NextcloudSnapshotTests.xctest"
+               BlueprintName = "NextcloudSnapshotTests"
                ReferencedContainer = "container:Nextcloud.xcodeproj">
             </BuildableReference>
          </TestableReference>

+ 44 - 0
Nextcloud.xcodeproj/xcshareddata/xcschemes/Widget.xcscheme

@@ -43,6 +43,50 @@
       selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
       shouldUseLaunchSchemeArgsEnv = "YES">
       <Testables>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "C0046CD92A17B98400D87C9D"
+               BuildableName = "NextcloudUITests.xctest"
+               BlueprintName = "NextcloudUITests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "C04E2F1F2A17BB4D001BAD85"
+               BuildableName = "NextcloudIntegrationTests.xctest"
+               BlueprintName = "NextcloudIntegrationTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "C04E2F2C2A17BB77001BAD85"
+               BuildableName = "NextcloudEndToEndTests.xctest"
+               BlueprintName = "NextcloudEndToEndTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "F31F69412A2F6D4500162F76"
+               BuildableName = "NextcloudSnapshotTests.xctest"
+               BlueprintName = "NextcloudSnapshotTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
       </Testables>
    </TestAction>
    <LaunchAction

+ 50 - 0
README.md

@@ -79,3 +79,53 @@ If you need assistance or want to ask a question about the iOS app, you are welc
 Do you want to try the latest version in development of Nextcloud iOS ? Simple, follow this simple step
 
 [Apple TestFlight](https://testflight.apple.com/join/RXEJbWj9)
+
+## Testing
+
+#### Note: If a Unit or Integration test exclusively uses and tests NextcloudKit functions and components, then write that test in the NextcloudKit repo. NextcloudKit is used in many other repos as an API, and it's better if such tests are located there.
+
+### Unit tests:
+
+There are currently no preresquites for unit testing that need to be done. Mock everything that's not needed. 
+
+### Integration tests:
+To run integration tests, we need a docker instance of a Nextcloud test server.
+The CI does all this automatically, but to do it manually:
+1. Run `docker run --rm -d -p 8080:80 ghcr.io/juliushaertl/nextcloud-dev-php80:latest` to spin up a docker container of the Nextcloud test server.
+2. Log in on the test server and generate an app password for device. There are a couple test accounts, but `admin` as username and password works best.
+3. Build the iOS project once. This will generate an `.env-vars` file in the root directory. It contains env vars that the project will use for testing.
+4. Provide proper values for the env vars inside the file. Here is an example:
+```
+export TEST_SERVER_URL=http://localhost:8080
+export TEST_USER=nextcloud
+export TEST_PASSWORD=FAeSR-6Jk7s-DzLny-CCQHL-f49BP
+```
+5. Build the iOS project again. If all the values are set correctly you will see a generated file called `EnvVars.generated.swift`. It contains the env vars as Swift fields that can be easily used in code:
+```
+/**
+This is generated from the .env-vars file in the root directory. If there is an environment variable here that is needed and not filled, please look into this file.
+ */
+ public struct EnvVars {
+  static let testUser = "nextcloud"
+  static let testPassword = "FAeSR-6Jk7s-DzLny-CCQHL-f49BP"
+  static let testServerUrl = "http://localhost:8080"
+}
+```
+6. You can now run the integration tests. They will use the env vars to connect to the test server to do the testing. 
+
+
+### UI tests
+
+UI tests also use the docker server, but besides that there is nothing else you need to do.
+
+### Snapshot tests
+
+Snapshot tests are made via this library: https://github.com/pointfreeco/swift-snapshot-testing and these 2 extensions:
+1. https://github.com/doordash-oss/swiftui-preview-snapshots - for creating SwiftUI snapshot tests via previews.
+2. https://github.com/alexey1312/SnapshotTestingHEIC - makes snapshot images HEIC instead of PNGs for much reduced size.
+
+Snapshot tests are a great way to test if UI elements are consistent with designs and don't break with new commits, but they can be very finicky and the smallest change can cause them to fail. Keep in mind:
+
+- For SwiftUI snapshot tests, It's always a good idea to utilize previews, as they do not depend on device/app state and it has less chances to fail due to wrong state.
+
+- For UIKit snapshot tests, try to include mock dependencies to always make sure the UI is rendered the same way. Even a text change can cause the tests to fail.

+ 13 - 7
Share/NCShareExtension+Files.swift

@@ -22,6 +22,7 @@
 //
 
 import Foundation
+import UniformTypeIdentifiers
 
 extension NCShareExtension {
 
@@ -89,7 +90,7 @@ extension NCShareExtension {
 
 class NCFilesExtensionHandler {
     var itemsProvider: [NSItemProvider] = []
-    lazy var filesName: [String] = []
+    lazy var fileNames: [String] = []
     let dateFormatter: DateFormatter = {
         let formatter = DateFormatter()
         formatter.dateFormat = "yyyy-MM-dd HH-mm-ss-"
@@ -102,20 +103,24 @@ class NCFilesExtensionHandler {
         var counter = 0
 
         self.itemsProvider = items.compactMap({ $0.attachments }).flatMap { $0.filter({
-            $0.hasItemConformingToTypeIdentifier(kUTTypeItem as String) || $0.hasItemConformingToTypeIdentifier("public.url")
+            $0.hasItemConformingToTypeIdentifier(UTType.item.identifier as String) || $0.hasItemConformingToTypeIdentifier("public.url")
         }) }
 
         for (ix, provider) in itemsProvider.enumerated() {
             provider.loadItem(forTypeIdentifier: provider.typeIdentifier) { [self] item, error in
                 defer {
                     counter += 1
-                    if counter == itemsProvider.count { completion(self.filesName) }
+                    if counter == itemsProvider.count { completion(self.fileNames) }
                 }
                 guard error == nil else { return }
                 var originalName = (dateFormatter.string(from: Date())) + String(ix)
 
                 if let url = item as? URL, url.isFileURL, !url.lastPathComponent.isEmpty {
                     originalName = url.lastPathComponent
+
+                    if fileNames.contains(originalName), let incrementalNumber = CCUtility.getIncrementalNumber() {
+                        originalName = "\(url.deletingPathExtension().lastPathComponent) \(incrementalNumber).\(url.pathExtension)"
+                    }
                 }
 
                 var fileName: String?
@@ -131,7 +136,9 @@ class NCFilesExtensionHandler {
                 default: return
                 }
 
-                if let fileName = fileName, !filesName.contains(fileName) { filesName.append(fileName) }
+                if let fileName, !fileNames.contains(fileName) {
+                    fileNames.append(fileName)
+                }
             }
         }
     }
@@ -140,8 +147,7 @@ class NCFilesExtensionHandler {
     func getItem(image: UIImage, fileName: String) -> String? {
         var fileUrl = URL(fileURLWithPath: NSTemporaryDirectory() + fileName)
         if fileUrl.pathExtension.isEmpty { fileUrl.appendPathExtension("png") }
-        guard let pngImageData = image.pngData(),
-              (try? pngImageData.write(to: fileUrl, options: [.atomic])) != nil
+        guard let pngImageData = image.pngData(), (try? pngImageData.write(to: fileUrl, options: [.atomic])) != nil
         else { return nil }
         return fileUrl.lastPathComponent
     }
@@ -151,7 +157,7 @@ class NCFilesExtensionHandler {
     func getItem(url: URL, fileName: String) -> String? {
         var fileName = fileName
         guard url.isFileURL else {
-            guard !filesName.contains(url.lastPathComponent) else { return nil }
+            guard !fileNames.contains(url.lastPathComponent) else { return nil }
             if !url.deletingPathExtension().lastPathComponent.isEmpty { fileName = url.deletingPathExtension().lastPathComponent }
             fileName += "." + (url.pathExtension.isEmpty ? "html" : url.pathExtension)
             let filenamePath = NSTemporaryDirectory() + fileName

+ 18 - 0
Sourcery/EnvVars.stencil

@@ -0,0 +1,18 @@
+//
+//  EnvVars.stencil.swift
+//  NextcloudIntegrationTests
+//
+//  Created by Milen on 31.05.23.
+//  Copyright © 2023 Marino Faggiana. All rights reserved.
+//
+
+import Foundation
+
+/**
+This is generated from the .env-vars file in the root directory. If there is an environment variable here that is needed and not filled, please look into this file.
+ */
+ public struct EnvVars {
+  static let testUser = "{{ argument.TEST_USER }}"
+  static let testAppPassword = "{{ argument.TEST_APP_PASSWORD }}"
+  static let testServerUrl = "{{ argument.TEST_SERVER_URL }}"
+}

BIN
Sourcery/bin/sourcery


+ 81 - 0
Tests/NextcloudIntegrationTests/FilesIntegrationTests.swift

@@ -0,0 +1,81 @@
+//
+//  NextcloudIntegrationTests.swift
+//  NextcloudIntegrationTests
+//
+//  Created by Milen Pivchev on 5/19/23.
+//  Copyright © 2023 Marino Faggiana. All rights reserved.
+//
+
+import XCTest
+import NextcloudKit
+@testable import Nextcloud
+
+final class FilesIntegrationTests: XCTestCase {
+    private let baseUrl = EnvVars.testServerUrl
+    private let user = EnvVars.testUser
+    private let userId = EnvVars.testUser
+    private let password = EnvVars.testAppPassword
+    private lazy var account = "\(userId) \(baseUrl)"
+
+    private let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
+
+    override func setUp() {
+        appDelegate.deleteAllAccounts()
+    }
+
+    func test_createReadDeleteFolder_withProperParams_shouldCreateReadDeleteFolder() throws {
+        let expectation = expectation(description: "Should finish last callback")
+
+        let folderName = "TestFolder10"
+        let serverUrl = "\(baseUrl)/remote.php/dav/files/\(userId)"
+        let serverUrlFileName = "\(serverUrl)/\(folderName)"
+
+        NextcloudKit.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: baseUrl)
+
+        // Test creating folder
+        NCNetworking.shared.createFolder(fileName: folderName, serverUrl: serverUrl, account: account, urlBase: baseUrl, userId: userId, withPush: true) { error in
+            XCTAssertEqual(NKError.success.errorCode, error.errorCode)
+            XCTAssertEqual(NKError.success.errorDescription, error.errorDescription)
+
+            Thread.sleep(forTimeInterval: 0.2)
+
+            // Test reading folder, should exist
+            NCNetworking.shared.readFolder(serverUrl: serverUrlFileName, account: self.user) { account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, metadatasDelete, error in
+                XCTAssertEqual(self.account, account)
+                XCTAssertEqual(NKError.success.errorCode, error.errorCode)
+                XCTAssertEqual(NKError.success.errorDescription, error.errorDescription)
+                XCTAssertEqual(metadataFolder?.fileName, folderName)
+
+                // Check Realm directory, should exist
+                let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "serverUrl == %@", serverUrlFileName))
+                XCTAssertNotNil(directory)
+
+                Thread.sleep(forTimeInterval: 0.2)
+
+                Task {
+                    // Test deleting folder
+                    await _ = NCNetworking.shared.deleteMetadata(metadataFolder!, onlyLocalCache: false)
+
+                    XCTAssertEqual(NKError.success.errorCode, error.errorCode)
+                    XCTAssertEqual(NKError.success.errorDescription, error.errorDescription)
+
+                    try await Task.sleep(for: .milliseconds(200))
+
+                    // Test reading folder, should NOT exist
+                    NCNetworking.shared.readFolder(serverUrl: serverUrlFileName, account: self.user) { account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, metadatasDelete, error in
+                        defer { expectation.fulfill() }
+
+                        XCTAssertEqual(404, error.errorCode)
+                        XCTAssertNil(metadataFolder?.fileName)
+
+                        // Check Realm directory, should NOT exist
+                        let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "serverUrl == %@", serverUrlFileName))
+                        XCTAssertNil(directory)
+                    }
+                }
+            }
+        }
+        
+        waitForExpectations(timeout: 100)
+    }
+}

+ 83 - 0
Tests/NextcloudIntegrationTests/LoginIntegrationTests.swift

@@ -0,0 +1,83 @@
+//
+//  NextcloudIntegrationTests.swift
+//  NextcloudIntegrationTests
+//
+//  Created by Milen Pivchev on 5/19/23.
+//  Copyright © 2023 Marino Faggiana. All rights reserved.
+//
+
+import XCTest
+import NextcloudKit
+@testable import Nextcloud
+
+final class LoginIntegrationTests: XCTestCase {
+    private let baseUrl = EnvVars.testServerUrl
+    private let user = EnvVars.testUser
+    private let userId = EnvVars.testUser
+    private let password = EnvVars.testAppPassword
+    private lazy var account = "\(userId) \(baseUrl)"
+
+    private let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
+
+    override func setUp() {
+        appDelegate.deleteAllAccounts()
+    }
+
+    func test_createReadDeleteFolder_withProperParams_shouldCreateReadDeleteFolder() throws {
+        let expectation = expectation(description: "Should finish last callback")
+
+        let folderName = "TestFolder10"
+        let serverUrl = "\(baseUrl)/remote.php/dav/files/\(userId)"
+        let serverUrlFileName = "\(serverUrl)/\(folderName)"
+
+        NextcloudKit.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: baseUrl)
+
+        // Test creating folder
+        NCNetworking.shared.createFolder(fileName: folderName, serverUrl: serverUrl, account: account, urlBase: baseUrl, userId: userId, withPush: true) { error in
+            XCTAssertEqual(NKError.success.errorCode, error.errorCode)
+            XCTAssertEqual(NKError.success.errorDescription, error.errorDescription)
+
+            Thread.sleep(forTimeInterval: 0.2)
+
+            // Test reading folder, should exist
+            NCNetworking.shared.readFolder(serverUrl: serverUrlFileName, account: self.user) { account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, metadatasDelete, error in
+                XCTAssertEqual(self.account, account)
+                XCTAssertEqual(NKError.success.errorCode, error.errorCode)
+                XCTAssertEqual(NKError.success.errorDescription, error.errorDescription)
+                XCTAssertEqual(metadataFolder?.fileName, folderName)
+
+                // Check Realm directory, should exist
+                let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "serverUrl == %@", serverUrlFileName))
+                XCTAssertNotNil(directory)
+
+                Thread.sleep(forTimeInterval: 0.2)
+
+                Task {
+                    // Test deleting folder
+                    await _ = NCNetworking.shared.deleteMetadata(metadataFolder!, onlyLocalCache: false)
+
+                    XCTAssertEqual(NKError.success.errorCode, error.errorCode)
+                    XCTAssertEqual(NKError.success.errorDescription, error.errorDescription)
+
+                    try await Task.sleep(for: .milliseconds(200))
+
+                    // Test reading folder, should NOT exist
+                    NCNetworking.shared.readFolder(serverUrl: serverUrlFileName, account: self.user) { account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, metadatasDelete, error in
+                        defer { expectation.fulfill() }
+
+                        XCTAssertEqual(404, error.errorCode)
+                        XCTAssertNil(metadataFolder?.fileName)
+
+                        // Check Realm directory, should NOT exist
+                        let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "serverUrl == %@", serverUrlFileName))
+                        XCTAssertNil(directory)
+                    }
+                }
+
+
+            }
+        }
+        
+        waitForExpectations(timeout: 100)
+    }
+}

+ 18 - 0
Tests/NextcloudSnapshotTests/Extensions/SwiftUIView+Extensions.swift

@@ -0,0 +1,18 @@
+//
+//  SwiftUIView+Extensions.swift
+//  Nextcloud
+//
+//  Created by Milen on 06.06.23.
+//  Copyright © 2023 Marino Faggiana. All rights reserved.
+//
+
+import Foundation
+import SwiftUI
+
+extension SwiftUI.View {
+    func toVC() -> UIViewController {
+        let vc = UIHostingController (rootView: self)
+        vc.view.frame = UIScreen.main.bounds
+        return vc
+    }
+}

+ 24 - 0
Tests/NextcloudSnapshotTests/NextcloudSnapshotTests.swift

@@ -0,0 +1,24 @@
+//
+//  NextcloudSnapshotTests.swift
+//  NextcloudSnapshotTests
+//
+//  Created by Milen on 06.06.23.
+//  Copyright © 2023 Marino Faggiana. All rights reserved.
+//
+
+import XCTest
+import SnapshotTesting
+import SnapshotTestingHEIC
+import PreviewSnapshotsTesting
+import SwiftUI
+@testable import Nextcloud
+
+final class NextcloudSnapshotTests: XCTestCase {
+    func test_HUDView() {
+        HUDView_Previews.snapshots.assertSnapshots(as: .imageHEIC)
+    }
+
+    func test_CapalitiesView() {
+        NCCapabilitiesView_Previews.snapshots.assertSnapshots(as: .imageHEIC)
+    }
+}

BIN
Tests/NextcloudSnapshotTests/__Snapshots__/NextcloudSnapshotTests/test_CapalitiesView.DefaultPreviewConfiguration.heic


BIN
Tests/NextcloudSnapshotTests/__Snapshots__/NextcloudSnapshotTests/test_HUDView.DefaultPreviewConfiguration.heic


+ 35 - 0
Tests/NextcloudUITests/BaseUIXCTestCase.swift

@@ -0,0 +1,35 @@
+//
+//  BaseUIXCTestCase.swift
+//  NextcloudUITests
+//
+//  Created by Milen on 20.06.23.
+//  Copyright © 2023 Marino Faggiana. All rights reserved.
+//
+
+import XCTest
+
+class BaseUIXCTestCase: XCTestCase {
+    let timeoutSeconds: Double = 100
+
+    override final class var runsForEachTargetApplicationUIConfiguration: Bool {
+        false
+    }
+
+    internal func waitForEnabled(object: Any?) {
+        let predicate = NSPredicate(format: "enabled == true")
+        expectation(for: predicate, evaluatedWith: object, handler: nil)
+        waitForExpectations(timeout: timeoutSeconds, handler: nil)
+    }
+
+    internal func waitForHittable(object: Any?) {
+        let predicate = NSPredicate(format: "hittable == true")
+        expectation(for: predicate, evaluatedWith: object, handler: nil)
+        waitForExpectations(timeout: timeoutSeconds, handler: nil)
+    }
+
+    internal func waitForEnabledAndHittable(object: Any?) {
+        waitForEnabled(object: object)
+        waitForHittable(object: object)
+    }
+}
+

+ 64 - 0
Tests/NextcloudUITests/LoginUITests.swift

@@ -0,0 +1,64 @@
+//
+//  NextcloudUITests.swift
+//  NextcloudUITests
+//
+//  Created by Milen Pivchev on 5/19/23.
+//  Copyright © 2023 Marino Faggiana. All rights reserved.
+//
+
+import XCTest
+
+final class LoginUITests: BaseUIXCTestCase {
+    private let baseUrl = EnvVars.testServerUrl
+    private let user = EnvVars.testUser
+    private let userId = EnvVars.testUser
+    private let password = EnvVars.testAppPassword
+    private lazy var account = "\(userId) \(baseUrl)"
+
+    let app = XCUIApplication()
+
+    override func setUp() {
+        app.launchArguments += ["UI_TESTING"]
+    }
+
+    func test_logIn_withProperParams_shouldLogInAndGoToHomeScreen() throws {
+        app.launch()
+
+        let loginButton = app.buttons["Log in"]
+        XCTAssert(loginButton.waitForExistence(timeout: timeoutSeconds))
+        loginButton.tap()
+
+        let serverAddressHttpsTextField = app.textFields["Server address https:// …"]
+        serverAddressHttpsTextField.tap()
+        serverAddressHttpsTextField.typeText(baseUrl)
+        let button = app.windows.children(matching: .other).element.children(matching: .other).element.children(matching: .other).element.children(matching: .other).element.children(matching: .other).element.children(matching: .other).element.children(matching: .button).element(boundBy: 0)
+        button.tap()
+
+        let webViewsQuery = app.webViews.webViews.webViews
+        let loginButton2 = webViewsQuery/*@START_MENU_TOKEN@*/.buttons["Log in"]/*[[".otherElements.matching(identifier: \"Nextcloud\")",".otherElements[\"main\"].buttons[\"Log in\"]",".buttons[\"Log in\"]"],[[[-1,2],[-1,1],[-1,0,1]],[[-1,2],[-1,1]]],[0]]@END_MENU_TOKEN@*/
+        XCTAssert(loginButton2.waitForExistence(timeout: timeoutSeconds))
+        waitForEnabledAndHittable(object: loginButton2)
+        loginButton2.tap()
+
+        let element = webViewsQuery/*@START_MENU_TOKEN@*/.otherElements["main"]/*[[".otherElements[\"Login – Nextcloud\"].otherElements[\"main\"]",".otherElements[\"main\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.children(matching: .other).element(boundBy: 1)
+        let usernameTextField = element.children(matching: .other).element(boundBy: 2).children(matching: .textField).element
+        XCTAssert(usernameTextField.waitForExistence(timeout: timeoutSeconds))
+        usernameTextField.tap()
+        usernameTextField.typeText(user)
+        let passwordTextField = element.children(matching: .other).element(boundBy: 4).children(matching: .secureTextField).element
+        passwordTextField.tap()
+        passwordTextField.typeText(user)
+        let loginButton3 = webViewsQuery/*@START_MENU_TOKEN@*/.buttons["Log in"]/*[[".otherElements[\"Login – Nextcloud\"]",".otherElements[\"main\"].buttons[\"Log in\"]",".buttons[\"Log in\"]"],[[[-1,2],[-1,1],[-1,0,1]],[[-1,2],[-1,1]]],[0]]@END_MENU_TOKEN@*/
+        XCTAssert(loginButton3.waitForExistence(timeout: timeoutSeconds))
+        loginButton3.tap()
+
+        let grantAccessButton = webViewsQuery/*@START_MENU_TOKEN@*/.buttons["Grant access"]/*[[".otherElements.matching(identifier: \"Nextcloud\")",".otherElements[\"main\"].buttons[\"Grant access\"]",".buttons[\"Grant access\"]"],[[[-1,2],[-1,1],[-1,0,1]],[[-1,2],[-1,1]]],[0]]@END_MENU_TOKEN@*/
+        XCTAssert(grantAccessButton.waitForExistence(timeout: timeoutSeconds))
+        waitForEnabledAndHittable(object: grantAccessButton)
+        grantAccessButton.tap()
+
+        // Check if we are in the home screen
+        XCTAssert(app.navigationBars["Nextcloud"].waitForExistence(timeout: timeoutSeconds))
+        XCTAssert(app.tabBars["Tab Bar"].waitForExistence(timeout: timeoutSeconds))
+    }
+}

+ 1 - 1
NextcloudTests/NextcloudTests.swift → Tests/NextcloudUnitTests/NextcloudUnitTests.swift

@@ -8,7 +8,7 @@
 
 import XCTest
 
-class NextcloudTests: XCTestCase {
+class NextcloudUnitTests: XCTestCase {
 
     override func setUpWithError() throws {
         // Put setup code here. This method is called before the invocation of each test method in the class.

+ 49 - 0
create-docker-test-server.sh

@@ -0,0 +1,49 @@
+#!/usr/bin/env bash
+#This script creates a testable Docker enviroment of the Nextcloud server, and is used by the CI for tests.
+
+container_name="nextcloud_test"
+port=8080
+server_url="http://localhost:${port}"
+user="admin"
+
+docker run --rm -d --name $container_name -p $port:80 ghcr.io/juliushaertl/nextcloud-dev-php80:latest
+
+timeout=300
+elapsed=0
+
+echo "Waiting for server..."
+
+sleep 2
+
+while true; do
+    content=$(curl -s $server_url/status.php)
+
+    if [[ $content == *"installed\":true"* ]]; then
+        break
+    fi
+
+    elapsed=$((elapsed + 1))
+
+    if [ $elapsed -ge $timeout ]; then
+        echo "No success after $timeout seconds."
+        exit 1
+    fi
+
+    sleep 1
+done
+
+echo "Server is installed."
+echo "Exporting env vars..."
+
+sleep 2
+
+password=$(docker exec -e NC_PASS=$user $container_name sudo -E -u www-data php /var/www/html/occ user:add-app-password $user --password-from-env | tail -1)
+
+export TEST_APP_PASSWORD=$password
+export TEST_SERVER_URL=$server_url
+export TEST_USER=$user
+
+echo "TEST_SERVER_URL: ${TEST_SERVER_URL}"
+echo "TEST_USER: ${TEST_USER}"
+echo "TEST_APP_PASSWORD: ${TEST_APP_PASSWORD}"
+echo "Env vars exported."

+ 16 - 0
iOSClient/AppDelegate.swift

@@ -59,7 +59,16 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
 
     private var privacyProtectionWindow: UIWindow?
 
+    var isUiTestingEnabled: Bool {
+         get {
+             return ProcessInfo.processInfo.arguments.contains("UI_TESTING")
+         }
+     }
+
     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
+        if isUiTestingEnabled {
+            deleteAllAccounts()
+        }
 
         NCSettingsBundleHelper.checkAndExecuteSettings(delay: 0)
 
@@ -625,6 +634,13 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
         }
     }
 
+    @objc func deleteAllAccounts() {
+        let accounts = NCManageDatabase.shared.getAccounts()
+        accounts?.forEach({ account in
+            deleteAccount(account, wipe: true)
+        })
+    }
+
     @objc func changeAccount(_ account: String) {
 
         NCManageDatabase.shared.setAccountActive(account)

+ 72 - 59
iOSClient/Diagnostics/NCCapabilitiesView.swift

@@ -8,6 +8,7 @@
 
 import SwiftUI
 import NextcloudKit
+import PreviewSnapshots
 
 @objc class NCHostingCapabilitiesView: NSObject {
 
@@ -35,70 +36,62 @@ class NCCapabilitiesViewOO: ObservableObject {
     @Published var homeServer = ""
 
     init() {
+        guard let activeAccount = NCManageDatabase.shared.getActiveAccount() else { return }
+        var textEditor = false
+        var onlyofficeEditors = false
 
-        if ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" {
-            capabililies = [Capability(text: "Collabora", image: UIImage(named: "collabora")!, resize: true, available: true),
-                            Capability(text: "XXX site", image: UIImage(systemName: "lock.shield")!, resize: false, available: false)
-            ]
-            homeServer = "https://cloud.nextcloud.com/remote.php.dav/files/marino/"
-        } else {
-            guard let activeAccount = NCManageDatabase.shared.getActiveAccount() else { return }
-            var textEditor = false
-            var onlyofficeEditors = false
-
-            if let image = UIImage(named: "share") {
-                capabililies.append(Capability(text: "File sharing", image: image, resize: true, available: NCGlobal.shared.capabilityFileSharingApiEnabled))
-            }
-            if let image = UIImage(systemName: "network") {
-                capabililies.append(Capability(text: "External site", image: image, resize: false, available: NCGlobal.shared.capabilityExternalSites))
-            }
-            if let image = UIImage(systemName: "lock") {
-                capabililies.append(Capability(text: "End-to-End Encryption", image: image, resize: false, available: NCGlobal.shared.capabilityE2EEEnabled))
-            }
-            if let image = UIImage(systemName: "bolt") {
-                capabililies.append(Capability(text: "Activity", image: image, resize: false, available: !NCGlobal.shared.capabilityActivity.isEmpty))
-            }
-            if let image = UIImage(systemName: "bell") {
-                capabililies.append(Capability(text: "Notification", image: image, resize: false, available: !NCGlobal.shared.capabilityNotification.isEmpty))
-            }
-            if let image = UIImage(systemName: "trash") {
-                capabililies.append(Capability(text: "Deleted files", image: image, resize: false, available: NCGlobal.shared.capabilityFilesUndelete))
-            }
+        if let image = UIImage(named: "share") {
+            capabililies.append(Capability(text: "File sharing", image: image, resize: true, available: NCGlobal.shared.capabilityFileSharingApiEnabled))
+        }
+        if let image = UIImage(systemName: "network") {
+            capabililies.append(Capability(text: "External site", image: image, resize: false, available: NCGlobal.shared.capabilityExternalSites))
+        }
+        if let image = UIImage(systemName: "lock") {
+            capabililies.append(Capability(text: "End-to-End Encryption", image: image, resize: false, available: NCGlobal.shared.capabilityE2EEEnabled))
+        }
+        if let image = UIImage(systemName: "bolt") {
+            capabililies.append(Capability(text: "Activity", image: image, resize: false, available: !NCGlobal.shared.capabilityActivity.isEmpty))
+        }
+        if let image = UIImage(systemName: "bell") {
+            capabililies.append(Capability(text: "Notification", image: image, resize: false, available: !NCGlobal.shared.capabilityNotification.isEmpty))
+        }
+        if let image = UIImage(systemName: "trash") {
+            capabililies.append(Capability(text: "Deleted files", image: image, resize: false, available: NCGlobal.shared.capabilityFilesUndelete))
+        }
 
-            if let editors = NCManageDatabase.shared.getDirectEditingEditors(account: activeAccount.account) {
-                for editor in editors {
-                    if editor.editor == NCGlobal.shared.editorText {
-                        textEditor = true
-                    } else if editor.editor == NCGlobal.shared.editorOnlyoffice {
-                        onlyofficeEditors = true
-                    }
+        if let editors = NCManageDatabase.shared.getDirectEditingEditors(account: activeAccount.account) {
+            for editor in editors {
+                if editor.editor == NCGlobal.shared.editorText {
+                    textEditor = true
+                } else if editor.editor == NCGlobal.shared.editorOnlyoffice {
+                    onlyofficeEditors = true
                 }
             }
+        }
 
-            if let image = UIImage(systemName: "doc.text") {
-                capabililies.append(Capability(text: "Text", image: image, resize: false, available: textEditor))
-            }
-            if let image = UIImage(named: "onlyoffice") {
-                capabililies.append(Capability(text: "ONLYOFFICE", image: image, resize: true, available: onlyofficeEditors))
-            }
-            if let image = UIImage(named: "collabora") {
-                capabililies.append(Capability(text: "Collabora", image: image, resize: true, available: !NCGlobal.shared.capabilityRichdocumentsMimetypes.isEmpty))
-            }
-            if let image = UIImage(systemName: "moon") {
-                capabililies.append(Capability(text: "User Status", image: image, resize: false, available: NCGlobal.shared.capabilityUserStatusEnabled))
-            }
-            if let image = UIImage(systemName: "ellipsis.bubble") {
-                capabililies.append(Capability(text: "Comments", image: image, resize: false, available: NCGlobal.shared.capabilityFilesComments))
-            }
-            if let image = UIImage(systemName: "lock") {
-                capabililies.append(Capability(text: "Lock file", image: image, resize: false, available: !NCGlobal.shared.capabilityFilesLockVersion.isEmpty))
-            }
-            if let image = UIImage(systemName: "person.2") {
-                capabililies.append(Capability(text: "Group folders", image: image, resize: false, available: NCGlobal.shared.capabilityGroupfoldersEnabled))
-            }
-
-            homeServer = NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, userId: activeAccount.userId) + "/"
+        if let image = UIImage(systemName: "doc.text") {
+            capabililies.append(Capability(text: "Text", image: image, resize: false, available: textEditor))
+        }
+        if let image = UIImage(named: "onlyoffice") {
+            capabililies.append(Capability(text: "ONLYOFFICE", image: image, resize: true, available: onlyofficeEditors))
+        }
+        if let image = UIImage(named: "collabora") {
+            capabililies.append(Capability(text: "Collabora", image: image, resize: true, available: !NCGlobal.shared.capabilityRichdocumentsMimetypes.isEmpty))
+        }
+        if let image = UIImage(systemName: "moon") {
+            capabililies.append(Capability(text: "User Status", image: image, resize: false, available: NCGlobal.shared.capabilityUserStatusEnabled))
         }
+        if let image = UIImage(systemName: "ellipsis.bubble") {
+            capabililies.append(Capability(text: "Comments", image: image, resize: false, available: NCGlobal.shared.capabilityFilesComments))
+        }
+        if let image = UIImage(systemName: "lock") {
+            capabililies.append(Capability(text: "Lock file", image: image, resize: false, available: !NCGlobal.shared.capabilityFilesLockVersion.isEmpty))
+        }
+        if let image = UIImage(systemName: "person.2") {
+            capabililies.append(Capability(text: "Group folders", image: image, resize: false, available: NCGlobal.shared.capabilityGroupfoldersEnabled))
+        }
+
+        homeServer = NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, userId: activeAccount.userId) + "/"
     }
 }
 
@@ -175,6 +168,26 @@ struct NCCapabilitiesView: View {
 
 struct NCCapabilitiesView_Previews: PreviewProvider {
     static var previews: some View {
-        NCCapabilitiesView(capabilitiesStatus: NCCapabilitiesViewOO())
+        snapshots.previews.previewLayout(.device)
     }
+
+    static var snapshots: PreviewSnapshots<String> {
+        PreviewSnapshots(
+            configurations: [
+                .init(name: NCGlobal.shared.defaultSnapshotConfiguration, state: "")
+            ],
+            configure: { _ in
+                NCCapabilitiesView(capabilitiesStatus: getCapabilitiesViewOOForPreview()).padding(.top, 20).frameForPreview()
+            })
+    }
+}
+
+func getCapabilitiesViewOOForPreview() -> NCCapabilitiesViewOO {
+    let capabilitiesViewOO = NCCapabilitiesViewOO()
+    capabilitiesViewOO.capabililies = [
+        NCCapabilitiesViewOO.Capability(text: "Collabora", image: UIImage(named: "collabora")!, resize: true, available: true),
+        NCCapabilitiesViewOO.Capability(text: "XXX site", image: UIImage(systemName: "lock.shield")!, resize: false, available: false)
+    ]
+    capabilitiesViewOO.homeServer = "https://cloud.nextcloud.com/remote.php.dav/files/marino/"
+    return capabilitiesViewOO
 }

+ 0 - 0
iOSClient/Extensions/Optional+Extensions.swift → iOSClient/Extensions/Optional+Extension.swift


+ 1 - 1
iOSClient/Extensions/PHAsset+Extension.swift

@@ -15,7 +15,7 @@ extension PHAsset {
             return resource.originalFilename as NSString
         } else {
             return self.value(forKey: "filename") as? NSString
-            ?? ("IMG_" + CCUtility.getIncrementalNumber() + getExtension()) as NSString 
+            ?? ("IMG_" + CCUtility.getIncrementalNumber() + getExtension()) as NSString
         }
     }
 

+ 6 - 1
iOSClient/Extensions/View+Extension.swift

@@ -24,8 +24,13 @@
 import SwiftUI
 
 extension View {
-
     func complexModifier<V: View>(@ViewBuilder _ closure: (Self) -> V) -> some View {
         closure(self)
     }
+
+    /// Use this on preview views that are used in snapshot testing. It prevents the snapashot library from complaining that the view has a size of 0
+    /// Check: https://github.com/pointfreeco/swift-snapshot-testing/issues/738
+    func frameForPreview() -> some View {
+        return frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
+    }
 }

+ 12 - 1
iOSClient/GUI/HUDView.swift

@@ -22,6 +22,7 @@
 //
 
 import SwiftUI
+import PreviewSnapshots
 
 struct HUDView: View {
 
@@ -93,6 +94,16 @@ struct ContentView: View {
 
 struct HUDView_Previews: PreviewProvider {
     static var previews: some View {
-        ContentView()
+        snapshots.previews.previewLayout(.sizeThatFits)
+    }
+
+    static var snapshots: PreviewSnapshots<String> {
+        PreviewSnapshots(
+            configurations: [
+                .init(name: NCGlobal.shared.defaultSnapshotConfiguration, state: "")
+            ],
+            configure: { _ in
+                ContentView().frameForPreview()
+            })
     }
 }

+ 3 - 0
iOSClient/NCGlobal.swift

@@ -441,4 +441,7 @@ class NCGlobal: NSObject {
     @objc var capabilityUserStatusEnabled: Bool                 = false
     var capabilityExternalSites: Bool                           = false
     var capabilityGroupfoldersEnabled: Bool                     = false // NC27
+
+    // SNAPSHOT PREVIEW
+    let defaultSnapshotConfiguration = "DefaultPreviewConfiguration"
 }

+ 3 - 0
iOSClient/Notification/NCNotification.storyboard

@@ -159,6 +159,9 @@
                         </connections>
                     </tableView>
                     <navigationItem key="navigationItem" id="bV4-Hy-bmE"/>
+                    <refreshControl key="refreshControl" opaque="NO" multipleTouchEnabled="YES" contentMode="center" insetsLayoutMarginsFromSafeArea="NO" enabled="NO" contentHorizontalAlignment="center" contentVerticalAlignment="center" id="JwZ-Sr-qEU">
+                        <autoresizingMask key="autoresizingMask"/>
+                    </refreshControl>
                 </tableViewController>
                 <placeholder placeholderIdentifier="IBFirstResponder" id="I7i-N5-tEB" userLabel="First Responder" sceneMemberID="firstResponder"/>
             </objects>

+ 4 - 2
iOSClient/Notification/NCNotification.swift

@@ -34,7 +34,6 @@ class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmpty
     var emptyDataSet: NCEmptyDataSet?
     var isReloadDataSourceNetworkInProgress: Bool = false
 
-
     // MARK: - View Life Cycle
 
     override func viewDidLoad() {
@@ -48,6 +47,8 @@ class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmpty
         tableView.estimatedRowHeight = 50.0
         tableView.backgroundColor = .systemBackground
 
+        refreshControl?.addTarget(self, action: #selector(getNetwokingNotification), for: .valueChanged)
+
         // Empty
         let offset = (self.navigationController?.navigationBar.bounds.height ?? 0) - 20
         emptyDataSet = NCEmptyDataSet(view: tableView, offset: -offset, delegate: self)
@@ -294,7 +295,7 @@ class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmpty
 
     // MARK: - Load notification networking
 
-    func getNetwokingNotification() {
+   @objc func getNetwokingNotification() {
 
         isReloadDataSourceNetworkInProgress = true
         self.tableView.reloadData()
@@ -309,6 +310,7 @@ class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmpty
                     }
                     self.notifications.append(notification as! NKNotifications)
                 }
+                self.refreshControl?.endRefreshing()
                 self.isReloadDataSourceNetworkInProgress = false
                 self.tableView.reloadData()
             }

BIN
iOSClient/Supporting Files/ar.lproj/InfoPlist.strings


BIN
iOSClient/Supporting Files/cs-CZ.lproj/Localizable.strings


BIN
iOSClient/Supporting Files/de.lproj/Localizable.strings


BIN
iOSClient/Supporting Files/es.lproj/Localizable.strings


BIN
iOSClient/Supporting Files/fr.lproj/Localizable.strings


BIN
iOSClient/Supporting Files/gl.lproj/InfoPlist.strings


BIN
iOSClient/Supporting Files/gl.lproj/Localizable.strings


BIN
iOSClient/Supporting Files/hu.lproj/Localizable.strings


BIN
iOSClient/Supporting Files/pt-BR.lproj/Localizable.strings


BIN
iOSClient/Supporting Files/sr.lproj/Localizable.strings


BIN
iOSClient/Supporting Files/sv.lproj/Localizable.strings


BIN
iOSClient/Supporting Files/tr.lproj/Localizable.strings


BIN
iOSClient/Supporting Files/uk.lproj/Localizable.strings


BIN
iOSClient/Supporting Files/zh-Hans.lproj/Localizable.strings


BIN
iOSClient/Supporting Files/zh_HK.lproj/Localizable.strings


+ 1 - 0
iOSClient/Viewer/NCViewer.swift

@@ -100,6 +100,7 @@ class NCViewer: NSObject {
                     let viewController: NCViewerPDF = UIStoryboard(name: "NCViewerPDF", bundle: nil).instantiateInitialViewController() as! NCViewerPDF
 
                     viewController.metadata = metadata
+                    viewController.titleView = metadata.fileNameView
                     viewController.imageIcon = imageIcon
 
                     navigationController.pushViewController(viewController, animated: true)

+ 58 - 3
iOSClient/Viewer/NCViewerMedia/NCPlayer/NCPlayer.swift

@@ -31,6 +31,7 @@ class NCPlayer: NSObject {
     internal let appDelegate = UIApplication.shared.delegate as! AppDelegate
     internal var url: URL?
     internal var player = VLCMediaPlayer()
+    internal var dialogProvider: VLCDialogProvider?
     internal var metadata: tableMetadata
     internal var singleTapGestureRecognizer: UITapGestureRecognizer?
     internal var activityIndicator: UIActivityIndicatorView
@@ -90,6 +91,9 @@ class NCPlayer: NSObject {
         player.media = VLCMedia(url: url)
         player.delegate = self
 
+        dialogProvider = VLCDialogProvider(library: VLCLibrary.shared(), customUI: true)
+        dialogProvider?.customRenderer = self
+
         // player?.media?.addOption("--network-caching=500")
         player.media?.addOption(":http-user-agent=\(userAgent)")
 
@@ -260,9 +264,6 @@ extension NCPlayer: VLCMediaPlayerDelegate {
             print("Played mode: ENDED")
             break
         case .error:
-            let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_error_something_wrong_")
-            NCContentPresenter.shared.showError(error: error, priority: .max)
-            playerToolBar?.removeFromSuperview()
             print("Played mode: ERROR")
             break
         case .playing:
@@ -340,3 +341,57 @@ extension NCPlayer: VLCMediaThumbnailerDelegate {
 
     func mediaThumbnailer(_ mediaThumbnailer: VLCMediaThumbnailer, didFinishThumbnail thumbnail: CGImage) { }
 }
+
+extension NCPlayer: VLCCustomDialogRendererProtocol {
+
+    func showError(withTitle error: String, message: String) {
+
+        let alert = UIAlertController(title: error, message: message, preferredStyle: .alert)
+
+        alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
+            self.playerToolBar?.removeFromSuperview()
+            self.viewerMediaPage?.viewUnload()
+        }))
+
+        self.viewerMediaPage?.present(alert, animated: true)
+    }
+
+    func showLogin(withTitle title: String, message: String, defaultUsername username: String?, askingForStorage: Bool, withReference reference: NSValue) {
+        // UIAlertController other states...
+    }
+
+    func showQuestion(withTitle title: String, message: String, type questionType: VLCDialogQuestionType, cancel cancelString: String?, action1String: String?, action2String: String?, withReference reference: NSValue) {
+
+        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
+
+        if let action1String = action1String {
+            alert.addAction(UIAlertAction(title: action1String, style: .default, handler: { _ in
+                self.dialogProvider?.postAction(1, forDialogReference: reference)
+            }))
+        }
+        if let action2String = action2String {
+            alert.addAction(UIAlertAction(title: action2String, style: .default, handler: { _ in
+                self.dialogProvider?.postAction(2, forDialogReference: reference)
+            }))
+        }
+        if let cancelString = cancelString {
+            alert.addAction(UIAlertAction(title: cancelString, style: .cancel, handler: { _ in
+                self.dialogProvider?.postAction(3, forDialogReference: reference)
+            }))
+        }
+
+        self.viewerMediaPage?.present(alert, animated: true)
+    }
+
+    func showProgress(withTitle title: String, message: String, isIndeterminate: Bool, position: Float, cancel cancelString: String?, withReference reference: NSValue) {
+        // UIAlertController other states...
+    }
+
+    func updateProgress(withReference reference: NSValue, message: String?, position: Float) {
+        // UIAlertController other states...
+    }
+
+    func cancelDialog(withReference reference: NSValue) {
+        // UIAlertController other states...
+    }
+}

+ 35 - 14
iOSClient/Viewer/NCViewerPDF/NCViewerPDF.swift

@@ -30,7 +30,9 @@ class NCViewerPDF: UIViewController, NCViewerPDFSearchDelegate {
 
     @IBOutlet weak var pdfContainer: UIView!
 
-    var metadata = tableMetadata()
+    var metadata: tableMetadata?
+    var url: URL?
+    var titleView: String?
     var imageIcon: UIImage?
 
     private var filePath = ""
@@ -65,14 +67,18 @@ class NCViewerPDF: UIViewController, NCViewerPDFSearchDelegate {
 
     override func viewDidLoad() {
 
-        filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
-        pdfDocument = PDFDocument(url: URL(fileURLWithPath: filePath))
+        if let url = self.url {
+            pdfDocument = PDFDocument(url: url)
+        } else if let metadata = self.metadata {
+            filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
+            pdfDocument = PDFDocument(url: URL(fileURLWithPath: filePath))
+            navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "more")!.image(color: .label, size: 25), style: .plain, target: self, action: #selector(self.openMenuMore))
+        }
         defaultBackgroundColor = pdfView.backgroundColor
         view.backgroundColor = defaultBackgroundColor
 
         navigationController?.navigationBar.prefersLargeTitles = false
-        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "more")!.image(color: .label, size: 25), style: .plain, target: self, action: #selector(self.openMenuMore))
-        navigationItem.title = metadata.fileNameView
+        navigationItem.title = titleView
 
         // TIP
 
@@ -123,6 +129,11 @@ class NCViewerPDF: UIViewController, NCViewerPDFSearchDelegate {
             pdfView.bottomAnchor.constraint(equalTo: pdfContainer.bottomAnchor)
         ])
 
+        // MODAL
+        if self.navigationController?.presentingViewController != nil {
+            self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_close_", comment: ""), style: .plain, target: self, action: #selector(viewDismiss))
+        }
+
         // NOTIFIFICATION
 
         NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
@@ -281,6 +292,10 @@ class NCViewerPDF: UIViewController, NCViewerPDFSearchDelegate {
         navigationController?.popViewController(animated: true)
     }
 
+    @objc func viewDismiss() {
+        self.dismiss(animated: true)
+    }
+
     // MARK: - Tip
 
     func showTip() {
@@ -298,9 +313,9 @@ class NCViewerPDF: UIViewController, NCViewerPDFSearchDelegate {
 
         guard let userInfo = notification.userInfo as NSDictionary?,
               let serverUrl = userInfo["serverUrl"] as? String,
-              serverUrl == self.metadata.serverUrl,
+              serverUrl == self.metadata?.serverUrl,
               let fileName = userInfo["fileName"] as? String,
-              fileName == self.metadata.fileName
+              fileName == self.metadata?.fileName
         else { return }
 
         NCActivityIndicator.shared.start()
@@ -310,9 +325,9 @@ class NCViewerPDF: UIViewController, NCViewerPDFSearchDelegate {
 
         guard let userInfo = notification.userInfo as NSDictionary?,
               let serverUrl = userInfo["serverUrl"] as? String,
-              serverUrl == self.metadata.serverUrl,
+              serverUrl == self.metadata?.serverUrl,
               let fileName = userInfo["fileName"] as? String,
-              fileName == self.metadata.fileName,
+              fileName == self.metadata?.fileName,
               let error = userInfo["error"] as? NKError
         else {
             return
@@ -331,7 +346,7 @@ class NCViewerPDF: UIViewController, NCViewerPDFSearchDelegate {
 
         guard let userInfo = notification.userInfo as NSDictionary?,
               let ocId = userInfo["ocId"] as? String,
-              ocId == self.metadata.ocId,
+              ocId == self.metadata?.ocId,
               let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
         else { return }
 
@@ -342,7 +357,7 @@ class NCViewerPDF: UIViewController, NCViewerPDFSearchDelegate {
 
         guard let userInfo = notification.userInfo as NSDictionary?,
               let ocId = userInfo["ocId"] as? String,
-              ocId == self.metadata.ocId,
+              ocId == self.metadata?.ocId,
               let ocIdNew = userInfo["ocIdNew"] as? String,
               let metadataNew = NCManageDatabase.shared.getMetadataFromOcId(ocIdNew)
         else { return }
@@ -357,7 +372,9 @@ class NCViewerPDF: UIViewController, NCViewerPDFSearchDelegate {
               let error = userInfo["error"] as? NKError
         else { return }
 
-        if error == .success, let ocId = ocId.first, metadata.ocId == ocId {
+        if error == .success,
+           let ocId = ocId.first,
+           metadata?.ocId == ocId {
             viewUnload()
         }
     }
@@ -366,7 +383,7 @@ class NCViewerPDF: UIViewController, NCViewerPDFSearchDelegate {
 
         guard let userInfo = notification.userInfo as NSDictionary?,
               let ocId = userInfo["ocId"] as? String,
-              ocId == self.metadata.ocId,
+              ocId == self.metadata?.ocId,
               let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
         else { return }
 
@@ -410,7 +427,11 @@ class NCViewerPDF: UIViewController, NCViewerPDFSearchDelegate {
 
     @objc func openMenuMore() {
 
-        if imageIcon == nil { imageIcon = UIImage(named: "file_pdf") }
+        guard let metadata = self.metadata else { return }
+        if imageIcon == nil {
+            imageIcon = UIImage(named: "file_pdf")
+        }
+
         NCViewer.shared.toggleMenu(viewController: self, metadata: metadata, webView: false, imageIcon: imageIcon)
     }
 

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно