Procházet zdrojové kódy

add CI (#1711)

* fix

* 404

* fix

* fix

* coding

* coding

* fix

* new Cartfile

* added: allowedAlbumCloudShared

* fix

* fix svg

* fix

* update strings

* new version

* improved share

* coding

* coding

* coding

* coding

* improved richWorkspace

* fix

* added link name (label)

* Delete files / Clear cache

* fix

* test

* coding

* fix

* fix

* fix

* update

* update library

* fix

* #1642

* add size in share

* set title Files as ALIAS

* Build 3

* title & alias

* improved cleanUp

* Improvements pastePasteboard

* coding

* coding

* coding

* build 4

* fix

* coding

* coding

* fix

* fix

* fix share

* coding

* coding

* coding

* coding

* coding

* coding

* coding

* coding

* coding

* coding

* improved code

* nextcloud_unsupported_version 16

* update lib

* new lib

* new build

* Update README.md

update readme

* new version

* update Strings & lib

* Update README.md

* [tx-robot] updated from transifex

Signed-off-by: Nextcloud bot <bot@nextcloud.com>

* Revert "Talk notification"

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Update NCCollectionViewCommon.swift

Fix selection count (in NCRecent)

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Version 4.2.0

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Precompile Brinding header NO

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Coding

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Coding

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Coding

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Coding

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Coding

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Coding

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Improvements passcode

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Revert "Revert "Talk notification""

* Fix TalkNotification room token

Get only roomToken if token & message id are present in objectId

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* PrivacyProtectionWindow

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* PrivacyProtectionWindow

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* PrivacyProtectionWindow

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Improvements

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Improvements

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Improvements

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Improvements

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Improvements

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Improvements

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Update iOSClient/Supporting Files/en.lproj/Localizable.strings

Co-authored-by: Henry <thisisthefoxe@gmail.com>

* Update iOSClient/Settings/NCSettings.m

Co-authored-by: Henry <thisisthefoxe@gmail.com>

* update comment

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* rename func

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* rename func

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Improvements

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Improvements

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Improvements

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Improvements

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Use `guard` for splash screen checks

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* [tx-robot] updated from transifex

Signed-off-by: Nextcloud bot <bot@nextcloud.com>

* [tx-robot] updated from transifex

Signed-off-by: Nextcloud bot <bot@nextcloud.com>

* [tx-robot] updated from transifex

Signed-off-by: Nextcloud bot <bot@nextcloud.com>

* [tx-robot] updated from transifex

Signed-off-by: Nextcloud bot <bot@nextcloud.com>

* Improvements

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Improvements

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Improvements

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Improvement

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Fix server trust nitpicks

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* New build for TestFlight

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* [tx-robot] updated from transifex

Signed-off-by: Nextcloud bot <bot@nextcloud.com>

* [tx-robot] updated from transifex

Signed-off-by: Nextcloud bot <bot@nextcloud.com>

* [tx-robot] updated from transifex

Signed-off-by: Nextcloud bot <bot@nextcloud.com>

* Update NCLoginWeb.swift

Use default app user agent for login. This will display *Nextcloud iOS app* in the user settings.

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Use device name as user agent for login flow

Make sure the user agent is ascii encoded.
Will be shown when logging in, granting access and in /settings/user/security
Use ONLY for login flow, when user agent is saved to DB. For API requests always use `getUserAgent()`

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Build 2

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>

* Fix share email, not asked for password

Check for password enforcement every time a new share should be created. Will display an alert. If password enforcement is off, callback returns `nil`.

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* add CI for xcbuild + linting

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* add resolved cartfile for caching

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* add resolved cartfile for caching

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* add resolved cartfile for caching

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* add resolved cartfile for caching

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* add resolved cartfile for caching

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Update xcode.yml

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Update xcode.yml

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Revert "add resolved cartfile for caching"

This reverts commit 53532867f906b22be8775220316eb413be2b097e.

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Update xcode.yml

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Update xcode.yml

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* fix GoogleServices.plist

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* update CI to XC 13 + fix GoogleService.plist

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Update xcode.yml

Caching..?

Signed-off-by: Henrik Storch <thisisthefoxe@gmail.com>
Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Delete lint.yml

Remove for now since it seem it causes problems with other PRs

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Revert "Delete lint.yml"

This reverts commit 181739526bf76353b992d689a1899296a2dccbcf.

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Linting (default, auto)

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* SwiftLint customisation (few errors, many warnings)

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Update .SwiftLint.yml

+ autocorrect

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Fix linting

Build Successful (?)

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Fix GH actions yml

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Quarantine infected lint files

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Add initial tests

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* CI: Remove xc clean for extensions

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Fix notification weak delegate

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

* Update Readme

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>

Co-authored-by: marinofaggiana <marino@marinofaggiana.com>
Co-authored-by: Nextcloud bot <bot@nextcloud.com>
Henry před 3 roky
rodič
revize
5e304a4e45
100 změnil soubory, kde provedl 7796 přidání a 7218 odebrání
  1. 24 0
      .github/workflows/lint.yml
  2. 55 0
      .github/workflows/xcode.yml
  3. 147 0
      .swiftlint.yml
  4. 36 36
      File Provider Extension/FileProviderData.swift
  5. 13 13
      File Provider Extension/FileProviderDomain.swift
  6. 55 55
      File Provider Extension/FileProviderEnumerator.swift
  7. 85 85
      File Provider Extension/FileProviderExtension+Actions.swift
  8. 14 14
      File Provider Extension/FileProviderExtension+Thumbnail.swift
  9. 113 116
      File Provider Extension/FileProviderExtension.swift
  10. 16 16
      File Provider Extension/FileProviderItem.swift
  11. 39 39
      File Provider Extension/FileProviderUtility.swift
  12. 212 3
      Nextcloud.xcodeproj/project.pbxproj
  13. 11 0
      Nextcloud.xcodeproj/xcshareddata/xcschemes/File Provider Extension.xcscheme
  14. 12 1
      Nextcloud.xcodeproj/xcshareddata/xcschemes/Nextcloud.xcscheme
  15. 11 0
      Nextcloud.xcodeproj/xcshareddata/xcschemes/Share.xcscheme
  16. 54 0
      NextcloudTests/NCGlobalTests.swift
  17. 33 0
      NextcloudTests/NextcloudTests.swift
  18. 3 3
      Notification Service Extension/NotificationService.swift
  19. 11 7
      README.md
  20. 222 223
      Share/NCShareExtension.swift
  21. 52 53
      iOSClient/Activity/NCActivity.swift
  22. 69 69
      iOSClient/Activity/NCActivityTableViewCell.swift
  23. 154 152
      iOSClient/AppDelegate.swift
  24. 51 51
      iOSClient/BackgroundImageColor/NCBackgroundImageColor.swift
  25. 1 1
      iOSClient/Brand/Intro/NCIntroCollectionViewCell.swift
  26. 9 11
      iOSClient/Brand/Intro/NCIntroViewController.swift
  27. 89 89
      iOSClient/Brand/NCBrand.swift
  28. 29 30
      iOSClient/BrowserWeb/NCBrowserWeb.swift
  29. 46 46
      iOSClient/Data/NCDataSource.swift
  30. 44 46
      iOSClient/Data/NCDatabase.swift
  31. 30 30
      iOSClient/Data/NCElementsJSON.swift
  32. 485 0
      iOSClient/Data/NCManageDatabase+Account.swift
  33. 235 0
      iOSClient/Data/NCManageDatabase+Activity.swift
  34. 691 2163
      iOSClient/Data/NCManageDatabase.swift
  35. 789 0
      iOSClient/Data/NCManageDatabse+Metadata.swift
  36. 60 60
      iOSClient/Diagnostics/NCCapabilitiesViewController.swift
  37. 21 21
      iOSClient/EmptyView/NCEmptyDataSet.swift
  38. 2 2
      iOSClient/Extensions/NSMutableAttributedString+Extensions.swift
  39. 2 3
      iOSClient/Extensions/NotificationCenter+MainThread.swift
  40. 5 5
      iOSClient/Extensions/String+Extensions.swift
  41. 19 19
      iOSClient/Extensions/UIColor+Extensions.swift
  42. 6 6
      iOSClient/Extensions/UIControl+Extensions.swift
  43. 24 24
      iOSClient/Extensions/UIImage+Extensions.swift
  44. 23 24
      iOSClient/Favorites/NCFavorite.swift
  45. 27 28
      iOSClient/FileViewInFolder/NCFileViewInFolder.swift
  46. 25 26
      iOSClient/Files/NCFiles.swift
  47. 17 17
      iOSClient/Login/NCAppConfigView.swift
  48. 110 110
      iOSClient/Login/NCLogin.swift
  49. 23 23
      iOSClient/Login/NCLoginQRCode.swift
  50. 70 70
      iOSClient/Login/NCLoginWeb.swift
  51. 46 46
      iOSClient/Main/Account Request/NCAccountRequest.swift
  52. 72 73
      iOSClient/Main/AudioRecorder/NCAudioRecorderViewController.swift
  53. 214 214
      iOSClient/Main/Collection Common/NCCollectionViewCommon.swift
  54. 29 29
      iOSClient/Main/Collection Common/NCGridCell.swift
  55. 28 28
      iOSClient/Main/Collection Common/NCListCell.swift
  56. 163 167
      iOSClient/Main/Create cloud/NCCreateFormUploadAssets.swift
  57. 115 116
      iOSClient/Main/Create cloud/NCCreateFormUploadConflict.swift
  58. 6 6
      iOSClient/Main/Create cloud/NCCreateFormUploadConflictCell.swift
  59. 148 148
      iOSClient/Main/Create cloud/NCCreateFormUploadDocuments.swift
  60. 210 213
      iOSClient/Main/Create cloud/NCCreateFormUploadScanDocument.swift
  61. 101 102
      iOSClient/Main/Create cloud/NCCreateFormUploadVoiceNote.swift
  62. 39 39
      iOSClient/Main/Create cloud/NCCreateMenuAdd.swift
  63. 0 1
      iOSClient/Main/NCCellProtocol.swift
  64. 233 234
      iOSClient/Main/NCFunctionCenter.swift
  65. 17 19
      iOSClient/Main/NCMainNavigationController.swift
  66. 34 35
      iOSClient/Main/NCMainTabBar.swift
  67. 46 48
      iOSClient/Main/NCPickerViewController.swift
  68. 38 38
      iOSClient/Main/Section Header Footer/NCSectionHeaderFooter.swift
  69. 6 7
      iOSClient/Media/Cell/NCGridMediaCell.swift
  70. 179 182
      iOSClient/Media/NCMedia.swift
  71. 41 41
      iOSClient/Menu/AppDelegate+Menu.swift
  72. 74 76
      iOSClient/Menu/NCCollectionViewCommon+Menu.swift
  73. 6 7
      iOSClient/Menu/NCLoginWeb+Menu.swift
  74. 32 33
      iOSClient/Menu/NCMedia+Menu.swift
  75. 6 6
      iOSClient/Menu/NCMenu.swift
  76. 20 20
      iOSClient/Menu/NCSortMenu.swift
  77. 8 9
      iOSClient/Menu/NCTrash+Menu.swift
  78. 66 66
      iOSClient/Menu/NCViewer+Menu.swift
  79. 2 2
      iOSClient/Menu/UIViewController+Menu.swift
  80. 53 53
      iOSClient/More/NCMore.swift
  81. 26 54
      iOSClient/NCGlobal.swift
  82. 76 72
      iOSClient/Networking/NCAutoUpload.swift
  83. 283 264
      iOSClient/Networking/NCNetworking.swift
  84. 20 20
      iOSClient/Networking/NCNetworkingCheckRemoteUser.swift
  85. 92 81
      iOSClient/Networking/NCNetworkingChunkedUpload.swift
  86. 150 142
      iOSClient/Networking/NCNetworkingE2EE.swift
  87. 62 56
      iOSClient/Networking/NCNetworkingProcessUpload.swift
  88. 115 109
      iOSClient/Networking/NCOperationQueue.swift
  89. 65 65
      iOSClient/Networking/NCService.swift
  90. 61 61
      iOSClient/Notification/NCNotification.swift
  91. 26 26
      iOSClient/Offline/NCOffline.swift
  92. 25 26
      iOSClient/Recent/NCRecent.swift
  93. 56 56
      iOSClient/Rename file/NCRenameFile.swift
  94. 35 35
      iOSClient/RichWorkspace/NCRichWorkspaceCommon.swift
  95. 14 14
      iOSClient/RichWorkspace/NCViewerRichWorkspace.swift
  96. 30 31
      iOSClient/RichWorkspace/NCViewerRichWorkspaceWebView.swift
  97. 1 1
      iOSClient/ScanDocument/ScanCell.swift
  98. 177 181
      iOSClient/ScanDocument/ScanCollectionView.swift
  99. 67 67
      iOSClient/Security/NCEndToEndMetadata.swift
  100. 9 9
      iOSClient/Security/NCViewCertificateDetails.swift

+ 24 - 0
.github/workflows/lint.yml

@@ -0,0 +1,24 @@
+
+# Lints the project using SwiftLint
+
+name: SwiftLint
+
+on:
+  push:
+    branches:
+      - master
+      - develop
+  pull_request:
+    branches:
+      - master
+      - develop  
+
+jobs:
+  Lint:
+    runs-on: ubuntu-latest
+    
+    steps:
+     - uses: actions/checkout@v2
+       
+     - name: GitHub Action for SwiftLint
+       uses: norio-nomura/action-swiftlint@3.1.0

+ 55 - 0
.github/workflows/xcode.yml

@@ -0,0 +1,55 @@
+name: Build
+
+on: 
+  push:
+    branches: 
+      - master
+      - develop
+  pull_request:
+    branches: 
+      - master
+      - develop
+
+jobs:
+  XCBuild:
+    runs-on: macOS-11
+    env:
+      PROJECT: Nextcloud.xcodeproj
+      DESTINATION: platform=iOS Simulator,name=iPhone 11
+    steps:
+    - name: Set env var
+      run: echo "DEVELOPER_DIR=$(xcode-select --print-path)" >> $GITHUB_ENV
+    - uses: actions/checkout@v2
+    - name: Restore Carhage Cache
+      uses: actions/cache@v2
+      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 & Test Nextcloud iOS
+      run: |
+        xcodebuild clean build test -project $PROJECT -scheme "$SCHEME" -destination "$DESTINATION"
+      env:
+          SCHEME: Nextcloud
+    - 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

+ 147 - 0
.swiftlint.yml

@@ -0,0 +1,147 @@
+opt_in_rules: # some rules are turned off by default, so you need to opt-in
+  - empty_collection_literal
+  - empty_count
+  - empty_string
+  - explicit_init
+  - file_types_order
+  - unneeded_parentheses_in_closure_argument
+
+empty_count:
+  severity: warning
+
+line_length:
+  # warning: 120
+  warning: 200
+
+type_body_length:
+  # error: 350
+  error: 500
+
+identifier_name:
+  min_length: 0
+
+
+excluded:
+  - Carthage
+  - Pods
+
+  # iOS Files Quarantine
+  - File Provider Extension/FileProviderData.swift
+  - File Provider Extension/FileProviderDomain.swift
+  - File Provider Extension/FileProviderEnumerator.swift
+  - File Provider Extension/FileProviderExtension+Actions.swift
+  - File Provider Extension/FileProviderExtension+Thumbnail.swift
+  - File Provider Extension/FileProviderExtension.swift
+  - File Provider Extension/FileProviderUtility.swift
+  - Notification Service Extension/NotificationService.swift
+  - Share/NCShareExtension.swift
+  - iOSClient/Activity/NCActivity.swift
+  - iOSClient/Activity/NCActivityTableViewCell.swift
+  - iOSClient/AppDelegate.swift
+  - iOSClient/BackgroundImageColor/NCBackgroundImageColor.swift
+  - iOSClient/Brand/Intro/NCIntroViewController.swift
+  - iOSClient/Brand/NCBrand.swift
+  - iOSClient/BrowserWeb/NCBrowserWeb.swift
+  - iOSClient/Data/NCDataSource.swift
+  - iOSClient/Data/NCDatabase.swift
+  - iOSClient/Data/NCElementsJSON.swift
+  - iOSClient/Data/NCManageDatabase+Account.swift
+  - iOSClient/Data/NCManageDatabase+Activity.swift
+  - iOSClient/Data/NCManageDatabase.swift
+  - iOSClient/Data/NCManageDatabse+Metadata.swift
+  - iOSClient/Diagnostics/NCCapabilitiesViewController.swift
+  - iOSClient/EmptyView/NCEmptyDataSet.swift
+  - iOSClient/Extensions/UIColor+Extensions.swift
+  - iOSClient/Extensions/UIImage+Extensions.swift
+  - iOSClient/Favorites/NCFavorite.swift
+  - iOSClient/FileViewInFolder/NCFileViewInFolder.swift
+  - iOSClient/Files/NCFiles.swift
+  - iOSClient/Login/NCAppConfigView.swift
+  - iOSClient/Login/NCLogin.swift
+  - iOSClient/Login/NCLoginWeb.swift
+  - iOSClient/Main/Account Request/NCAccountRequest.swift
+  - iOSClient/Main/AudioRecorder/NCAudioRecorderViewController.swift
+  - iOSClient/Main/Collection Common/NCCollectionViewCommon.swift
+  - iOSClient/Main/Collection Common/NCGridCell.swift
+  - iOSClient/Main/Collection Common/NCListCell.swift
+  - iOSClient/Main/Create cloud/NCCreateFormUploadAssets.swift
+  - iOSClient/Main/Create cloud/NCCreateFormUploadConflict.swift
+  - iOSClient/Main/Create cloud/NCCreateFormUploadConflictCell.swift
+  - iOSClient/Main/Create cloud/NCCreateFormUploadDocuments.swift
+  - iOSClient/Main/Create cloud/NCCreateFormUploadScanDocument.swift
+  - iOSClient/Main/Create cloud/NCCreateFormUploadVoiceNote.swift
+  - iOSClient/Main/Create cloud/NCCreateMenuAdd.swift
+  - iOSClient/Main/NCFunctionCenter.swift
+  - iOSClient/Main/NCMainTabBar.swift
+  - iOSClient/Main/NCPickerViewController.swift
+  - iOSClient/Main/Section Header Footer/NCSectionHeaderFooter.swift
+  - iOSClient/Media/Cell/NCGridMediaCell.swift
+  - iOSClient/Media/NCMedia.swift
+  - iOSClient/Menu/AppDelegate+Menu.swift
+  - iOSClient/Menu/NCCollectionViewCommon+Menu.swift
+  - iOSClient/Menu/NCLoginWeb+Menu.swift
+  - iOSClient/Menu/NCMedia+Menu.swift
+  - iOSClient/Menu/NCMenu.swift
+  - iOSClient/Menu/NCSortMenu.swift
+  - iOSClient/Menu/NCViewer+Menu.swift
+  - iOSClient/More/NCMore.swift
+  - iOSClient/NCGlobal.swift
+  - iOSClient/Networking/NCAutoUpload.swift
+  - iOSClient/Networking/NCNetworking.swift
+  - iOSClient/Networking/NCNetworkingCheckRemoteUser.swift
+  - iOSClient/Networking/NCNetworkingChunkedUpload.swift
+  - iOSClient/Networking/NCNetworkingE2EE.swift
+  - iOSClient/Networking/NCNetworkingProcessUpload.swift
+  - iOSClient/Networking/NCOperationQueue.swift
+  - iOSClient/Networking/NCService.swift
+  - iOSClient/Notification/NCNotification.swift
+  - iOSClient/Offline/NCOffline.swift
+  - iOSClient/Recent/NCRecent.swift
+  - iOSClient/Rename file/NCRenameFile.swift
+  - iOSClient/RichWorkspace/NCRichWorkspaceCommon.swift
+  - iOSClient/RichWorkspace/NCViewerRichWorkspace.swift
+  - iOSClient/ScanDocument/ScanCollectionView.swift
+  - iOSClient/Security/NCEndToEndMetadata.swift
+  - iOSClient/Security/NCViewCertificateDetails.swift
+  - iOSClient/Select/NCSelect.swift
+  - iOSClient/Settings/NCEndToEndInitialize.swift
+  - iOSClient/Settings/NCManageAutoUploadFileName.swift
+  - iOSClient/Share/NCShare.swift
+  - iOSClient/Share/NCShareCommentsCell.swift
+  - iOSClient/Share/NCShareCommon.swift
+  - iOSClient/Share/NCShareLinkCell.swift
+  - iOSClient/Share/NCShareLinkMenuView.swift
+  - iOSClient/Share/NCShareNetworking.swift
+  - iOSClient/Share/NCSharePaging.swift
+  - iOSClient/Share/NCShareQuickStatusMenu.swift
+  - iOSClient/Share/NCShareUserCell.swift
+  - iOSClient/Share/NCShareUserMenuView.swift
+  - iOSClient/Shares/NCShares.swift
+  - iOSClient/Transfers/NCTransferCell.swift
+  - iOSClient/Transfers/NCTransfers.swift
+  - iOSClient/Trash/Cell/NCTrashListCell.swift
+  - iOSClient/Trash/NCTrash.swift
+  - iOSClient/Trash/Section/NCTrashSectionHeaderFooter.swift
+  - iOSClient/UserStatus/NCUserStatus.swift
+  - iOSClient/Utility/NCAskAuthorization.swift
+  - iOSClient/Utility/NCContentPresenter.swift
+  - iOSClient/Utility/NCLivePhoto.swift
+  - iOSClient/Utility/NCPopupViewController.swift
+  - iOSClient/Utility/NCStoreReview.swift
+  - iOSClient/Utility/NCUtility.swift
+  - iOSClient/Utility/NCUtilityFileSystem.swift
+  - iOSClient/Viewer/NCViewer.swift
+  - iOSClient/Viewer/NCViewerMedia/NCPlayer/NCPlayer.swift
+  - iOSClient/Viewer/NCViewerMedia/NCPlayer/NCPlayerToolBar.swift
+  - iOSClient/Viewer/NCViewerMedia/NCViewerMedia.swift
+  - iOSClient/Viewer/NCViewerMedia/NCViewerMediaDetailView.swift
+  - iOSClient/Viewer/NCViewerMedia/NCViewerMediaPage.swift
+  - iOSClient/Viewer/NCViewerNextcloudText/NCViewerNextcloudText.swift
+  - iOSClient/Viewer/NCViewerPDF/NCViewerPDF.swift
+  - iOSClient/Viewer/NCViewerPDF/NCViewerPDFSearch.swift
+  - iOSClient/Viewer/NCViewerProviderContextMenu.swift
+  - iOSClient/Viewer/NCViewerQuickLook/NCViewerQuickLook.swift
+  - iOSClient/Viewer/NCViewerRichdocument/NCViewerRichdocument.swift
+
+
+reporter: "xcode"

+ 36 - 36
File Provider Extension/FileProviderData.swift

@@ -29,144 +29,144 @@ class fileProviderData: NSObject {
         let instance = fileProviderData()
         return instance
     }()
-        
+
     var domain: NSFileProviderDomain?
     var fileProviderManager: NSFileProviderManager = NSFileProviderManager.default
-    
+
     var account = ""
     var user = ""
     var userId = ""
     var accountUrlBase = ""
     var homeServerUrl = ""
-        
+
     // Max item for page
     let itemForPage = 100
-    
+
     // Anchor
     var currentAnchor: UInt64 = 0
 
     // Rank favorite
     var listFavoriteIdentifierRank: [String: NSNumber] = [:]
-    
+
     // Item for signalEnumerator
     var fileProviderSignalDeleteContainerItemIdentifier: [NSFileProviderItemIdentifier: NSFileProviderItemIdentifier] = [:]
     var fileProviderSignalUpdateContainerItem: [NSFileProviderItemIdentifier: FileProviderItem] = [:]
     var fileProviderSignalDeleteWorkingSetItemIdentifier: [NSFileProviderItemIdentifier: NSFileProviderItemIdentifier] = [:]
     var fileProviderSignalUpdateWorkingSetItem: [NSFileProviderItemIdentifier: FileProviderItem] = [:]
-       
+
     // Error
     enum FileProviderError: Error {
         case downloadError
         case uploadError
     }
-    
+
     // MARK: - 
-    
+
     func setupAccount(domain: NSFileProviderDomain?, providerExtension: NSFileProviderExtension) -> tableAccount? {
-                
+
         if CCUtility.getDisableFilesApp() || NCBrandOptions.shared.disable_openin_file {
             return nil
         }
-        
+
         self.domain = domain
         if domain != nil {
-            if let fileProviderManager = NSFileProviderManager.init(for: domain!) {
+            if let fileProviderManager = NSFileProviderManager(for: domain!) {
                 self.fileProviderManager = fileProviderManager
             }
         }
-        
+
         // LOG
         if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
             NCCommunicationCommon.shared.pathLog = pathDirectoryGroup
             let levelLog = CCUtility.getLogLevel()
             NCCommunicationCommon.shared.levelLog = levelLog
-            let version = NSString(format:NCBrandOptions.shared.textCopyrightNextcloudiOS as NSString, NCUtility.shared.getVersionApp()) as String
+            let version = NSString(format: NCBrandOptions.shared.textCopyrightNextcloudiOS as NSString, NCUtility.shared.getVersionApp()) as String
             NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + version + " (File Provider Extension)")
         }
-        
+
         // NO DOMAIN -> Set default account
         if domain == nil {
-            
+
             guard let activeAccount = NCManageDatabase.shared.getActiveAccount() else { return nil }
             let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: activeAccount.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
             let webDav = NCUtilityFileSystem.shared.getWebDAV(account: activeAccount.account)
-            
+
             account = activeAccount.account
             user = activeAccount.user
             userId = activeAccount.userId
             accountUrlBase = activeAccount.urlBase
             homeServerUrl = NCUtilityFileSystem.shared.getHomeServer(account: activeAccount.account)
-                        
+
             NCCommunicationCommon.shared.setup(account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account), urlBase: activeAccount.urlBase, userAgent: CCUtility.getUserAgent(), webDav: webDav, nextcloudVersion: serverVersionMajor, delegate: NCNetworking.shared)
             NCNetworking.shared.delegate = providerExtension as? NCNetworkingDelegate
-            
+
             return tableAccount.init(value: activeAccount)
         }
-        
+
         // DOMAIN
         let accounts = NCManageDatabase.shared.getAllAccount()
         if accounts.count == 0 { return nil }
-        
+
         for activeAccount in accounts {
             guard let url = NSURL(string: activeAccount.urlBase) else { continue }
             guard let host = url.host else { continue }
             let accountDomain = activeAccount.userId + " (" + host + ")"
             if accountDomain == domain!.identifier.rawValue {
-                
+
                 let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: activeAccount.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
                 let webDav = NCUtilityFileSystem.shared.getWebDAV(account: activeAccount.account)
-                
+
                 account = activeAccount.account
                 user = activeAccount.user
                 userId = activeAccount.userId
                 accountUrlBase = activeAccount.urlBase
                 homeServerUrl = NCUtilityFileSystem.shared.getHomeServer(account: activeAccount.account)
-                
-                NCCommunicationCommon.shared.setup(account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account), urlBase: activeAccount.urlBase, userAgent: CCUtility.getUserAgent(), webDav: webDav,  nextcloudVersion: serverVersionMajor, delegate: NCNetworking.shared)
+
+                NCCommunicationCommon.shared.setup(account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account), urlBase: activeAccount.urlBase, userAgent: CCUtility.getUserAgent(), webDav: webDav, nextcloudVersion: serverVersionMajor, delegate: NCNetworking.shared)
                 NCNetworking.shared.delegate = providerExtension as? NCNetworkingDelegate
 
                 return tableAccount.init(value: activeAccount)
             }
         }
-        
+
         return nil
     }
-        
+
     // MARK: -
 
     @discardableResult
     func signalEnumerator(ocId: String, delete: Bool = false, update: Bool = false) -> FileProviderItem? {
-        
+
         guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return nil }
-                
+
         guard let parentItemIdentifier = fileProviderUtility.shared.getParentItemIdentifier(metadata: metadata) else { return nil }
-        
+
         let item = FileProviderItem(metadata: metadata, parentItemIdentifier: parentItemIdentifier)
-        
+
         if delete {
             fileProviderData.shared.fileProviderSignalDeleteContainerItemIdentifier[item.itemIdentifier] = item.itemIdentifier
             fileProviderData.shared.fileProviderSignalDeleteWorkingSetItemIdentifier[item.itemIdentifier] = item.itemIdentifier
         }
-        
+
         if update {
             fileProviderData.shared.fileProviderSignalUpdateContainerItem[item.itemIdentifier] = item
             fileProviderData.shared.fileProviderSignalUpdateWorkingSetItem[item.itemIdentifier] = item
         }
-        
+
         if !update && !delete {
             fileProviderData.shared.fileProviderSignalUpdateWorkingSetItem[item.itemIdentifier] = item
         }
-        
+
         if update || delete {
             currentAnchor += 1
             fileProviderManager.signalEnumerator(for: parentItemIdentifier) { _ in }
         }
-        
+
         fileProviderManager.signalEnumerator(for: .workingSet) { _ in }
-        
+
         return item
     }
-    
+
     /*
      func updateFavoriteForWorkingSet() {
          

+ 13 - 13
File Provider Extension/FileProviderDomain.swift

@@ -24,19 +24,19 @@
 import UIKit
 
 class FileProviderDomain: NSObject {
-    
+
     func registerDomains() {
-        
-        NSFileProviderManager.getDomainsWithCompletionHandler { (fileProviderDomain, error) in
-            
-            var domains:[String] = []
+
+        NSFileProviderManager.getDomainsWithCompletionHandler { fileProviderDomain, error in
+
+            var domains: [String] = []
             let pathRelativeToDocumentStorage = NSFileProviderManager.default.documentStorageURL.absoluteString
             let accounts = NCManageDatabase.shared.getAllAccount()
-            
+
             for domain in fileProviderDomain {
                 domains.append(domain.identifier.rawValue)
             }
-            
+
             // Delete
             for domain in domains {
                 var domainFound = false
@@ -51,14 +51,14 @@ class FileProviderDomain: NSObject {
                 }
                 if !domainFound {
                     let domainRawValue = NSFileProviderDomain(identifier: NSFileProviderDomainIdentifier(rawValue: domain), displayName: domain, pathRelativeToDocumentStorage: pathRelativeToDocumentStorage)
-                    NSFileProviderManager.remove(domainRawValue, completionHandler: { (error) in
+                    NSFileProviderManager.remove(domainRawValue, completionHandler: { error in
                         if error != nil {
                             print("Error  domain: \(domainRawValue) error: \(String(describing: error))")
                         }
                     })
                 }
             }
-            
+
             // Add
             for account in accounts {
                 var domainFound = false
@@ -73,7 +73,7 @@ class FileProviderDomain: NSObject {
                 }
                 if !domainFound {
                     let domainRawValue = NSFileProviderDomain(identifier: NSFileProviderDomainIdentifier(rawValue: accountDomain), displayName: accountDomain, pathRelativeToDocumentStorage: pathRelativeToDocumentStorage)
-                    NSFileProviderManager.add(domainRawValue, completionHandler: { (error) in
+                    NSFileProviderManager.add(domainRawValue, completionHandler: { error in
                         if error != nil {
                             print("Error  domain: \(domainRawValue) error: \(String(describing: error))")
                         }
@@ -82,9 +82,9 @@ class FileProviderDomain: NSObject {
             }
         }
     }
-    
+
     func removeAllDomains() {
-        
-        NSFileProviderManager.removeAllDomains { (_) in }
+
+        NSFileProviderManager.removeAllDomains { _ in }
     }
 }

+ 55 - 55
File Provider Extension/FileProviderEnumerator.swift

@@ -26,60 +26,60 @@ import FileProvider
 import NCCommunication
 
 class FileProviderEnumerator: NSObject, NSFileProviderEnumerator {
-    
+
     var enumeratedItemIdentifier: NSFileProviderItemIdentifier
     var serverUrl: String?
-    
+
     init(enumeratedItemIdentifier: NSFileProviderItemIdentifier) {
-        
+
         self.enumeratedItemIdentifier = enumeratedItemIdentifier
-        
+
         // Select ServerUrl
-        if (enumeratedItemIdentifier == .rootContainer) {
+        if enumeratedItemIdentifier == .rootContainer {
             serverUrl = fileProviderData.shared.homeServerUrl
         } else {
-            
+
             let metadata = fileProviderUtility.shared.getTableMetadataFromItemIdentifier(enumeratedItemIdentifier)
-            if metadata != nil  {
-                if let directorySource = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata!.account, metadata!.serverUrl))  {
+            if metadata != nil {
+                if let directorySource = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata!.account, metadata!.serverUrl)) {
                     serverUrl = directorySource.serverUrl + "/" + metadata!.fileName
                 }
             }
         }
-        
+
         super.init()
     }
 
     func invalidate() {
-       
+
     }
 
     func enumerateItems(for observer: NSFileProviderEnumerationObserver, startingAt page: NSFileProviderPage) {
-        
+
         var items: [NSFileProviderItemProtocol] = []
-        
+
         /*** WorkingSet ***/
         if enumeratedItemIdentifier == .workingSet {
-            
+
             var itemIdentifierMetadata: [NSFileProviderItemIdentifier: tableMetadata] = [:]
-            
+
             // ***** Tags *****
             let tags = NCManageDatabase.shared.getTags(predicate: NSPredicate(format: "account == %@", fileProviderData.shared.account))
             for tag in tags {
-                
+
                 guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(tag.ocId)  else { continue }
                 fileProviderUtility.shared.createocIdentifierOnFileSystem(metadata: metadata)
                 itemIdentifierMetadata[fileProviderUtility.shared.getItemIdentifier(metadata: metadata)] = metadata
             }
-            
+
             // ***** Favorite *****
             fileProviderData.shared.listFavoriteIdentifierRank = NCManageDatabase.shared.getTableMetadatasDirectoryFavoriteIdentifierRank(account: fileProviderData.shared.account)
             for (identifier, _) in fileProviderData.shared.listFavoriteIdentifierRank {
-                
+
                 guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(identifier) else { continue }
                 itemIdentifierMetadata[fileProviderUtility.shared.getItemIdentifier(metadata: metadata)] = metadata
             }
-            
+
             // create items
             for (_, metadata) in itemIdentifierMetadata {
                 let parentItemIdentifier = fileProviderUtility.shared.getParentItemIdentifier(metadata: metadata)
@@ -88,38 +88,38 @@ class FileProviderEnumerator: NSObject, NSFileProviderEnumerator {
                     items.append(item)
                 }
             }
-            
+
             observer.didEnumerate(items)
             observer.finishEnumerating(upTo: nil)
-            
+
         } else {
-        
+
         /*** ServerUrl ***/
-                
+
             guard let serverUrl = serverUrl else {
                 observer.finishEnumerating(upTo: nil)
                 return
             }
-            
-            if (page == NSFileProviderPage.initialPageSortedByDate as NSFileProviderPage || page == NSFileProviderPage.initialPageSortedByName as NSFileProviderPage) {
-                
-                self.readFileOrFolder(serverUrl: serverUrl) { (metadatas) in
+
+            if page == NSFileProviderPage.initialPageSortedByDate as NSFileProviderPage || page == NSFileProviderPage.initialPageSortedByName as NSFileProviderPage {
+
+                self.readFileOrFolder(serverUrl: serverUrl) { metadatas in
                     self.completeObserver(observer, numPage: 1, metadatas: metadatas)
                 }
-                
+
             } else {
-                
+
                 let numPage = Int(String(data: page.rawValue, encoding: .utf8)!)!
                 completeObserver(observer, numPage: numPage, metadatas: nil)
             }
         }
     }
-    
+
     func enumerateChanges(for observer: NSFileProviderChangeObserver, from anchor: NSFileProviderSyncAnchor) {
-        
+
         var itemsDelete: [NSFileProviderItemIdentifier] = []
         var itemsUpdate: [FileProviderItem] = []
-        
+
         // Report the deleted items
         //
         if self.enumeratedItemIdentifier == .workingSet {
@@ -133,7 +133,7 @@ class FileProviderEnumerator: NSObject, NSFileProviderEnumerator {
             }
             fileProviderData.shared.fileProviderSignalDeleteContainerItemIdentifier.removeAll()
         }
-        
+
         // Report the updated items
         //
         if self.enumeratedItemIdentifier == .workingSet {
@@ -147,36 +147,36 @@ class FileProviderEnumerator: NSObject, NSFileProviderEnumerator {
             }
             fileProviderData.shared.fileProviderSignalUpdateContainerItem.removeAll()
         }
-        
+
         observer.didDeleteItems(withIdentifiers: itemsDelete)
         observer.didUpdate(itemsUpdate)
-        
+
         let data = "\(fileProviderData.shared.currentAnchor)".data(using: .utf8)
         observer.finishEnumeratingChanges(upTo: NSFileProviderSyncAnchor(data!), moreComing: false)
     }
-    
+
     func currentSyncAnchor(completionHandler: @escaping (NSFileProviderSyncAnchor?) -> Void) {
         let data = "\(fileProviderData.shared.currentAnchor)".data(using: .utf8)
         completionHandler(NSFileProviderSyncAnchor(data!))
     }
-    
+
     // --------------------------------------------------------------------------------------------
-    //  MARK: - User Function + Network
+    // MARK: - User Function + Network
     // --------------------------------------------------------------------------------------------
 
     func completeObserver(_ observer: NSFileProviderEnumerationObserver, numPage: Int, metadatas: [tableMetadata]?) {
-            
+
         var numPage = numPage
         var items: [NSFileProviderItemProtocol] = []
 
-        if (metadatas != nil) {
-            
+        if metadatas != nil {
+
             for metadata in metadatas! {
-                    
+
                 if metadata.e2eEncrypted || (metadata.session != "" && metadata.session != NCNetworking.shared.sessionIdentifierBackgroundExtension) { continue }
-                    
+
                 fileProviderUtility.shared.createocIdentifierOnFileSystem(metadata: metadata)
-                        
+
                 let parentItemIdentifier = fileProviderUtility.shared.getParentItemIdentifier(metadata: metadata)
                 if parentItemIdentifier != nil {
                     let item = FileProviderItem(metadata: metadata, parentItemIdentifier: parentItemIdentifier!)
@@ -185,8 +185,8 @@ class FileProviderEnumerator: NSObject, NSFileProviderEnumerator {
             }
             observer.didEnumerate(items)
         }
-        
-        if (items.count == fileProviderData.shared.itemForPage) {
+
+        if items.count == fileProviderData.shared.itemForPage {
             numPage += 1
             let providerPage = NSFileProviderPage("\(numPage)".data(using: .utf8)!)
             observer.finishEnumerating(upTo: providerPage)
@@ -194,24 +194,24 @@ class FileProviderEnumerator: NSObject, NSFileProviderEnumerator {
             observer.finishEnumerating(upTo: nil)
         }
     }
-        
+
     func readFileOrFolder(serverUrl: String, completionHandler: @escaping (_ metadatas: [tableMetadata]?) -> Void) {
-        
+
         var directoryEtag: String?
-        
+
         if let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", fileProviderData.shared.account, serverUrl)) {
             directoryEtag = tableDirectory.etag
         }
-            
-        NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
-        
+
+        NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { account, files, _, errorCode, _ in
+
             if directoryEtag != files.first?.etag {
-            
-                NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
-                    
+
+                NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: CCUtility.getShowHiddenFiles()) { account, files, _, errorCode, _ in
+
                     if errorCode == 0 {
                         DispatchQueue.global().async {
-                            NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: true, account: account) { (metadataFolder, metadatasFolder, metadatas) in
+                            NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: true, account: account) { _, metadatasFolder, metadatas in
                                 let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", account, serverUrl, NCGlobal.shared.metadataStatusNormal))
                                 NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult)
                                 for metadata in metadatasFolder {

+ 85 - 85
File Provider Extension/FileProviderExtension+Actions.swift

@@ -28,85 +28,85 @@ import NCCommunication
 extension FileProviderExtension {
 
     override func createDirectory(withName directoryName: String, inParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
-        
+
         guard let tableDirectory = fileProviderUtility.shared.getTableDirectoryFromParentItemIdentifier(parentItemIdentifier, account: fileProviderData.shared.account, homeServerUrl: fileProviderData.shared.homeServerUrl) else {
             completionHandler(nil, NSFileProviderError(.noSuchItem))
             return
         }
-        
+
         let directoryName = NCUtilityFileSystem.shared.createFileName(directoryName, serverUrl: tableDirectory.serverUrl, account: fileProviderData.shared.account)
         let serverUrlFileName = tableDirectory.serverUrl + "/" + directoryName
-        
-        NCCommunication.shared.createFolder(serverUrlFileName) { (account, ocId, date, errorCode, errorDescription) in
-                        
+
+        NCCommunication.shared.createFolder(serverUrlFileName) { account, ocId, _, errorCode, _ in
+
             if errorCode == 0 {
-                
-                NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
-                    
+
+                NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { account, files, _, errorCode, _ in
+
                     if errorCode == 0 && files.count > 0 {
-                        
+
                         let file = files.first!
                         let metadata = NCManageDatabase.shared.convertNCFileToMetadata(file, isEncrypted: false, account: fileProviderData.shared.account)
-            
+
                         NCManageDatabase.shared.addDirectory(encrypted: false, favorite: false, ocId: ocId!, fileId: metadata.fileId, etag: metadata.etag, permissions: metadata.permissions, serverUrl: serverUrlFileName, account: metadata.account)
                         NCManageDatabase.shared.addMetadata(metadata)
-                        
+
                         guard let metadataInsert = NCManageDatabase.shared.getMetadataFromOcId(ocId!) else {
                             completionHandler(nil, NSFileProviderError(.noSuchItem))
                             return
                         }
-                        
+
                         guard let parentItemIdentifier = fileProviderUtility.shared.getParentItemIdentifier(metadata: metadataInsert) else {
                             completionHandler(nil, NSFileProviderError(.noSuchItem))
                             return
                         }
-                     
+
                         let item = FileProviderItem(metadata: metadataInsert, parentItemIdentifier: parentItemIdentifier)
                         completionHandler(item, nil)
-                        
+
                     } else {
                         completionHandler(nil, NSFileProviderError(.serverUnreachable))
                     }
                 }
-                
+
             } else {
                 completionHandler(nil, NSFileProviderError(.serverUnreachable))
             }
         }
     }
-    
+
     override func deleteItem(withIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (Error?) -> Void) {
-        
+
         guard let metadata = fileProviderUtility.shared.getTableMetadataFromItemIdentifier(itemIdentifier) else {
             completionHandler(NSFileProviderError(.noSuchItem))
             return
         }
-        
+
         let ocId = metadata.ocId
         let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
         let isDirectory = metadata.directory
-        let serverUrl = metadata.serverUrl;
-        let fileName = metadata.fileName;
-        
-        NCCommunication.shared.deleteFileOrFolder(serverUrlFileName) { (account, errorCode, errorDescription) in
-            
-            if errorCode == 0 { //|| error == kOCErrorServerPathNotFound {
-            
+        let serverUrl = metadata.serverUrl
+        let fileName = metadata.fileName
+
+        NCCommunication.shared.deleteFileOrFolder(serverUrlFileName) { account, errorCode, _ in
+
+            if errorCode == 0 { // || error == kOCErrorServerPathNotFound {
+
                 let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(itemIdentifier.rawValue)!
                 do {
                     try fileProviderUtility.shared.fileManager.removeItem(atPath: fileNamePath)
                 } catch let error {
                     print("error: \(error)")
                 }
-                
+
                 if isDirectory {
                     let dirForDelete = CCUtility.stringAppendServerUrl(serverUrl, addFileName: fileName)
                     NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: dirForDelete!, account: account)
                 }
-                
+
                 NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocId))
                 NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", ocId))
-                
+
                 completionHandler(nil)
 
             } else {
@@ -114,126 +114,126 @@ extension FileProviderExtension {
             }
         }
     }
-    
+
     override func reparentItem(withIdentifier itemIdentifier: NSFileProviderItemIdentifier, toParentItemWithIdentifier parentItemIdentifier: NSFileProviderItemIdentifier, newName: String?, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
-        
+
         guard let itemFrom = try? item(for: itemIdentifier) else {
             completionHandler(nil, NSFileProviderError(.noSuchItem))
             return
         }
-        
+
         guard let metadataFrom = fileProviderUtility.shared.getTableMetadataFromItemIdentifier(itemIdentifier) else {
             completionHandler(nil, NSFileProviderError(.noSuchItem))
             return
         }
-        
+
         let ocIdFrom = metadataFrom.ocId
         let serverUrlFrom = metadataFrom.serverUrl
         let fileNameFrom = serverUrlFrom + "/" + itemFrom.filename
-        
+
         guard let tableDirectoryTo = fileProviderUtility.shared.getTableDirectoryFromParentItemIdentifier(parentItemIdentifier, account: fileProviderData.shared.account, homeServerUrl: fileProviderData.shared.homeServerUrl) else {
             completionHandler(nil, NSFileProviderError(.noSuchItem))
             return
         }
         let serverUrlTo = tableDirectoryTo.serverUrl
         let fileNameTo = serverUrlTo + "/" + itemFrom.filename
-        
-        NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNameFrom, serverUrlFileNameDestination: fileNameTo, overwrite: false) { (account, errorCode, errorDescription) in
-       
+
+        NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNameFrom, serverUrlFileNameDestination: fileNameTo, overwrite: false) { account, errorCode, _ in
+
             if errorCode == 0 {
-                
+
                 if metadataFrom.directory {
                     NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: serverUrlFrom, account: account)
-                    NCManageDatabase.shared.renameDirectory(ocId: ocIdFrom, serverUrl: serverUrlTo)                    
+                    NCManageDatabase.shared.renameDirectory(ocId: ocIdFrom, serverUrl: serverUrlTo)
                 }
-                
+
                 NCManageDatabase.shared.moveMetadata(ocId: ocIdFrom, serverUrlTo: serverUrlTo)
-                
+
                 guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocIdFrom) else {
                     completionHandler(nil, NSFileProviderError(.noSuchItem))
                     return
                 }
-                
+
                 let item = FileProviderItem(metadata: metadata, parentItemIdentifier: parentItemIdentifier)
                 completionHandler(item, nil)
-                
+
             } else {
                 completionHandler(nil, NSFileProviderError(.serverUnreachable))
             }
         }
     }
-    
+
     override func renameItem(withIdentifier itemIdentifier: NSFileProviderItemIdentifier, toName itemName: String, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
-        
+
         guard let metadata = fileProviderUtility.shared.getTableMetadataFromItemIdentifier(itemIdentifier) else {
             completionHandler(nil, NSFileProviderError(.noSuchItem))
             return
         }
-        
+
         guard let directoryTable = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) else {
             completionHandler(nil, NSFileProviderError(.noSuchItem))
             return
         }
-        
+
         let fileNameFrom = metadata.fileNameView
         let fileNamePathFrom = metadata.serverUrl + "/" + fileNameFrom
         let fileNamePathTo = metadata.serverUrl + "/" + itemName
         let ocId = metadata.ocId
-        
-        NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNamePathFrom, serverUrlFileNameDestination: fileNamePathTo, overwrite: false) { (account, errorCode, errorDescription) in
-       
+
+        NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNamePathFrom, serverUrlFileNameDestination: fileNamePathTo, overwrite: false) { account, errorCode, _ in
+
             if errorCode == 0 {
-                
+
                 // Rename metadata
                 NCManageDatabase.shared.renameMetadata(fileNameTo: itemName, ocId: ocId)
-                
+
                 guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else {
                     completionHandler(nil, NSFileProviderError(.noSuchItem))
                     return
                 }
-                
+
                 if metadata.directory {
-                    
+
                     NCManageDatabase.shared.setDirectory(serverUrl: fileNamePathFrom, serverUrlTo: fileNamePathTo, etag: nil, ocId: nil, fileId: nil, encrypted: directoryTable.e2eEncrypted, richWorkspace: nil, account: account)
-                    
+
                 } else {
-                    
+
                     let itemIdentifier = fileProviderUtility.shared.getItemIdentifier(metadata: metadata)
-                    
+
                     // rename file
                     _ = fileProviderUtility.shared.moveFile(CCUtility.getDirectoryProviderStorageOcId(itemIdentifier.rawValue, fileNameView: fileNameFrom), toPath: CCUtility.getDirectoryProviderStorageOcId(itemIdentifier.rawValue, fileNameView: itemName))
-                    
+
                     _ = fileProviderUtility.shared.moveFile(CCUtility.getDirectoryProviderStoragePreviewOcId(itemIdentifier.rawValue, etag: metadata.etag), toPath: CCUtility.getDirectoryProviderStoragePreviewOcId(itemIdentifier.rawValue, etag: metadata.etag))
-                    
+
                     _ = fileProviderUtility.shared.moveFile(CCUtility.getDirectoryProviderStorageIconOcId(itemIdentifier.rawValue, etag: metadata.etag), toPath: CCUtility.getDirectoryProviderStorageIconOcId(itemIdentifier.rawValue, etag: metadata.etag))
-                    
+
                     NCManageDatabase.shared.setLocalFile(ocId: ocId, fileName: itemName, etag: nil)
                 }
-                
+
                 guard let parentItemIdentifier = fileProviderUtility.shared.getParentItemIdentifier(metadata: metadata) else {
                     completionHandler(nil, NSFileProviderError(.noSuchItem))
                     return
                 }
-                
+
                 let item = FileProviderItem(metadata: tableMetadata.init(value: metadata), parentItemIdentifier: parentItemIdentifier)
                 completionHandler(item, nil)
-                
+
             } else {
                 completionHandler(nil, NSFileProviderError(.serverUnreachable))
             }
         }
     }
-    
+
     override func setFavoriteRank(_ favoriteRank: NSNumber?, forItemIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
-        
+
         guard let metadata = fileProviderUtility.shared.getTableMetadataFromItemIdentifier(itemIdentifier) else {
             completionHandler(nil, NSFileProviderError(.noSuchItem))
             return
         }
-        
+
         var favorite = false
         let ocId = metadata.ocId
-        
+
         if favoriteRank == nil {
             fileProviderData.shared.listFavoriteIdentifierRank.removeValue(forKey: itemIdentifier.rawValue)
         } else {
@@ -243,72 +243,72 @@ extension FileProviderExtension {
             }
             favorite = true
         }
-        
+
         if (favorite == true && metadata.favorite == false) || (favorite == false && metadata.favorite == true) {
             let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, account: metadata.account)!
-            
-            NCCommunication.shared.setFavorite(fileName: fileNamePath, favorite: favorite) { (account, errorCode, errorDescription) in
-                
+
+            NCCommunication.shared.setFavorite(fileName: fileNamePath, favorite: favorite) { _, errorCode, _ in
+
                 if errorCode == 0 {
-                    
+
                     guard let metadataTemp = NCManageDatabase.shared.getMetadataFromOcId(ocId) else {
                         completionHandler(nil, NSFileProviderError(.noSuchItem))
                         return
                     }
                     let metadata = tableMetadata.init(value: metadataTemp)
-                    
+
                     // Change DB
                     metadata.favorite = favorite
                     NCManageDatabase.shared.addMetadata(metadata)
-                    
+
                     let item = fileProviderData.shared.signalEnumerator(ocId: metadata.ocId)
                     completionHandler(item, nil)
-                    
+
                 } else {
-                    
+
                     guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else {
                         completionHandler(nil, NSFileProviderError(.noSuchItem))
                         return
                     }
-                    
+
                     // Errore, remove from listFavoriteIdentifierRank
                     fileProviderData.shared.listFavoriteIdentifierRank.removeValue(forKey: itemIdentifier.rawValue)
-                    
+
                     let item = fileProviderData.shared.signalEnumerator(ocId: metadata.ocId)
                     completionHandler(item, NSFileProviderError(.serverUnreachable))
                 }
             }
         }
     }
-    
+
     override func setTagData(_ tagData: Data?, forItemIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
-        
+
         guard let metadataForTag = fileProviderUtility.shared.getTableMetadataFromItemIdentifier(itemIdentifier) else {
             completionHandler(nil, NSFileProviderError(.noSuchItem))
             return
         }
         let ocId = metadataForTag.ocId
         let account = metadataForTag.account
-        
+
         // Add, Remove (nil)
         NCManageDatabase.shared.addTag(ocId, tagIOS: tagData, account: account)
-        
+
         let item = fileProviderData.shared.signalEnumerator(ocId: ocId)
         completionHandler(item, nil)
     }
-    
+
     override func setLastUsedDate(_ lastUsedDate: Date?, forItemIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
-        
+
         guard let metadata = fileProviderUtility.shared.getTableMetadataFromItemIdentifier(itemIdentifier) else {
             completionHandler(nil, NSFileProviderError(.noSuchItem))
             return
         }
-        
+
         guard let parentItemIdentifier = fileProviderUtility.shared.getParentItemIdentifier(metadata: metadata) else {
             completionHandler(nil, NSFileProviderError(.noSuchItem))
             return
         }
-        
+
         let item = FileProviderItem(metadata: metadata, parentItemIdentifier: parentItemIdentifier)
         completionHandler(item, nil)
     }

+ 14 - 14
File Provider Extension/FileProviderExtension+Thumbnail.swift

@@ -28,46 +28,46 @@ import NCCommunication
 extension FileProviderExtension {
 
     override func fetchThumbnails(for itemIdentifiers: [NSFileProviderItemIdentifier], requestedSize size: CGSize, perThumbnailCompletionHandler: @escaping (NSFileProviderItemIdentifier, Data?, Error?) -> Void, completionHandler: @escaping (Error?) -> Void) -> Progress {
-                
+
         let progress = Progress(totalUnitCount: Int64(itemIdentifiers.count))
         var counterProgress: Int64 = 0
-        
+
         for itemIdentifier in itemIdentifiers {
-            
+
             guard let metadata = fileProviderUtility.shared.getTableMetadataFromItemIdentifier(itemIdentifier) else {
                 counterProgress += 1
-                if (counterProgress == progress.totalUnitCount) { completionHandler(nil) }
+                if counterProgress == progress.totalUnitCount { completionHandler(nil) }
                 continue
             }
-            
-            if (metadata.hasPreview) {
-                
+
+            if metadata.hasPreview {
+
                 let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, account: metadata.account)!
                 let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
-                    
-                NCCommunication.shared.getPreview(fileNamePath: fileNamePath, widthPreview: NCGlobal.shared.sizeIcon, heightPreview: NCGlobal.shared.sizeIcon) { (account, data, errorCode, errorDescription) in
+
+                NCCommunication.shared.getPreview(fileNamePath: fileNamePath, widthPreview: NCGlobal.shared.sizeIcon, heightPreview: NCGlobal.shared.sizeIcon) { _, data, errorCode, _ in
                     if errorCode == 0 && data != nil {
                         do {
-                            try data!.write(to: URL.init(fileURLWithPath: fileNameIconLocalPath), options: .atomic)
+                            try data!.write(to: URL(fileURLWithPath: fileNameIconLocalPath), options: .atomic)
                         } catch { }
                         perThumbnailCompletionHandler(itemIdentifier, data, nil)
                     } else {
                         perThumbnailCompletionHandler(itemIdentifier, nil, NSFileProviderError(.serverUnreachable))
                     }
                     counterProgress += 1
-                    if (counterProgress == progress.totalUnitCount) {
+                    if counterProgress == progress.totalUnitCount {
                         completionHandler(nil)
                     }
                 }
             } else {
                 counterProgress += 1
-                if (counterProgress == progress.totalUnitCount) {
+                if counterProgress == progress.totalUnitCount {
                     completionHandler(nil)
                 }
             }
         }
-        
+
         return progress
     }
-    
+
 }

+ 113 - 116
File Provider Extension/FileProviderExtension.swift

@@ -52,67 +52,67 @@ import Alamofire
    -------------------------------------------------------------------------------------------------------------------------------------------- */
 
 class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate {
-    
+
     var outstandingSessionTasks: [URL: URLSessionTask] = [:]
     var outstandingOcIdTemp: [String: String] = [:]
-    
+
     override init() {
         super.init()
-        
+
         // Create directory File Provider Storage
         CCUtility.getDirectoryProviderStorage()
         // Configure URLSession
         _ = NCNetworking.shared.sessionManagerBackgroundExtension
     }
-    
+
     deinit {
         print("")
     }
-    
+
     // MARK: - Enumeration
-    
+
     override func enumerator(for containerItemIdentifier: NSFileProviderItemIdentifier) throws -> NSFileProviderEnumerator {
-        
-        var maybeEnumerator: NSFileProviderEnumerator? = nil
-        
-        if (containerItemIdentifier != NSFileProviderItemIdentifier.workingSet) {
+
+        var maybeEnumerator: NSFileProviderEnumerator?
+
+        if containerItemIdentifier != NSFileProviderItemIdentifier.workingSet {
             if fileProviderData.shared.setupAccount(domain: domain, providerExtension: self) == nil {
-                throw NSError(domain: NSFileProviderErrorDomain, code: NSFileProviderError.notAuthenticated.rawValue, userInfo:[:])
+                throw NSError(domain: NSFileProviderErrorDomain, code: NSFileProviderError.notAuthenticated.rawValue, userInfo: [:])
             }
         }
-        
-        if (containerItemIdentifier == NSFileProviderItemIdentifier.rootContainer) {
+
+        if containerItemIdentifier == NSFileProviderItemIdentifier.rootContainer {
             maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier)
-        } else if (containerItemIdentifier == NSFileProviderItemIdentifier.workingSet) {
+        } else if containerItemIdentifier == NSFileProviderItemIdentifier.workingSet {
             maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier)
         } else {
             // determine if the item is a directory or a file
             // - for a directory, instantiate an enumerator of its subitems
             // - for a file, instantiate an enumerator that observes changes to the file
             let item = try self.item(for: containerItemIdentifier)
-            
+
             if item.typeIdentifier == kUTTypeFolder as String {
                 maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier)
             } else {
                 maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier)
             }
         }
-        
+
         guard let enumerator = maybeEnumerator else {
-            throw NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError, userInfo:[:])
+            throw NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError, userInfo: [:])
         }
-        
+
         return enumerator
     }
-    
+
     // MARK: - Item
 
     override func item(for identifier: NSFileProviderItemIdentifier) throws -> NSFileProviderItem {
-        
+
         if identifier == .rootContainer {
-            
+
             let metadata = tableMetadata()
-            
+
             metadata.account = fileProviderData.shared.account
             metadata.directory = true
             metadata.ocId = NSFileProviderItemIdentifier.rootContainer.rawValue
@@ -120,11 +120,11 @@ class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate {
             metadata.fileNameView = "root"
             metadata.serverUrl = fileProviderData.shared.homeServerUrl
             metadata.classFile = NCCommunicationCommon.typeClassFile.directory.rawValue
-            
+
             return FileProviderItem(metadata: metadata, parentItemIdentifier: NSFileProviderItemIdentifier(NSFileProviderItemIdentifier.rootContainer.rawValue))
-            
+
         } else {
-            
+
             guard let metadata = fileProviderUtility.shared.getTableMetadataFromItemIdentifier(identifier) else {
                 throw NSFileProviderError(.noSuchItem)
             }
@@ -135,46 +135,46 @@ class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate {
             return item
         }
     }
-    
+
     override func urlForItem(withPersistentIdentifier identifier: NSFileProviderItemIdentifier) -> URL? {
-        
+
         // resolve the given identifier to a file on disk
         guard let item = try? item(for: identifier) else {
             return nil
         }
-                
+
         var url = fileProviderData.shared.fileProviderManager.documentStorageURL.appendingPathComponent(identifier.rawValue, isDirectory: true)
-        
+
         // (fix copy/paste directory -> isDirectory = false)
-        url = url.appendingPathComponent(item.filename, isDirectory:false)
-    
+        url = url.appendingPathComponent(item.filename, isDirectory: false)
+
         return url
     }
-    
+
     override func persistentIdentifierForItem(at url: URL) -> NSFileProviderItemIdentifier? {
-        
+
         // resolve the given URL to a persistent identifier using a database
         let pathComponents = url.pathComponents
-        
+
         // exploit the fact that the path structure has been defined as
         // <base storage directory>/<item identifier>/<item file name> above
         assert(pathComponents.count > 2)
-        
+
         let itemIdentifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
         return itemIdentifier
     }
-        
+
     override func providePlaceholder(at url: URL, completionHandler: @escaping (Error?) -> Void) {
-        
+
         guard let identifier = persistentIdentifierForItem(at: url) else {
             completionHandler(NSFileProviderError(.noSuchItem))
             return
         }
-        
+
         do {
             let fileProviderItem = try item(for: identifier)
             let placeholderURL = NSFileProviderManager.placeholderURL(for: url)
-            try NSFileProviderManager.writePlaceholder(at: placeholderURL,withMetadata: fileProviderItem)
+            try NSFileProviderManager.writePlaceholder(at: placeholderURL, withMetadata: fileProviderItem)
             completionHandler(nil)
         } catch {
             completionHandler(error)
@@ -182,89 +182,89 @@ class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate {
     }
 
     override func startProvidingItem(at url: URL, completionHandler: @escaping ((_ error: Error?) -> Void)) {
-        
+
         let pathComponents = url.pathComponents
         let identifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
-        
+
         if let _ = outstandingSessionTasks[url] {
             completionHandler(nil)
             return
         }
-        
+
         guard let metadata = fileProviderUtility.shared.getTableMetadataFromItemIdentifier(identifier) else {
             completionHandler(NSFileProviderError(.noSuchItem))
             return
         }
-        
+
         let tableLocalFile = NCManageDatabase.shared.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
-        if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) && tableLocalFile?.etag == metadata.etag  {
+        if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) && tableLocalFile?.etag == metadata.etag {
             completionHandler(nil)
             return
         }
-        
+
         let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
         let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)!
-        
+
         // Update status
         NCManageDatabase.shared.setMetadataStatus(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusDownloading)
         fileProviderData.shared.signalEnumerator(ocId: metadata.ocId, update: true)
-        
-        NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath,  requestHandler: { (request) in
-                        
-        }, taskHandler: { (task) in
-            
+
+        NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { _ in
+
+        }, taskHandler: { task in
+
             self.outstandingSessionTasks[url] = task
-            fileProviderData.shared.fileProviderManager.register(task, forItemWithIdentifier: NSFileProviderItemIdentifier(identifier.rawValue)) { (error) in }
-            
-        }, progressHandler: { (_) in
-            
-        }) { (account, etag, date, length, allHeaderFields, error, errorCode, errorDescription) in
-            
+            fileProviderData.shared.fileProviderManager.register(task, forItemWithIdentifier: NSFileProviderItemIdentifier(identifier.rawValue)) { _ in }
+
+        }, progressHandler: { _ in
+
+        }) { _, etag, date, _, _, _, errorCode, errorDescription in
+
             self.outstandingSessionTasks.removeValue(forKey: url)
             guard var metadata = fileProviderUtility.shared.getTableMetadataFromItemIdentifier(identifier) else {
                 completionHandler(NSFileProviderError(.noSuchItem))
                 return
             }
             metadata = tableMetadata.init(value: metadata)
-            
-            if errorCode == 0  {
-                
+
+            if errorCode == 0 {
+
                 metadata.status = NCGlobal.shared.metadataStatusNormal
                 metadata.date = date ?? NSDate()
                 metadata.etag = etag ?? ""
-                
+
                 NCManageDatabase.shared.addLocalFile(metadata: metadata)
                 NCManageDatabase.shared.addMetadata(metadata)
-                
+
                 completionHandler(nil)
-                
+
             } else if errorCode == 200 {
-                
+
                 NCManageDatabase.shared.setMetadataStatus(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusNormal)
-                
+
                 completionHandler(nil)
 
             } else {
-                
+
                 metadata.status = NCGlobal.shared.metadataStatusDownloadError
                 metadata.sessionError = errorDescription
                 NCManageDatabase.shared.addMetadata(metadata)
 
                 completionHandler(NSFileProviderError(.noSuchItem))
             }
-            
+
             fileProviderData.shared.signalEnumerator(ocId: metadata.ocId, update: true)
         }
     }
-    
+
     override func itemChanged(at url: URL) {
-        
+
         let pathComponents = url.pathComponents
         assert(pathComponents.count > 2)
         let itemIdentifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
         let fileName = pathComponents[pathComponents.count - 1]
         var ocId = itemIdentifier.rawValue
-        
+
         // Temp ocId ?
         if outstandingOcIdTemp[ocId] != nil && outstandingOcIdTemp[ocId] != ocId {
             ocId = outstandingOcIdTemp[ocId]!
@@ -276,17 +276,17 @@ class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate {
 
         let serverUrlFileName = metadata.serverUrl + "/" + fileName
         let fileNameLocalPath = url.path
-        
+
         if let task = NCCommunicationBackground.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: nil, dateModificationFile: nil, description: metadata.ocId, session: NCNetworking.shared.sessionManagerBackgroundExtension) {
-            
-            fileProviderData.shared.fileProviderManager.register(task, forItemWithIdentifier: NSFileProviderItemIdentifier(metadata.fileId)) { (error) in }
+
+            fileProviderData.shared.fileProviderManager.register(task, forItemWithIdentifier: NSFileProviderItemIdentifier(metadata.fileId)) { _ in }
         }
     }
-    
+
     override func stopProvidingItem(at url: URL) {
-      
+
         let fileHasLocalChanges = false
-        
+
         if !fileHasLocalChanges {
             // remove the existing file to free up space
             do {
@@ -294,36 +294,36 @@ class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate {
             } catch let error {
                 print("error: \(error)")
             }
-            
+
             // write out a placeholder to facilitate future property lookups
-            self.providePlaceholder(at: url, completionHandler: { error in
+            self.providePlaceholder(at: url, completionHandler: { _ in
                 // handle any error, do any necessary cleanup
             })
         }
-        
+
         // Download task
         if let downloadTask = outstandingSessionTasks[url] {
             downloadTask.cancel()
             outstandingSessionTasks.removeValue(forKey: url)
         }
     }
-    
+
     override func importDocument(at fileURL: URL, toParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
-                
+
         DispatchQueue.main.async {
-            
+
             autoreleasepool {
-            
+
                 var size = 0 as Int64
                 var error: NSError?
-                
+
                 guard let tableDirectory = fileProviderUtility.shared.getTableDirectoryFromParentItemIdentifier(parentItemIdentifier, account: fileProviderData.shared.account, homeServerUrl: fileProviderData.shared.homeServerUrl) else {
                     completionHandler(nil, NSFileProviderError(.noSuchItem))
                     return
                 }
-                
+
                 _ = fileURL.startAccessingSecurityScopedResource()
-                   
+
                 // typefile directory ? (NOT PERMITTED)
                 do {
                     let attributes = try fileProviderUtility.shared.fileManager.attributesOfItem(atPath: fileURL.path)
@@ -337,60 +337,60 @@ class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate {
                     completionHandler(nil, NSFileProviderError(.noSuchItem))
                     return
                 }
-        
+
                 let fileName = NCUtilityFileSystem.shared.createFileName(fileURL.lastPathComponent, serverUrl: tableDirectory.serverUrl, account: fileProviderData.shared.account)
                 let ocIdTemp = NSUUID().uuidString.lowercased()
-                
-                NSFileCoordinator().coordinate(readingItemAt: fileURL, options: .withoutChanges, error: &error) { (url) in
+
+                NSFileCoordinator().coordinate(readingItemAt: fileURL, options: .withoutChanges, error: &error) { url in
                     _ = fileProviderUtility.shared.copyFile(url.path, toPath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: fileName))
                 }
-                
+
                 fileURL.stopAccessingSecurityScopedResource()
-                                
+
                 let metadata = NCManageDatabase.shared.createMetadata(account: fileProviderData.shared.account, user: fileProviderData.shared.user, userId: fileProviderData.shared.userId, fileName: fileName, fileNameView: fileName, ocId: ocIdTemp, serverUrl: tableDirectory.serverUrl, urlBase: fileProviderData.shared.accountUrlBase, url: "", contentType: "", livePhoto: false)
                 metadata.session = NCNetworking.shared.sessionIdentifierBackgroundExtension
                 metadata.size = size
                 metadata.status = NCGlobal.shared.metadataStatusUploading
-                
+
                 NCManageDatabase.shared.addMetadata(metadata)
-                
+
                 let serverUrlFileName = tableDirectory.serverUrl + "/" + fileName
                 let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: fileName)!
-                
+
                 if let task = NCCommunicationBackground.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: nil, dateModificationFile: nil, description: ocIdTemp, session: NCNetworking.shared.sessionManagerBackgroundExtension) {
-                    
+
                     self.outstandingSessionTasks[URL(fileURLWithPath: fileNameLocalPath)] = task as URLSessionTask
-                    
-                    fileProviderData.shared.fileProviderManager.register(task, forItemWithIdentifier: NSFileProviderItemIdentifier(ocIdTemp)) { (error) in }
+
+                    fileProviderData.shared.fileProviderManager.register(task, forItemWithIdentifier: NSFileProviderItemIdentifier(ocIdTemp)) { _ in }
                 }
-                
+
                 let item = FileProviderItem(metadata: tableMetadata.init(value: metadata), parentItemIdentifier: parentItemIdentifier)
-                
+
                 completionHandler(item, nil)
             }
         }
     }
-    
+
     func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String) {
-                
+
         guard let ocIdTemp = description else { return }
         guard let metadataTemp = NCManageDatabase.shared.getMetadataFromOcId(ocIdTemp) else { return }
         let metadata = tableMetadata.init(value: metadataTemp)
-        
+
         let url = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: fileName))
         DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
             self.outstandingSessionTasks.removeValue(forKey: url)
         }
         outstandingOcIdTemp[ocIdTemp] = ocId
-        
+
         if errorCode == 0 {
-            
+
             // New file
             if ocId != ocIdTemp {
                 // Signal update
                 fileProviderData.shared.signalEnumerator(ocId: metadata.ocId, delete: true)
             }
-                        
+
             metadata.fileName = fileName
             metadata.serverUrl = serverUrl
             if let etag = etag { metadata.etag = etag }
@@ -400,32 +400,29 @@ class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate {
             metadata.session = ""
             metadata.size = size
             metadata.status = NCGlobal.shared.metadataStatusNormal
-                  
+
             NCManageDatabase.shared.addMetadata(metadata)
             NCManageDatabase.shared.addLocalFile(metadata: metadata)
-            
+
             // New file
             if ocId != ocIdTemp {
-            
+
                 NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
-                
+
                 // File system
                 let atPath = CCUtility.getDirectoryProviderStorageOcId(ocIdTemp)
                 let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId)
                 CCUtility.copyFile(atPath: atPath, toPath: toPath)
             }
-            
+
             fileProviderData.shared.signalEnumerator(ocId: metadata.ocId, update: true)
-            
+
         } else {
-            
+
             NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
-            
+
             fileProviderData.shared.signalEnumerator(ocId: ocIdTemp, delete: true)
         }
     }
 
 }
-
-
-    

+ 16 - 16
File Provider Extension/FileProviderItem.swift

@@ -33,44 +33,44 @@ class FileProviderItem: NSObject, NSFileProviderItem {
     var itemIdentifier: NSFileProviderItemIdentifier {
         return fileProviderUtility.shared.getItemIdentifier(metadata: metadata)
     }
-    
+
     var filename: String {
         return metadata.fileNameView
     }
-    
+
     var documentSize: NSNumber? {
         return NSNumber(value: metadata.size)
     }
-    
+
     var typeIdentifier: String {
         let results = NCCommunicationCommon.shared.getInternalType(fileName: metadata.fileNameView, mimeType: "", directory: metadata.directory)
         return results.typeIdentifier
     }
-    
+
     var contentModificationDate: Date? {
         return metadata.date as Date
     }
-    
+
     var creationDate: Date? {
         return metadata.creationDate as Date
     }
-    
+
     var lastUsedDate: Date? {
         return metadata.date as Date
     }
 
     var capabilities: NSFileProviderItemCapabilities {
-        if (metadata.directory) {
+        if metadata.directory {
             return [ .allowsAddingSubItems, .allowsContentEnumerating, .allowsReading, .allowsDeleting, .allowsRenaming ]
         } else {
             return [ .allowsWriting, .allowsReading, .allowsDeleting, .allowsRenaming, .allowsReparenting ]
         }
     }
-    
+
     var isTrashed: Bool {
         return false
     }
-    
+
     var childItemCount: NSNumber? {
         return nil
     }
@@ -78,7 +78,7 @@ class FileProviderItem: NSObject, NSFileProviderItem {
     var versionIdentifier: Data? {
         return metadata.etag.data(using: .utf8)
     }
-    
+
     var tagData: Data? {
         if let tableTag = NCManageDatabase.shared.getTag(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) {
             return tableTag.tagIOS
@@ -86,7 +86,7 @@ class FileProviderItem: NSObject, NSFileProviderItem {
             return nil
         }
     }
-    
+
     var favoriteRank: NSNumber? {
         if let rank = fileProviderData.shared.listFavoriteIdentifierRank[metadata.ocId] {
             return rank
@@ -98,7 +98,7 @@ class FileProviderItem: NSObject, NSFileProviderItem {
     var isMostRecentVersionDownloaded: Bool {
         return true
     }
-    
+
     var isDownloaded: Bool {
         if metadata.directory {
             return true
@@ -109,7 +109,7 @@ class FileProviderItem: NSObject, NSFileProviderItem {
             return false
         }
     }
-    
+
     var isDownloading: Bool {
         if metadata.status == NCGlobal.shared.metadataStatusDownloading {
             return true
@@ -117,7 +117,7 @@ class FileProviderItem: NSObject, NSFileProviderItem {
             return false
         }
     }
-    
+
     var downloadingError: Error? {
         if metadata.status == NCGlobal.shared.metadataStatusDownloadError {
             return fileProviderData.FileProviderError.downloadError
@@ -133,7 +133,7 @@ class FileProviderItem: NSObject, NSFileProviderItem {
             return false
         }
     }
-    
+
     var isUploading: Bool {
         if metadata.status == NCGlobal.shared.metadataStatusUploading {
             return true
@@ -141,7 +141,7 @@ class FileProviderItem: NSObject, NSFileProviderItem {
             return false
         }
     }
-    
+
     var uploadingError: Error? {
         if metadata.status == NCGlobal.shared.metadataStatusUploadError {
             return fileProviderData.FileProviderError.uploadError

+ 39 - 39
File Provider Extension/FileProviderUtility.swift

@@ -28,41 +28,41 @@ class fileProviderUtility: NSObject {
         let instance = fileProviderUtility()
         return instance
     }()
-    
+
     var fileManager = FileManager()
-    
+
     func getAccountFromItemIdentifier(_ itemIdentifier: NSFileProviderItemIdentifier) -> String? {
-        
+
         let ocId = itemIdentifier.rawValue
         return NCManageDatabase.shared.getMetadataFromOcId(ocId)?.account
     }
-    
+
     func getTableMetadataFromItemIdentifier(_ itemIdentifier: NSFileProviderItemIdentifier) -> tableMetadata? {
-        
+
         let ocId = itemIdentifier.rawValue
         return NCManageDatabase.shared.getMetadataFromOcId(ocId)
     }
 
     func getItemIdentifier(metadata: tableMetadata) -> NSFileProviderItemIdentifier {
-        
+
         return NSFileProviderItemIdentifier(metadata.ocId)
     }
-    
+
     func createocIdentifierOnFileSystem(metadata: tableMetadata) {
-        
+
         let itemIdentifier = getItemIdentifier(metadata: metadata)
-        
+
         if metadata.directory {
             CCUtility.getDirectoryProviderStorageOcId(itemIdentifier.rawValue)
         } else {
             CCUtility.getDirectoryProviderStorageOcId(itemIdentifier.rawValue, fileNameView: metadata.fileNameView)
         }
     }
-    
+
     func getParentItemIdentifier(metadata: tableMetadata) -> NSFileProviderItemIdentifier? {
-        
+
         let homeServerUrl = NCUtilityFileSystem.shared.getHomeServer(account: metadata.account)
-        if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl))  {
+        if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
             if directory.serverUrl == homeServerUrl {
                 return NSFileProviderItemIdentifier(NSFileProviderItemIdentifier.rootContainer.rawValue)
             } else {
@@ -73,37 +73,37 @@ class fileProviderUtility: NSObject {
                 }
             }
         }
-        
+
         return nil
     }
-    
+
     func getTableDirectoryFromParentItemIdentifier(_ parentItemIdentifier: NSFileProviderItemIdentifier, account: String, homeServerUrl: String) -> tableDirectory? {
-        
+
         var predicate: NSPredicate
-        
+
         if parentItemIdentifier == .rootContainer {
-            
+
             predicate = NSPredicate(format: "account == %@ AND serverUrl == %@", account, homeServerUrl)
-            
+
         } else {
-            
+
             guard let metadata = getTableMetadataFromItemIdentifier(parentItemIdentifier) else { return nil }
             predicate = NSPredicate(format: "ocId == %@", metadata.ocId)
         }
-        
+
         guard let directory = NCManageDatabase.shared.getTableDirectory(predicate: predicate) else { return nil }
-        
+
         return directory
     }
-    
+
     // MARK: -
-    
+
     func copyFile(_ atPath: String, toPath: String) -> Error? {
-        
+
         var errorResult: Error?
-        
-        if !fileManager.fileExists(atPath: atPath) { return NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo:[:]) }
-        
+
+        if !fileManager.fileExists(atPath: atPath) { return NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: [:]) }
+
         do {
             try fileManager.removeItem(atPath: toPath)
         } catch let error {
@@ -114,17 +114,17 @@ class fileProviderUtility: NSObject {
         } catch let error {
             errorResult = error
         }
-        
+
         return errorResult
     }
-    
+
     func moveFile(_ atPath: String, toPath: String) -> Error? {
-        
+
         var errorResult: Error?
-        
+
         if atPath == toPath { return nil }
-        if !fileManager.fileExists(atPath: atPath) { return NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo:[:]) }
-        
+        if !fileManager.fileExists(atPath: atPath) { return NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: [:]) }
+
         do {
             try fileManager.removeItem(atPath: toPath)
         } catch let error {
@@ -135,23 +135,23 @@ class fileProviderUtility: NSObject {
         } catch let error {
             errorResult = error
         }
-        
+
         return errorResult
     }
-    
+
     func deleteFile(_ atPath: String) -> Error? {
-        
+
         var errorResult: Error?
-        
+
         do {
             try fileManager.removeItem(atPath: atPath)
         } catch let error {
             errorResult = error
         }
-        
+
         return errorResult
     }
-    
+
     func fileExists(atPath: String) -> Bool {
         return fileManager.fileExists(atPath: atPath)
     }

+ 212 - 3
Nextcloud.xcodeproj/project.pbxproj

@@ -20,10 +20,24 @@
 		8491B1CD273BBA82001C8C5B /* UIViewController+Menu.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8491B1CC273BBA82001C8C5B /* UIViewController+Menu.swift */; };
 		AF2D7C7C2742556F00ADF566 /* NCShareLinkCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF2D7C7B2742556F00ADF566 /* NCShareLinkCell.swift */; };
 		AF2D7C7E2742559100ADF566 /* NCShareUserCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF2D7C7D2742559100ADF566 /* NCShareUserCell.swift */; };
+		AF4BF614275629E20081CEEF /* NCManageDatabase+Account.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF4BF613275629E20081CEEF /* NCManageDatabase+Account.swift */; };
+		AF4BF615275629E20081CEEF /* NCManageDatabase+Account.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF4BF613275629E20081CEEF /* NCManageDatabase+Account.swift */; };
+		AF4BF616275629E20081CEEF /* NCManageDatabase+Account.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF4BF613275629E20081CEEF /* NCManageDatabase+Account.swift */; };
+		AF4BF617275629E20081CEEF /* NCManageDatabase+Account.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF4BF613275629E20081CEEF /* NCManageDatabase+Account.swift */; };
+		AF4BF61927562A4B0081CEEF /* NCManageDatabse+Metadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF4BF61827562A4B0081CEEF /* NCManageDatabse+Metadata.swift */; };
+		AF4BF61A27562A4B0081CEEF /* NCManageDatabse+Metadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF4BF61827562A4B0081CEEF /* NCManageDatabse+Metadata.swift */; };
+		AF4BF61B27562A4B0081CEEF /* NCManageDatabse+Metadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF4BF61827562A4B0081CEEF /* NCManageDatabse+Metadata.swift */; };
+		AF4BF61C27562A4B0081CEEF /* NCManageDatabse+Metadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF4BF61827562A4B0081CEEF /* NCManageDatabse+Metadata.swift */; };
+		AF4BF61E27562B3F0081CEEF /* NCManageDatabase+Activity.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF4BF61D27562B3F0081CEEF /* NCManageDatabase+Activity.swift */; };
+		AF4BF61F27562B3F0081CEEF /* NCManageDatabase+Activity.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF4BF61D27562B3F0081CEEF /* NCManageDatabase+Activity.swift */; };
+		AF4BF62027562B3F0081CEEF /* NCManageDatabase+Activity.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF4BF61D27562B3F0081CEEF /* NCManageDatabase+Activity.swift */; };
+		AF4BF62127562B3F0081CEEF /* NCManageDatabase+Activity.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF4BF61D27562B3F0081CEEF /* NCManageDatabase+Activity.swift */; };
 		AF817EF1274BC781009ED85B /* NCUserBaseUrl.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF817EF0274BC781009ED85B /* NCUserBaseUrl.swift */; };
 		AF817EF2274BC781009ED85B /* NCUserBaseUrl.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF817EF0274BC781009ED85B /* NCUserBaseUrl.swift */; };
 		AF817EF3274BC781009ED85B /* NCUserBaseUrl.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF817EF0274BC781009ED85B /* NCUserBaseUrl.swift */; };
 		AF817EF4274BC781009ED85B /* NCUserBaseUrl.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF817EF0274BC781009ED85B /* NCUserBaseUrl.swift */; };
+		AF8ED1FC2757821000B8DBC4 /* NextcloudTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF8ED1FB2757821000B8DBC4 /* NextcloudTests.swift */; };
+		AF8ED2032757822700B8DBC4 /* NCGlobalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF8ED2022757822700B8DBC4 /* NCGlobalTests.swift */; };
 		D575039F27146F93008DC9DC /* String+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7A0D1342591FBC5008F8A13 /* String+Extensions.swift */; };
 		D5B6AA7827200C7200D49C24 /* NCActivityTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5B6AA7727200C7200D49C24 /* NCActivityTableViewCell.swift */; };
 		F700222C1EC479840080073F /* Custom.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = F700222B1EC479840080073F /* Custom.xcassets */; };
@@ -366,6 +380,13 @@
 			remoteGlobalIDString = 2C33C47E23E2C475005F963B;
 			remoteInfo = "Notification Service Extension";
 		};
+		AF8ED1FD2757821000B8DBC4 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = F7F67BA01A24D27800EE80DA /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = F77B0DEB1D118A16002130FE;
+			remoteInfo = Nextcloud;
+		};
 		F7145A311D12E65F00CAFEEC /* PBXContainerItemProxy */ = {
 			isa = PBXContainerItemProxy;
 			containerPortal = F7F67BA01A24D27800EE80DA /* Project object */;
@@ -436,7 +457,13 @@
 		8491B1CC273BBA82001C8C5B /* UIViewController+Menu.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIViewController+Menu.swift"; sourceTree = "<group>"; };
 		AF2D7C7B2742556F00ADF566 /* NCShareLinkCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCShareLinkCell.swift; sourceTree = "<group>"; };
 		AF2D7C7D2742559100ADF566 /* NCShareUserCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCShareUserCell.swift; sourceTree = "<group>"; };
+		AF4BF613275629E20081CEEF /* NCManageDatabase+Account.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NCManageDatabase+Account.swift"; sourceTree = "<group>"; };
+		AF4BF61827562A4B0081CEEF /* NCManageDatabse+Metadata.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NCManageDatabse+Metadata.swift"; sourceTree = "<group>"; };
+		AF4BF61D27562B3F0081CEEF /* NCManageDatabase+Activity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NCManageDatabase+Activity.swift"; sourceTree = "<group>"; };
 		AF817EF0274BC781009ED85B /* NCUserBaseUrl.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCUserBaseUrl.swift; sourceTree = "<group>"; };
+		AF8ED1F92757821000B8DBC4 /* NextcloudTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = NextcloudTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
+		AF8ED1FB2757821000B8DBC4 /* NextcloudTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NextcloudTests.swift; sourceTree = "<group>"; };
+		AF8ED2022757822700B8DBC4 /* NCGlobalTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCGlobalTests.swift; sourceTree = "<group>"; };
 		D5B6AA7727200C7200D49C24 /* NCActivityTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCActivityTableViewCell.swift; sourceTree = "<group>"; };
 		F700222B1EC479840080073F /* Custom.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Custom.xcassets; sourceTree = "<group>"; };
 		F700510022DF63AC003A3356 /* NCShare.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; path = NCShare.storyboard; sourceTree = "<group>"; };
@@ -800,6 +827,13 @@
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
+		AF8ED1F62757821000B8DBC4 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
 		F7145A141D12E3B700CAFEEC /* Frameworks */ = {
 			isa = PBXFrameworksBuildPhase;
 			buildActionMask = 2147483647;
@@ -888,6 +922,15 @@
 			path = Menu;
 			sourceTree = "<group>";
 		};
+		AF8ED1FA2757821000B8DBC4 /* NextcloudTests */ = {
+			isa = PBXGroup;
+			children = (
+				AF8ED2022757822700B8DBC4 /* NCGlobalTests.swift */,
+				AF8ED1FB2757821000B8DBC4 /* NextcloudTests.swift */,
+			);
+			path = NextcloudTests;
+			sourceTree = "<group>";
+		};
 		F70211F31BAC56E9003FC03E /* Main */ = {
 			isa = PBXGroup;
 			children = (
@@ -1333,6 +1376,9 @@
 				F7C1EEA425053A9C00866ACC /* NCDataSource.swift */,
 				F7BAADB41ED5A87C00B7EAD4 /* NCDatabase.swift */,
 				F7BAADB51ED5A87C00B7EAD4 /* NCManageDatabase.swift */,
+				AF4BF61D27562B3F0081CEEF /* NCManageDatabase+Activity.swift */,
+				AF4BF613275629E20081CEEF /* NCManageDatabase+Account.swift */,
+				AF4BF61827562A4B0081CEEF /* NCManageDatabse+Metadata.swift */,
 				F73D5E46246DE09200DF6467 /* NCElementsJSON.swift */,
 			);
 			path = Data;
@@ -1504,10 +1550,12 @@
 				F771E3D120E2392D00AFB62D /* File Provider Extension */,
 				F7C0F46D1C8880540059EC54 /* Share */,
 				2C33C48023E2C475005F963B /* Notification Service Extension */,
+				AF8ED1FA2757821000B8DBC4 /* NextcloudTests */,
 				F7FC7D651DC1F98700BB2C6A /* Products */,
 				F7FC7D541DC1F93700BB2C6A /* Frameworks */,
 				F771E3D020E2392D00AFB62D /* File Provider Extension.appex */,
 				2C33C47F23E2C475005F963B /* Notification Service Extension.appex */,
+				AF8ED1F92757821000B8DBC4 /* NextcloudTests.xctest */,
 			);
 			sourceTree = "<group>";
 		};
@@ -1699,6 +1747,24 @@
 			productReference = 2C33C47F23E2C475005F963B /* Notification Service Extension.appex */;
 			productType = "com.apple.product-type.app-extension";
 		};
+		AF8ED1F82757821000B8DBC4 /* NextcloudTests */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = AF8ED2012757821000B8DBC4 /* Build configuration list for PBXNativeTarget "NextcloudTests" */;
+			buildPhases = (
+				AF8ED1F52757821000B8DBC4 /* Sources */,
+				AF8ED1F62757821000B8DBC4 /* Frameworks */,
+				AF8ED1F72757821000B8DBC4 /* Resources */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+				AF8ED1FE2757821000B8DBC4 /* PBXTargetDependency */,
+			);
+			name = NextcloudTests;
+			productName = NextcloudTests;
+			productReference = AF8ED1F92757821000B8DBC4 /* NextcloudTests.xctest */;
+			productType = "com.apple.product-type.bundle.unit-test";
+		};
 		F71459B41D12E3B700CAFEEC /* Share */ = {
 			isa = PBXNativeTarget;
 			buildConfigurationList = F7145A251D12E3B700CAFEEC /* Build configuration list for PBXNativeTarget "Share" */;
@@ -1758,7 +1824,8 @@
 				F77B0EE91D118A16002130FE /* Resources */,
 				F77B0F981D118A16002130FE /* Embed App Extensions */,
 				F70B86782642CF5300ED5349 /* Embed Frameworks */,
-				F7439BF8265669E800406313 /* ShellScript */,
+				F7439BF8265669E800406313 /* Run Script */,
+				AFBFD01327551A54002244BC /* ShellScript */,
 			);
 			buildRules = (
 			);
@@ -1793,7 +1860,7 @@
 		F7F67BA01A24D27800EE80DA /* Project object */ = {
 			isa = PBXProject;
 			attributes = {
-				LastSwiftUpdateCheck = 1130;
+				LastSwiftUpdateCheck = 1310;
 				LastUpgradeCheck = 1250;
 				ORGANIZATIONNAME = "Marino Faggiana";
 				TargetAttributes = {
@@ -1802,6 +1869,10 @@
 						DevelopmentTeam = 6JLRKY9ZV7;
 						ProvisioningStyle = Automatic;
 					};
+					AF8ED1F82757821000B8DBC4 = {
+						CreatedOnToolsVersion = 13.1;
+						TestTargetID = F77B0DEB1D118A16002130FE;
+					};
 					F71459B41D12E3B700CAFEEC = {
 						DevelopmentTeam = 6JLRKY9ZV7;
 						LastSwiftMigration = 1020;
@@ -1907,6 +1978,7 @@
 				F71459B41D12E3B700CAFEEC /* Share */,
 				F771E3CF20E2392D00AFB62D /* File Provider Extension */,
 				2C33C47E23E2C475005F963B /* Notification Service Extension */,
+				AF8ED1F82757821000B8DBC4 /* NextcloudTests */,
 			);
 		};
 /* End PBXProject section */
@@ -1920,6 +1992,13 @@
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
+		AF8ED1F72757821000B8DBC4 /* Resources */ = {
+			isa = PBXResourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
 		F7145A181D12E3B700CAFEEC /* Resources */ = {
 			isa = PBXResourcesBuildPhase;
 			buildActionMask = 2147483647;
@@ -2030,7 +2109,24 @@
 /* End PBXResourcesBuildPhase section */
 
 /* Begin PBXShellScriptBuildPhase section */
-		F7439BF8265669E800406313 /* ShellScript */ = {
+		AFBFD01327551A54002244BC /* ShellScript */ = {
+			isa = PBXShellScriptBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			inputFileListPaths = (
+			);
+			inputPaths = (
+			);
+			outputFileListPaths = (
+			);
+			outputPaths = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+			shellPath = /bin/sh;
+			shellScript = "if test -d \"/opt/homebrew/bin/\"; then\n  PATH=\"/opt/homebrew/bin/:${PATH}\"\nfi\n\nexport PATH\n\nif which swiftlint >/dev/null; then\n  swiftlint\nelse\n  echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n";
+		};
+		F7439BF8265669E800406313 /* Run Script */ = {
 			isa = PBXShellScriptBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
@@ -2039,6 +2135,7 @@
 			);
 			inputPaths = (
 			);
+			name = "Run Script";
 			outputFileListPaths = (
 			);
 			outputPaths = (
@@ -2058,14 +2155,17 @@
 				2C1D5D7923E2DE9100334ABB /* NCBrand.swift in Sources */,
 				F770768A263A8A2500A1BA94 /* NCUtilityFileSystem.swift in Sources */,
 				F746EC50273906BA0052598D /* NCViewCertificateDetails.swift in Sources */,
+				AF4BF62127562B3F0081CEEF /* NCManageDatabase+Activity.swift in Sources */,
 				F702F2D225EE5B5C008F8E80 /* NCGlobal.swift in Sources */,
 				F7707689263A896A00A1BA94 /* UIImage+Extensions.swift in Sources */,
 				2C1D5D7523E2DE3300334ABB /* NCDatabase.swift in Sources */,
 				2C1D5D7623E2DE3300334ABB /* NCManageDatabase.swift in Sources */,
 				2C33C48223E2C475005F963B /* NotificationService.swift in Sources */,
+				AF4BF617275629E20081CEEF /* NCManageDatabase+Account.swift in Sources */,
 				D575039F27146F93008DC9DC /* String+Extensions.swift in Sources */,
 				F73D5E4A246DE09200DF6467 /* NCElementsJSON.swift in Sources */,
 				F79B646326CA661600838ACA /* UIControl+Extensions.swift in Sources */,
+				AF4BF61C27562A4B0081CEEF /* NCManageDatabse+Metadata.swift in Sources */,
 				AF817EF4274BC781009ED85B /* NCUserBaseUrl.swift in Sources */,
 				F798F0EC2588060A000DAFFD /* UIColor+Extensions.swift in Sources */,
 				2CB7D1CA23E2EDCB00376EF9 /* NCPushNotificationEncryption.m in Sources */,
@@ -2073,6 +2173,15 @@
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
+		AF8ED1F52757821000B8DBC4 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				AF8ED1FC2757821000B8DBC4 /* NextcloudTests.swift in Sources */,
+				AF8ED2032757822700B8DBC4 /* NCGlobalTests.swift in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
 		F71459B51D12E3B700CAFEEC /* Sources */ = {
 			isa = PBXSourcesBuildPhase;
 			buildActionMask = 2147483647;
@@ -2081,6 +2190,7 @@
 				F73D5E48246DE09200DF6467 /* NCElementsJSON.swift in Sources */,
 				F7EDE4E5262D7BBE00414FE6 /* NCSectionHeaderFooter.swift in Sources */,
 				F79EC78926316AC4004E59D6 /* NCPopupViewController.swift in Sources */,
+				AF4BF61F27562B3F0081CEEF /* NCManageDatabase+Activity.swift in Sources */,
 				F7A0D1362591FBC5008F8A13 /* String+Extensions.swift in Sources */,
 				F7EDE4D6262D7B9600414FE6 /* NCListCell.swift in Sources */,
 				F7707687263A853700A1BA94 /* NCContentPresenter.swift in Sources */,
@@ -2088,6 +2198,8 @@
 				F70BFC7520E0FA7D00C67599 /* NCUtility.swift in Sources */,
 				F79B646126CA661600838ACA /* UIControl+Extensions.swift in Sources */,
 				F7EDE4CC262D7B6F00414FE6 /* NCEmptyDataSet.swift in Sources */,
+				AF4BF61A27562A4B0081CEEF /* NCManageDatabse+Metadata.swift in Sources */,
+				AF4BF615275629E20081CEEF /* NCManageDatabase+Account.swift in Sources */,
 				F798F0E225880608000DAFFD /* UIColor+Extensions.swift in Sources */,
 				AF817EF2274BC781009ED85B /* NCUserBaseUrl.swift in Sources */,
 				F78295311F962EFA00A572F5 /* NCEndToEndEncryption.m in Sources */,
@@ -2126,8 +2238,10 @@
 				F771E3D320E2392D00AFB62D /* FileProviderExtension.swift in Sources */,
 				F73D5E49246DE09200DF6467 /* NCElementsJSON.swift in Sources */,
 				F771E3D520E2392D00AFB62D /* FileProviderItem.swift in Sources */,
+				AF4BF616275629E20081CEEF /* NCManageDatabase+Account.swift in Sources */,
 				F7434B3620E23FE000417916 /* NCManageDatabase.swift in Sources */,
 				F798F0E725880609000DAFFD /* UIColor+Extensions.swift in Sources */,
+				AF4BF61B27562A4B0081CEEF /* NCManageDatabse+Metadata.swift in Sources */,
 				F70460542499095400BB98A7 /* NotificationCenter+MainThread.swift in Sources */,
 				F785EEA42461A4A600B3F945 /* NCUtility.swift in Sources */,
 				F79B646226CA661600838ACA /* UIControl+Extensions.swift in Sources */,
@@ -2139,6 +2253,7 @@
 				F74AF3A6247FB6AE00AC767B /* NCUtilityFileSystem.swift in Sources */,
 				F7A76DCD256A71CE00119AB3 /* UIImage+Extensions.swift in Sources */,
 				F771E3F820E239B500AFB62D /* FileProviderExtension+Thumbnail.swift in Sources */,
+				AF4BF62027562B3F0081CEEF /* NCManageDatabase+Activity.swift in Sources */,
 				F785EEA62461A4FB00B3F945 /* CCUtility.m in Sources */,
 				F73ADD2226554FD10069EA0D /* NCContentPresenter.swift in Sources */,
 			);
@@ -2179,6 +2294,7 @@
 				F7A80BCB252624C100C7CD01 /* NCFileViewInFolder.swift in Sources */,
 				F78A18B823CDE2B300F681F3 /* NCViewerRichWorkspace.swift in Sources */,
 				F77910AB25DD53C700CEDB9E /* NCSettingsBundleHelper.swift in Sources */,
+				AF4BF61927562A4B0081CEEF /* NCManageDatabse+Metadata.swift in Sources */,
 				F78A18B623CDD07D00F681F3 /* NCViewerRichWorkspaceWebView.swift in Sources */,
 				F716B75F26F09DF600D37EFC /* NCKTVHTTPCache.swift in Sources */,
 				F75A9EE623796C6F0044CFCE /* NCNetworking.swift in Sources */,
@@ -2281,6 +2397,8 @@
 				F717402E24F699A5000C87D5 /* NCFavorite.swift in Sources */,
 				AF2D7C7E2742559100ADF566 /* NCShareUserCell.swift in Sources */,
 				F74DE14325135B6800917068 /* NCTransfers.swift in Sources */,
+				AF4BF614275629E20081CEEF /* NCManageDatabase+Account.swift in Sources */,
+				AF4BF61E27562B3F0081CEEF /* NCManageDatabase+Activity.swift in Sources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
@@ -2292,6 +2410,11 @@
 			target = 2C33C47E23E2C475005F963B /* Notification Service Extension */;
 			targetProxy = 2C33C48423E2C475005F963B /* PBXContainerItemProxy */;
 		};
+		AF8ED1FE2757821000B8DBC4 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = F77B0DEB1D118A16002130FE /* Nextcloud */;
+			targetProxy = AF8ED1FD2757821000B8DBC4 /* PBXContainerItemProxy */;
+		};
 		F7145A321D12E65F00CAFEEC /* PBXTargetDependency */ = {
 			isa = PBXTargetDependency;
 			target = F71459B41D12E3B700CAFEEC /* Share */;
@@ -2465,6 +2588,83 @@
 			};
 			name = Release;
 		};
+		AF8ED1FF2757821000B8DBC4 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				BUNDLE_LOADER = "$(TEST_HOST)";
+				CLANG_ANALYZER_NONNULL = YES;
+				CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+				CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
+				CLANG_ENABLE_OBJC_WEAK = YES;
+				CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+				CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+				CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
+				CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+				CODE_SIGN_STYLE = Automatic;
+				CURRENT_PROJECT_VERSION = 1;
+				DEBUG_INFORMATION_FORMAT = dwarf;
+				DEVELOPMENT_TEAM = 6JLRKY9ZV7;
+				GCC_C_LANGUAGE_STANDARD = gnu11;
+				GCC_PREPROCESSOR_DEFINITIONS = (
+					"DEBUG=1",
+					"$(inherited)",
+				);
+				GENERATE_INFOPLIST_FILE = YES;
+				IPHONEOS_DEPLOYMENT_TARGET = 15.0;
+				LD_RUNPATH_SEARCH_PATHS = (
+					"$(inherited)",
+					"@executable_path/Frameworks",
+					"@loader_path/Frameworks",
+				);
+				MARKETING_VERSION = 1.0;
+				MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
+				MTL_FAST_MATH = YES;
+				PRODUCT_BUNDLE_IDENTIFIER = it.twsweb.NextcloudTests;
+				PRODUCT_NAME = "$(TARGET_NAME)";
+				SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
+				SWIFT_EMIT_LOC_STRINGS = NO;
+				SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+				SWIFT_VERSION = 5.0;
+				TARGETED_DEVICE_FAMILY = "1,2";
+				TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Nextcloud.app/Nextcloud";
+			};
+			name = Debug;
+		};
+		AF8ED2002757821000B8DBC4 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				BUNDLE_LOADER = "$(TEST_HOST)";
+				CLANG_ANALYZER_NONNULL = YES;
+				CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+				CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
+				CLANG_ENABLE_OBJC_WEAK = YES;
+				CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+				CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+				CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
+				CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+				CODE_SIGN_STYLE = Automatic;
+				CURRENT_PROJECT_VERSION = 1;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				DEVELOPMENT_TEAM = 6JLRKY9ZV7;
+				GCC_C_LANGUAGE_STANDARD = gnu11;
+				GENERATE_INFOPLIST_FILE = YES;
+				IPHONEOS_DEPLOYMENT_TARGET = 15.0;
+				LD_RUNPATH_SEARCH_PATHS = (
+					"$(inherited)",
+					"@executable_path/Frameworks",
+					"@loader_path/Frameworks",
+				);
+				MARKETING_VERSION = 1.0;
+				MTL_FAST_MATH = YES;
+				PRODUCT_BUNDLE_IDENTIFIER = it.twsweb.NextcloudTests;
+				PRODUCT_NAME = "$(TARGET_NAME)";
+				SWIFT_EMIT_LOC_STRINGS = NO;
+				SWIFT_VERSION = 5.0;
+				TARGETED_DEVICE_FAMILY = "1,2";
+				TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Nextcloud.app/Nextcloud";
+			};
+			name = Release;
+		};
 		F7145A261D12E3B700CAFEEC /* Debug */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
@@ -2891,6 +3091,15 @@
 			defaultConfigurationIsVisible = 0;
 			defaultConfigurationName = Release;
 		};
+		AF8ED2012757821000B8DBC4 /* Build configuration list for PBXNativeTarget "NextcloudTests" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				AF8ED1FF2757821000B8DBC4 /* Debug */,
+				AF8ED2002757821000B8DBC4 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
 		F7145A251D12E3B700CAFEEC /* Build configuration list for PBXNativeTarget "Share" */ = {
 			isa = XCConfigurationList;
 			buildConfigurations = (

+ 11 - 0
Nextcloud.xcodeproj/xcshareddata/xcschemes/File Provider Extension.xcscheme

@@ -52,6 +52,16 @@
          </BuildableReference>
       </MacroExpansion>
       <Testables>
+         <TestableReference
+            skipped = "NO">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "AF8ED1F82757821000B8DBC4"
+               BuildableName = "NextcloudTests.xctest"
+               BlueprintName = "NextcloudTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
       </Testables>
    </TestAction>
    <LaunchAction
@@ -83,6 +93,7 @@
       savedToolIdentifier = ""
       useCustomWorkingDirectory = "NO"
       debugDocumentVersioning = "YES"
+      askForAppToLaunch = "Yes"
       launchAutomaticallySubstyle = "2">
       <BuildableProductRunnable
          runnableDebuggingMode = "0">

+ 12 - 1
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 = "YES"
+      codeCoverageEnabled = "YES">
       <MacroExpansion>
          <BuildableReference
             BuildableIdentifier = "primary"
@@ -37,6 +38,16 @@
          </BuildableReference>
       </MacroExpansion>
       <Testables>
+         <TestableReference
+            skipped = "NO">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "AF8ED1F82757821000B8DBC4"
+               BuildableName = "NextcloudTests.xctest"
+               BlueprintName = "NextcloudTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
       </Testables>
    </TestAction>
    <LaunchAction

+ 11 - 0
Nextcloud.xcodeproj/xcshareddata/xcschemes/Share.xcscheme

@@ -52,6 +52,16 @@
          </BuildableReference>
       </MacroExpansion>
       <Testables>
+         <TestableReference
+            skipped = "NO">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "AF8ED1F82757821000B8DBC4"
+               BuildableName = "NextcloudTests.xctest"
+               BlueprintName = "NextcloudTests"
+               ReferencedContainer = "container:Nextcloud.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
       </Testables>
    </TestAction>
    <LaunchAction
@@ -87,6 +97,7 @@
       savedToolIdentifier = ""
       useCustomWorkingDirectory = "NO"
       debugDocumentVersioning = "YES"
+      askForAppToLaunch = "Yes"
       launchAutomaticallySubstyle = "2">
       <BuildableProductRunnable
          runnableDebuggingMode = "0">

+ 54 - 0
NextcloudTests/NCGlobalTests.swift

@@ -0,0 +1,54 @@
+//
+//  NCGlobalTests.swift
+//  Nextcloud
+//
+//  Created by Henrik Storch on 01.12.21.
+//  Copyright © 2021 Henrik Storch. All rights reserved.
+//
+//  Author Henrik Storch <henrik.storch@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/>.
+//
+
+@testable import Nextcloud
+import XCTest
+
+class NCGlobalTests: XCTestCase {
+
+    func testSharedInatance() throws {
+        XCTAssertNotNil(NCGlobal.shared, "Shared instance should be initialized")
+    }
+
+    func testHashToInt() {
+        let emptyHash10 = NCGlobal.hashToInt(hash: "", maximum: 10)
+        let emptyHash2 = NCGlobal.hashToInt(hash: "", maximum: 2)
+        XCTAssertEqual(emptyHash10, 0, "Empty hash should be zero")
+        XCTAssertEqual(emptyHash10, emptyHash2, "Empty hashes should be the same")
+        let emptyHashA = NCGlobal.hashToInt(hash: "a", maximum: 10)
+        XCTAssertEqual(emptyHashA, 0, "Hash of 'a' mod 10 should be zero")
+        let emptyHash22 = NCGlobal.hashToInt(hash: "1ab", maximum: 100)
+        XCTAssertEqual(emptyHash22, 22, "Hash of '1ab' mod 100 should be 22")
+        let nonHexHash = NCGlobal.hashToInt(hash: "1qw&(*}", maximum: 10)
+        XCTAssertEqual(nonHexHash, 1, "Non hex characters should be ignored")
+    }
+
+    func testUsernameToColor() {
+        let color = NCGlobal.shared.usernameToColor("00000000")
+        let userColor = NCBrandColor.shared.userColors[0]
+        XCTAssertEqual(color, userColor, "Zero usercolor doesn't match")
+        let emptyColor = NCGlobal.shared.usernameToColor("")
+        let emptyUserColor = NCBrandColor.shared.userColors[12]
+        XCTAssertEqual(emptyColor, emptyUserColor, "Empty usercolor doesn't match")
+    }
+}

+ 33 - 0
NextcloudTests/NextcloudTests.swift

@@ -0,0 +1,33 @@
+//
+//  NextcloudTests.swift
+//  NextcloudTests
+//
+//  Created by Henrik Storch on 01.12.21.
+//  Copyright © 2021 Marino Faggiana. All rights reserved.
+//
+
+import XCTest
+
+class NextcloudTests: XCTestCase {
+
+    override func setUpWithError() throws {
+        // Put setup code here. This method is called before the invocation of each test method in the class.
+    }
+
+    override func tearDownWithError() throws {
+        // Put teardown code here. This method is called after the invocation of each test method in the class.
+    }
+
+    func testExample() throws {
+        // This is an example of a functional test case.
+        // Use XCTAssert and related functions to verify your tests produce the correct results.
+    }
+
+    func testPerformanceExample() throws {
+        // This is an example of a performance test case.
+        measure {
+            // Put the code you want to measure the time of here.
+        }
+    }
+
+}

+ 3 - 3
Notification Service Extension/NotificationService.swift

@@ -30,7 +30,7 @@ class NotificationService: UNNotificationServiceExtension {
     override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
         self.contentHandler = contentHandler
         bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
-        
+
         if let bestAttemptContent = bestAttemptContent {
             bestAttemptContent.title = ""
             bestAttemptContent.body = "Nextcloud notification"
@@ -55,11 +55,11 @@ class NotificationService: UNNotificationServiceExtension {
             } catch let error as NSError {
                 print("Failed : \(error.localizedDescription)")
             }
-            
+
             contentHandler(bestAttemptContent)
         }
     }
-    
+
     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.

+ 11 - 7
README.md

@@ -1,10 +1,14 @@
-# [Nextcloud](https://nextcloud.com)  iOS app [![Releases](https://img.shields.io/github/release/nextcloud/ios.svg)](https://github.com/nextcloud/ios/releases/latest)
+# [Nextcloud](https://nextcloud.com) iOS app 
+[![Releases](https://img.shields.io/github/release/nextcloud/ios.svg)](https://github.com/nextcloud/ios/releases/latest) [![Build](https://github.com/nextcloud/ios/actions/workflows/xcode.yml/badge.svg)](https://github.com/nextcloud/ios/actions/workflows/xcode.yml) [![SwiftLint](https://github.com/nextcloud/ios/actions/workflows/lint.yml/badge.svg)](https://github.com/nextcloud/ios/actions/workflows/lint.yml)
+[![irc](https://img.shields.io/badge/IRC-%23nextcloud--mobile%20on%20freenode-blue.svg)](https://webchat.freenode.net/?channels=nextcloud-mobile)
 
-[<img src="Animation.gif"
-alt="Download from App Store"
-height="400">](https://itunes.apple.com/us/app/nextcloud/id1125420102?mt=8)
+<img src="Animation.gif" 
+alt="Demo of the Nextcloud iOS files app"
+height="400">
 
-[![irc](https://img.shields.io/badge/IRC-%23nextcloud--mobile%20on%20freenode-blue.svg)](https://webchat.freenode.net/?channels=nextcloud-mobile)
+[<img src="https://developer.apple.com/assets/elements/badges/download-on-the-app-store.svg"
+alt="Demo of the Nextcloud iOS files app"
+height="40">](https://itunes.apple.com/us/app/nextcloud/id1125420102)
 
 Check out https://nextcloud.com and follow us on [twitter.com/nextclouders](https://twitter.com/nextclouders) or [twitter.com/NextcloudiOS](https://twitter.com/NextcloudiOS)
 
@@ -33,11 +37,11 @@ More information how to contribute: [https://nextcloud.com/contribute/](https://
 ## Start contributing
 
 You can start by forking this repository and creating pull requests on the develop
-branch. Maybe start working on [starter issues](https://github.com/nextcloud/ios/issues?q=is%3Aopen+is%3Aissue+label%3A%22starter+issue%22). 
+branch. Maybe start working on [starter issues](https://github.com/nextcloud/ios/labels/good%20first%20issue). 
 
 Easy starting points are also reviewing [pull requests](https://github.com/nextcloud/ios/pulls)
 
-### Xcode V 13 Project Setup
+### Xcode 13 Project Setup
 
 #### Dependencies
 

Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 222 - 223
Share/NCShareExtension.swift


+ 52 - 53
iOSClient/Activity/NCActivity.swift

@@ -54,7 +54,7 @@ class NCActivity: UIViewController {
     var hasActivityToLoad = true {
         didSet { tableView.tableFooterView?.isHidden = hasActivityToLoad }
     }
-    var dateAutomaticFetch : Date?
+    var dateAutomaticFetch: Date?
 
     // MARK: - View Life Cycle
 
@@ -82,7 +82,7 @@ class NCActivity: UIViewController {
     }
 
     func setupComments() {
-        tableView.register(UINib.init(nibName: "NCShareCommentsCell", bundle: nil), forCellReuseIdentifier: "cell")
+        tableView.register(UINib(nibName: "NCShareCommentsCell", bundle: nil), forCellReuseIdentifier: "cell")
 
         newCommentField.placeholder = NSLocalizedString("_new_comment_", comment: "")
         viewContainerConstraint.constant = height
@@ -92,7 +92,7 @@ class NCActivity: UIViewController {
             commentView.isHidden = true
             return
         }
-        
+
         let fileName = appDelegate.userBaseUrl + "-" + appDelegate.user + ".png"
         let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
         if let image = UIImage(contentsOfFile: fileNameLocalPath) {
@@ -100,7 +100,7 @@ class NCActivity: UIViewController {
         } else {
             imageItem.image = UIImage(named: "avatar")
         }
-        
+
         if activeAccount.displayName.isEmpty {
             labelUser.text = activeAccount.user
         } else {
@@ -108,14 +108,14 @@ class NCActivity: UIViewController {
         }
         labelUser.textColor = NCBrandColor.shared.label
     }
-    
+
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
-        
+
         appDelegate.activeViewController = self
 
         NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
-        
+
         initialize()
     }
 
@@ -139,7 +139,7 @@ class NCActivity: UIViewController {
     @objc func changeTheming() {
         tableView.reloadData()
     }
-    
+
     @IBAction func newCommentFieldDidEndOnExit(textField: UITextField) {
         guard
             let message = textField.text,
@@ -147,7 +147,7 @@ class NCActivity: UIViewController {
             let metadata = self.metadata
         else { return }
 
-        NCCommunication.shared.putComments(fileId: metadata.fileId, message: message) { (account, errorCode, errorDescription) in
+        NCCommunication.shared.putComments(fileId: metadata.fileId, message: message) { _, errorCode, errorDescription in
             if errorCode == 0 {
                 self.newCommentField.text = ""
                 self.loadComments()
@@ -177,19 +177,19 @@ class NCActivity: UIViewController {
 // MARK: - Table View
 
 extension NCActivity: UITableViewDelegate {
-    
+
     func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
         return 120
     }
-    
+
     func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
         return 60
     }
-    
+
     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
         return UITableView.automaticDimension
     }
-    
+
     func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
 
         let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 60))
@@ -237,16 +237,16 @@ extension NCActivity: UITableViewDataSource {
             return UITableViewCell()
         }
     }
-    
+
     func makeCommentCell(_ comment: tableComments, for indexPath: IndexPath) -> UITableViewCell {
         guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? NCShareCommentsCell else {
             return UITableViewCell()
         }
-        
+
         cell.tableComments = comment
         cell.delegate = self
         cell.sizeToFit()
-        
+
         // Image
         let fileName = appDelegate.userBaseUrl + "-" + comment.actorId + ".png"
         NCOperationQueue.shared.downloadAvatar(user: comment.actorId, dispalyName: comment.actorDisplayName, fileName: fileName, cell: cell, view: tableView)
@@ -265,37 +265,37 @@ extension NCActivity: UITableViewDataSource {
         } else {
             cell.buttonMenu.isHidden = true
         }
-        
+
         return cell
     }
-    
+
     func makeActivityCell(_ activity: tableActivity, for indexPath: IndexPath) -> UITableViewCell {
         guard let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as? NCActivityTableViewCell else {
             return UITableViewCell()
         }
-        
+
         var orderKeysId: [String] = []
-        
+
         cell.idActivity = activity.idActivity
-        
+
         cell.avatar.image = nil
         cell.avatar.isHidden = true
         cell.subjectTrailingConstraint.constant = 10
         cell.didSelectItemEnable = self.didSelectItemEnable
         cell.subject.textColor = NCBrandColor.shared.label
         cell.viewController = self
-        
+
         // icon
         if activity.icon.count > 0 {
-            
+
             let fileNameIcon = (activity.icon as NSString).lastPathComponent
             let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + fileNameIcon
-            
+
             if FileManager.default.fileExists(atPath: fileNameLocalPath) {
                 let image = NCUtility.shared.loadImage(named: fileNameIcon, color: NCBrandColor.shared.gray)
                 cell.icon.image = image
             } else {
-                NCCommunication.shared.downloadContent(serverUrl: activity.icon) { (account, data, errorCode, errorMessage) in
+                NCCommunication.shared.downloadContent(serverUrl: activity.icon) { _, data, errorCode, _ in
                     if errorCode == 0 {
                         do {
                             try data!.write(to: NSURL(fileURLWithPath: fileNameLocalPath) as URL, options: .atomic)
@@ -305,39 +305,39 @@ extension NCActivity: UITableViewDataSource {
                 }
             }
         }
-        
+
         // avatar
         if activity.user.count > 0 && activity.user != appDelegate.userId {
-            
+
             cell.subjectTrailingConstraint.constant = 50
             cell.avatar.isHidden = false
             cell.fileUser = activity.user
-            
+
             let fileName = appDelegate.userBaseUrl + "-" + activity.user + ".png"
-            
+
             NCOperationQueue.shared.downloadAvatar(user: activity.user, dispalyName: nil, fileName: fileName, cell: cell, view: tableView)
         }
-        
+
         // subject
         if activity.subjectRich.count > 0 {
-            
+
             var subject = activity.subjectRich
             var keys: [String] = []
-            
+
             if let regex = try? NSRegularExpression(pattern: "\\{[a-z0-9]+\\}", options: .caseInsensitive) {
                 let string = subject as NSString
                 keys = regex.matches(in: subject, options: [], range: NSRange(location: 0, length: string.length)).map {
                     string.substring(with: $0.range).replacingOccurrences(of: "[\\{\\}]", with: "", options: .regularExpression)
                 }
             }
-            
+
             for key in keys {
                 if let result = NCManageDatabase.shared.getActivitySubjectRich(account: appDelegate.account, idActivity: activity.idActivity, key: key) {
                     orderKeysId.append(result.id)
                     subject = subject.replacingOccurrences(of: "{\(key)}", with: "<bold>" + result.name + "</bold>")
                 }
             }
-            
+
             let normal = Style {
                 $0.font = UIFont.systemFont(ofSize: cell.subject.font.pointSize)
                 $0.lineSpacing = 1.5
@@ -346,11 +346,11 @@ extension NCActivity: UITableViewDataSource {
             let date = Style { $0.font = UIFont.systemFont(ofSize: cell.subject.font.pointSize - 3)
                 $0.color = UIColor.lightGray
             }
-            
-            subject = subject + "\n" + "<date>" + CCUtility.dateDiff(activity.date as Date) + "</date>"
+
+            subject += "\n" + "<date>" + CCUtility.dateDiff(activity.date as Date) + "</date>"
             cell.subject.attributedText = subject.set(style: StyleGroup(base: normal, ["bold": bold, "date": date]))
         }
-        
+
         // CollectionView
         cell.activityPreviews = NCManageDatabase.shared.getActivityPreview(account: activity.account, idActivity: activity.idActivity, orderKeysId: orderKeysId)
         if cell.activityPreviews.count == 0 {
@@ -359,7 +359,7 @@ extension NCActivity: UITableViewDataSource {
             cell.collectionViewHeightConstraint.constant = 60
         }
         cell.collectionView.reloadData()
-        
+
         return cell
     }
 }
@@ -406,7 +406,7 @@ extension NCActivity {
             }
         }
     }
-    
+
     func loadDataSource() {
 
         var newItems = [DateCompareable]()
@@ -427,12 +427,12 @@ extension NCActivity {
         }.sorted(by: >)
         self.tableView.reloadData()
     }
-    
+
     func loadComments(disptachGroup: DispatchGroup? = nil) {
         guard showComments, let metadata = metadata else { return }
         disptachGroup?.enter()
 
-        NCCommunication.shared.getComments(fileId: metadata.fileId) { (account, comments, errorCode, errorDescription) in
+        NCCommunication.shared.getComments(fileId: metadata.fileId) { account, comments, errorCode, errorDescription in
             if errorCode == 0, let comments = comments {
                 NCManageDatabase.shared.addComments(comments, account: metadata.account, objectId: metadata.fileId)
             } else if errorCode != NCGlobal.shared.errorResourceNotFound {
@@ -462,7 +462,7 @@ extension NCActivity {
             limit: 1,
             objectId: nil,
             objectType: objectType,
-            previews: true) { (account, activities, errorCode, errorDescription) in
+            previews: true) { account, activities, errorCode, _ in
                 defer { disptachGroup.leave() }
 
                 guard errorCode == 0,
@@ -488,7 +488,7 @@ extension NCActivity {
             limit: min(limit, 200),
             objectId: metadata?.fileId,
             objectType: objectType,
-            previews: true) { (account, activities, errorCode, errorDescription) in
+            previews: true) { account, activities, errorCode, _ in
                 defer { disptachGroup.leave() }
                 guard errorCode == 0,
                       account == self.appDelegate.account,
@@ -526,20 +526,20 @@ extension NCActivity: NCShareCommentsCellDelegate {
             NCMenuAction(
                 title: NSLocalizedString("_edit_comment_", comment: ""),
                 icon: UIImage(named: "edit")!.image(color: NCBrandColor.shared.gray, size: 50),
-                action: { menuAction in
+                action: { _ in
                     guard let metadata = self.metadata, let tableComments = tableComments else { return }
-                    
+
                     let alert = UIAlertController(title: NSLocalizedString("_edit_comment_", comment: ""), message: nil, preferredStyle: .alert)
                     alert.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil))
-                    
+
                     alert.addTextField(configurationHandler: { textField in
                         textField.placeholder = NSLocalizedString("_new_comment_", comment: "")
                     })
-                    
-                    alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in
+
+                    alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
                         guard let message = alert.textFields?.first?.text, message != "" else { return }
 
-                        NCCommunication.shared.updateComments(fileId: metadata.fileId, messageId: tableComments.messageId, message: message) { (account, errorCode, errorDescription) in
+                        NCCommunication.shared.updateComments(fileId: metadata.fileId, messageId: tableComments.messageId, message: message) { _, errorCode, errorDescription in
                             if errorCode == 0 {
                                 self.loadComments()
                             } else {
@@ -552,15 +552,15 @@ extension NCActivity: NCShareCommentsCellDelegate {
                 }
             )
         )
-        
+
         actions.append(
             NCMenuAction(
                 title: NSLocalizedString("_delete_comment_", comment: ""),
                 icon: NCUtility.shared.loadImage(named: "trash"),
-                action: { menuAction in
+                action: { _ in
                     guard let metadata = self.metadata, let tableComments = tableComments else { return }
 
-                    NCCommunication.shared.deleteComments(fileId: metadata.fileId, messageId: tableComments.messageId) { (account, errorCode, errorDescription) in
+                    NCCommunication.shared.deleteComments(fileId: metadata.fileId, messageId: tableComments.messageId) { _, errorCode, errorDescription in
                         if errorCode == 0 {
                             self.loadComments()
                         } else {
@@ -574,4 +574,3 @@ extension NCActivity: NCShareCommentsCellDelegate {
         presentMenu(with: actions)
     }
 }
-

+ 69 - 69
iOSClient/Activity/NCActivityTableViewCell.swift

@@ -25,16 +25,16 @@ import Foundation
 import NCCommunication
 
 class NCActivityCollectionViewCell: UICollectionViewCell {
-    
+
     @IBOutlet weak var imageView: UIImageView!
-    
+
     override func awakeFromNib() {
         super.awakeFromNib()
     }
 }
 
 class NCActivityTableViewCell: UITableViewCell, NCCellProtocol {
-    
+
     private let appDelegate = UIApplication.shared.delegate as! AppDelegate
 
     @IBOutlet weak var collectionView: UICollectionView!
@@ -50,8 +50,8 @@ class NCActivityTableViewCell: UITableViewCell, NCCellProtocol {
     var account: String = ""
     var activityPreviews: [tableActivityPreview] = []
     var didSelectItemEnable: Bool = true
-    var viewController: UIViewController? = nil
-    
+    var viewController: UIViewController?
+
     var fileAvatarImageView: UIImageView? {
         get {
             return avatar
@@ -94,20 +94,20 @@ class NCActivityTableViewCell: UITableViewCell, NCCellProtocol {
 // MARK: - Collection View
 
 extension NCActivityTableViewCell: UICollectionViewDelegate {
-    
+
     func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
-        
+
         // Select not permitted
         if !didSelectItemEnable {
             return
         }
-        
+
         let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as? NCActivityCollectionViewCell
-        
+
         let activityPreview = activityPreviews[indexPath.row]
-        
+
         if activityPreview.view == "trashbin" {
-            
+
             var responder: UIResponder? = collectionView
             while !(responder is UIViewController) {
                 responder = responder?.next
@@ -116,7 +116,7 @@ extension NCActivityTableViewCell: UICollectionViewDelegate {
                 }
             }
             if (responder as? UIViewController)!.navigationController != nil {
-                if let viewController = UIStoryboard.init(name: "NCTrash", bundle: nil).instantiateInitialViewController() as? NCTrash {
+                if let viewController = UIStoryboard(name: "NCTrash", bundle: nil).instantiateInitialViewController() as? NCTrash {
                     if let result = NCManageDatabase.shared.getTrashItem(fileId: String(activityPreview.fileId), account: activityPreview.account) {
                         viewController.blinkFileId = result.fileId
                         viewController.trashPath = result.filePath
@@ -126,16 +126,16 @@ extension NCActivityTableViewCell: UICollectionViewDelegate {
                     }
                 }
             }
-            
+
             return
         }
-        
+
         if activityPreview.view == "files" && activityPreview.mimeType != "dir" {
-            
+
             guard let activitySubjectRich = NCManageDatabase.shared.getActivitySubjectRich(account: activityPreview.account, idActivity: activityPreview.idActivity, id: String(activityPreview.fileId)) else {
                 return
             }
-            
+
             if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "fileId == %@", activitySubjectRich.id)) {
                 if let filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) {
                     do {
@@ -152,51 +152,51 @@ extension NCActivityTableViewCell: UICollectionViewDelegate {
                     }
                 }
             }
-            
+
             var pathComponents = activityPreview.link.components(separatedBy: "?")
             pathComponents = pathComponents[1].components(separatedBy: "&")
             var serverUrlFileName = pathComponents[0].replacingOccurrences(of: "dir=", with: "").removingPercentEncoding!
             serverUrlFileName = appDelegate.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: activityPreview.account) + serverUrlFileName + "/" + activitySubjectRich.name
-            
+
             let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(activitySubjectRich.id, fileNameView: activitySubjectRich.name)!
-            
+
             NCUtility.shared.startActivityIndicator(backgroundView: (appDelegate.window?.rootViewController?.view)!, blurEffect: true)
-            
-            NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { (_) in
-                
-            }, taskHandler: { (_) in
-                
-            }, progressHandler: { (_) in
-                
-            }) { (account, etag, date, lenght, allHeaderFields, error, errorCode, errorDescription) in
-                
+
+            NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { _ in
+
+            }, taskHandler: { _ in
+
+            }, progressHandler: { _ in
+
+            }) { account, _, _, _, _, _, errorCode, _ in
+
                 if account == self.appDelegate.account && errorCode == 0 {
-                    
+
                     let serverUrl = (serverUrlFileName as NSString).deletingLastPathComponent
                     let fileName = (serverUrlFileName as NSString).lastPathComponent
                     let serverUrlFileName = serverUrl + "/" + fileName
-                    
-                    NCNetworking.shared.readFile(serverUrlFileName: serverUrlFileName, account: activityPreview.account) { (account, metadata, errorCode, errorDescription) in
-                        
+
+                    NCNetworking.shared.readFile(serverUrlFileName: serverUrlFileName, account: activityPreview.account) { account, metadata, errorCode, _ in
+
                         NCUtility.shared.stopActivityIndicator()
-                        
-                        if account == self.appDelegate.account && errorCode == 0  {
-                            
+
+                        if account == self.appDelegate.account && errorCode == 0 {
+
                             // move from id to oc:id + instanceid (ocId)
                             let atPath = CCUtility.getDirectoryProviderStorage()! + "/" + activitySubjectRich.id
                             let toPath = CCUtility.getDirectoryProviderStorage()! + "/" + metadata!.ocId
-                                                       
+
                             CCUtility.moveFile(atPath: atPath, toPath: toPath)
-                                                       
+
                             NCManageDatabase.shared.addMetadata(metadata!)
                             if let viewController = self.viewController {
                                 NCViewer.shared.view(viewController: viewController, metadata: metadata!, metadatas: [metadata!], imageIcon: cell?.imageView.image)
                             }
                         }
                     }
-                    
+
                 } else {
-                    
+
                     NCUtility.shared.stopActivityIndicator()
                 }
             }
@@ -205,70 +205,70 @@ extension NCActivityTableViewCell: UICollectionViewDelegate {
 }
 
 extension NCActivityTableViewCell: UICollectionViewDataSource {
-    
+
     func numberOfSections(in collectionView: UICollectionView) -> Int {
         return 1
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
         return activityPreviews.count
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
-        
+
         let cell: NCActivityCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! NCActivityCollectionViewCell
-            
+
         cell.imageView.image = nil
-        
+
         let activityPreview = activityPreviews[indexPath.row]
         let fileId = String(activityPreview.fileId)
-        
+
         // Trashbin
         if activityPreview.view == "trashbin" {
-            
+
             let source = activityPreview.source
-            
-            NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: source, fileName: nil, width: 100, rewrite: false, account: appDelegate.account) { (imageNamePath) in
+
+            NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: source, fileName: nil, width: 100, rewrite: false, account: appDelegate.account) { imageNamePath in
                 if imageNamePath != nil {
                     if let image = UIImage(contentsOfFile: imageNamePath!) {
                         cell.imageView.image = image
                     }
                 } else {
-                     cell.imageView.image = UIImage.init(named: "file")
+                     cell.imageView.image = UIImage(named: "file")
                 }
             }
-            
+
         } else {
-            
+
             if activityPreview.isMimeTypeIcon {
-                
+
                 let source = activityPreview.source
-                
-                NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: source, fileName: nil, width: 100, rewrite: false, account: appDelegate.account) { (imageNamePath) in
+
+                NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: source, fileName: nil, width: 100, rewrite: false, account: appDelegate.account) { imageNamePath in
                     if imageNamePath != nil {
                         if let image = UIImage(contentsOfFile: imageNamePath!) {
                             cell.imageView.image = image
                         }
                     } else {
-                        cell.imageView.image = UIImage.init(named: "file")
+                        cell.imageView.image = UIImage(named: "file")
                     }
                 }
-                
+
             } else {
-                
+
                 if let activitySubjectRich = NCManageDatabase.shared.getActivitySubjectRich(account: account, idActivity: idActivity, id: fileId) {
-                    
+
                     let fileNamePath = CCUtility.getDirectoryUserData() + "/" + activitySubjectRich.name
-                    
+
                     if FileManager.default.fileExists(atPath: fileNamePath) {
-                        
+
                         if let image = UIImage(contentsOfFile: fileNamePath) {
                             cell.imageView.image = image
                         }
-                        
+
                     } else {
-                        
-                        NCCommunication.shared.downloadPreview(fileNamePathOrFileId: activityPreview.source, fileNamePreviewLocalPath: fileNamePath, widthPreview: 0, heightPreview: 0, etag: nil, useInternalEndpoint: false) { (account, imagePreview, imageIcon, imageOriginal, etag, errorCode, errorDescription) in
+
+                        NCCommunication.shared.downloadPreview(fileNamePathOrFileId: activityPreview.source, fileNamePreviewLocalPath: fileNamePath, widthPreview: 0, heightPreview: 0, etag: nil, useInternalEndpoint: false) { _, imagePreview, _, _, _, errorCode, _ in
                             if errorCode == 0 && imagePreview != nil {
                                 self.collectionView.reloadData()
                             }
@@ -277,22 +277,22 @@ extension NCActivityTableViewCell: UICollectionViewDataSource {
                 }
             }
         }
-            
+
         return cell
     }
-    
+
 }
 
 extension NCActivityTableViewCell: UICollectionViewDelegateFlowLayout {
-    
+
     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
         return CGSize(width: 50, height: 50)
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
         return 20
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
         return UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
     }

+ 154 - 152
iOSClient/AppDelegate.swift

@@ -51,12 +51,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
     @objc var activeViewController: UIViewController?
     var mainTabBar: NCMainTabBar?
     var activeMetadata: tableMetadata?
-    
-    var listFilesVC: [String:NCFiles] = [:]
-    var listFavoriteVC: [String:NCFavorite] = [:]
-    var listOfflineVC: [String:NCOffline] = [:]
-    var listProgress: [String:NCGlobal.progressType] = [:]
-    
+
+    var listFilesVC: [String: NCFiles] = [:]
+    var listFavoriteVC: [String: NCFavorite] = [:]
+    var listOfflineVC: [String: NCOffline] = [:]
+    var listProgress: [String: NCGlobal.progressType] = [:]
+
     var disableSharesView: Bool = false
     var documentPickerViewController: NCDocumentPickerViewController?
     var networkingProcessUpload: NCNetworkingProcessUpload?
@@ -67,37 +67,37 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
     private var privacyProtectionWindow: UIWindow?
     
     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
-        
+
         let userAgent = CCUtility.getUserAgent() as String
         let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
         let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
 
-        UserDefaults.standard.register(defaults: ["UserAgent" : userAgent])
+        UserDefaults.standard.register(defaults: ["UserAgent": userAgent])
         if !CCUtility.getDisableCrashservice() && !NCBrandOptions.shared.disable_crash_service {
             FirebaseApp.configure()
         }
-        
+
         CCUtility.createDirectoryStandard()
         CCUtility.emptyTemporaryDirectory()
-        
+
         NCCommunicationCommon.shared.setup(delegate: NCNetworking.shared)
         NCCommunicationCommon.shared.setup(userAgent: userAgent)
-        
+
         startTimerErrorNetworking()
-        
+
         // LOG
         var levelLog = 0
         if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
             NCCommunicationCommon.shared.pathLog = pathDirectoryGroup
         }
-        
+
         if NCBrandOptions.shared.disable_log {
-            
+
             NCUtilityFileSystem.shared.deleteFile(filePath: NCCommunicationCommon.shared.filenamePathLog)
             NCUtilityFileSystem.shared.deleteFile(filePath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/" + NCCommunicationCommon.shared.filenameLog)
-            
+
         } else {
-            
+
             levelLog = CCUtility.getLogLevel()
             NCCommunicationCommon.shared.levelLog = levelLog
             NCCommunicationCommon.shared.copyLogToDocumentDirectory = true
@@ -107,10 +107,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
                 NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS)
             }
         }
-        
+
         // Activate user account
         if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
-            
+
             // FIX 3.0.5 lost urlbase
             if activeAccount.urlBase.count == 0 {
                 let user = activeAccount.user + " "
@@ -118,28 +118,28 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
                 activeAccount.urlBase = urlBase
                 NCManageDatabase.shared.updateAccount(activeAccount)
             }
-            
+
             settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
-            
+
         } else {
-            
+
             CCUtility.deleteAllChainStore()
             if let bundleID = Bundle.main.bundleIdentifier {
                 UserDefaults.standard.removePersistentDomain(forName: bundleID)
             }
         }
-        
+
         // initialize
         NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
         NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
-        
+
         // Process upload
-        networkingProcessUpload = NCNetworkingProcessUpload.init()
-        
+        networkingProcessUpload = NCNetworkingProcessUpload()
+
         // Push Notification & display notification
         application.registerForRemoteNotifications()
         UNUserNotificationCenter.current().delegate = self
-        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (_, _) in }
+        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in }
 
         // Store review
         if !NCUtility.shared.isSimulatorOrTestFlight() {
@@ -147,7 +147,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
             review.incrementAppRuns()
             review.showStoreReview()
         }
-        
+
         // Background task: register
         if #available(iOS 13.0, *) {
             BGTaskScheduler.shared.register(forTaskWithIdentifier: NCGlobal.shared.refreshTask, using: nil) { task in
@@ -159,7 +159,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
         } else {
             application.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
         }
-        
+
         // Intro
         if NCBrandOptions.shared.disable_intro {
             CCUtility.setIntro(true)
@@ -175,17 +175,17 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
                 }
             }
         }
-        
+
         // Passcode
         DispatchQueue.main.async {
             self.presentPasscode {
                 self.enableTouchFaceID()
             }
         }
-        
+
         return true
     }
-    
+
     // MARK: - Life Cycle
 
     // L' applicazione entrerà in primo piano (attivo sempre)
@@ -196,42 +196,44 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
         
         NCSettingsBundleHelper.setVersionAndBuildNumber()
         
+        NCSettingsBundleHelper.setVersionAndBuildNumber()
+
         if account == "" { return }
 
         networkingProcessUpload?.verifyUploadZombie()
-        
+
         NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationDidBecomeActive)
     }
-    
+
     // L' applicazione entrerà in primo piano (attivo solo dopo il background)
     func applicationWillEnterForeground(_ application: UIApplication) {
-        
+
         if account == "" { return }
         guard let activeAccount = NCManageDatabase.shared.getActiveAccount() else { return }
-        
+
         // close HUD
         IHProgressHUD.dismiss()
-        
+
         // Account changed ??
         if activeAccount.account != account {
             settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
-            
+
             NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
         }
-        
+
         NCCommunicationCommon.shared.writeLog("Application will enter in foreground")
-        
+
         // START TIMER UPLOAD PROCESS
         if NCUtility.shared.isSimulator() {
             networkingProcessUpload?.startTimer()
         }
         
         // Initialize Auto upload
-        NCAutoUpload.shared.initAutoUpload(viewController: nil) { (_) in }
-                
+        NCAutoUpload.shared.initAutoUpload(viewController: nil) { _ in }
+
         // Required unsubscribing / subscribing
         NCPushNotification.shared().pushNotification()
-            
+
         // Request Service Server Nextcloud
         NCService.shared.startRequestServicesServer()
         
@@ -245,7 +247,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
 
     // L' applicazione si dimetterà dallo stato di attivo
     func applicationWillResignActive(_ application: UIApplication) {
-        
+
         if account == "" { return }
 
         // Privacy
@@ -261,13 +263,13 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
         if let directory = CCUtility.getDirectoryProviderStorage() {
             NCUtilityFileSystem.shared.cleanUp(directory: directory, days: TimeInterval(days))
         }
-        
+
         NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationWillResignActive)
     }
-    
+
     // L' applicazione è entrata nello sfondo
     func applicationDidEnterBackground(_ application: UIApplication) {
-        
+
         if account == "" { return }
         
         // STOP TIMER UPLOAD PROCESS
@@ -285,49 +287,49 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
         
         NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationDidEnterBackground)
     }
-    
+
     // L'applicazione terminerà
     func applicationWillTerminate(_ application: UIApplication) {
-        
+
         NCNetworking.shared.cancelAllDownloadTransfer()
         NCCommunicationCommon.shared.writeLog("bye bye")
     }
-    
+
     // MARK: -
 
     @objc private func initialize() {
-        
+
         if account == "" { return }
 
         NCCommunicationCommon.shared.writeLog("initialize Main")
                 
         // Registeration push notification
         NCPushNotification.shared().pushNotification()
-        
+
         // Setting Theming
         NCBrandColor.shared.settingThemingColor(account: account)
-        
+
         // Start Auto Upload
-        NCAutoUpload.shared.initAutoUpload(viewController: nil) { (_) in }
-        
+        NCAutoUpload.shared.initAutoUpload(viewController: nil) { _ in }
+
         // Start services
         NCService.shared.startRequestServicesServer()
-        
+
         // close detail
         NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterMenuDetailClose)
-        
+
         // Registeration domain File Provider
-        //FileProviderDomain *fileProviderDomain = [FileProviderDomain new];
-        //[fileProviderDomain removeAllDomains];
-        //[fileProviderDomain registerDomains];
+        // FileProviderDomain *fileProviderDomain = [FileProviderDomain new];
+        // [fileProviderDomain removeAllDomains];
+        // [fileProviderDomain registerDomains];
     }
-    
+
     // MARK: - Background Task
-    
+
     @available(iOS 13.0, *)
     func scheduleAppRefresh() {
-        
-        let request = BGAppRefreshTaskRequest.init(identifier: NCGlobal.shared.refreshTask)
+
+        let request = BGAppRefreshTaskRequest(identifier: NCGlobal.shared.refreshTask)
         request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60) // Refresh after 5 minutes.
         do {
             try BGTaskScheduler.shared.submit(request)
@@ -336,11 +338,11 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
             NCCommunicationCommon.shared.writeLog("Refresh task failed to submit request: \(error)")
         }
     }
-    
+
     @available(iOS 13.0, *)
     func scheduleBackgroundProcessing() {
-        
-        let request = BGProcessingTaskRequest.init(identifier: NCGlobal.shared.processingTask)
+
+        let request = BGProcessingTaskRequest(identifier: NCGlobal.shared.processingTask)
         request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60) // Refresh after 5 minutes.
         request.requiresNetworkConnectivity = true
         request.requiresExternalPower = false
@@ -351,18 +353,18 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
             NCCommunicationCommon.shared.writeLog("Background Processing task failed to submit request: \(error)")
         }
     }
-    
+
     @available(iOS 13.0, *)
     func handleRefreshTask(_ task: BGTask) {
-        
+
         if account == "" {
             task.setTaskCompleted(success: true)
             return
         }
-        
+
         NCCommunicationCommon.shared.writeLog("Start handler refresh task [Auto upload]")
-        
-        NCAutoUpload.shared.initAutoUpload(viewController: nil) { (items) in
+
+        NCAutoUpload.shared.initAutoUpload(viewController: nil) { _ in
             DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                 NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUpdateBadgeNumber)
                 NCCommunicationCommon.shared.writeLog("Completition handler refresh task with %lu uploads [Auto upload]")
@@ -370,42 +372,42 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
             }
         }
     }
-    
+
     @available(iOS 13.0, *)
     func handleProcessingTask(_ task: BGTask) {
-        
+
         if account == "" {
             task.setTaskCompleted(success: true)
             return
         }
-        
+
         NCCommunicationCommon.shared.writeLog("Start handler processing task [Synchronize Favorite & Offline]")
-        
-        NCNetworking.shared.listingFavoritescompletion(selector: NCGlobal.shared.selectorReadFile) { (account, metadatas, errorCode, errorDescription) in
+
+        NCNetworking.shared.listingFavoritescompletion(selector: NCGlobal.shared.selectorReadFile) { _, _, errorCode, _ in
             NCCommunicationCommon.shared.writeLog("Completition listing favorite with error: \(errorCode)")
         }
-        
+
         NCService.shared.synchronizeOffline(account: account)
-        
+
         DispatchQueue.main.asyncAfter(deadline: .now() + 25) {
             NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUpdateBadgeNumber)
             NCCommunicationCommon.shared.writeLog("Completition handler processing task [Synchronize Favorite & Offline]")
             task.setTaskCompleted(success: true)
         }
     }
-    
+
     // MARK: - Fetch
 
     func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
-        
+
         if account == "" {
             completionHandler(UIBackgroundFetchResult.noData)
             return
         }
-        
+
         NCCommunicationCommon.shared.writeLog("Start perform Fetch [Auto upload]")
-        
-        NCAutoUpload.shared.initAutoUpload(viewController: nil) { (items) in
+
+        NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
             NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUpdateBadgeNumber)
             NCCommunicationCommon.shared.writeLog("Completition perform Fetch with \(items) uploads [Auto upload]")
             if items == 0 {
@@ -415,25 +417,25 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
             }
         }
     }
-    
+
     // MARK: - Background Networking Session
 
     func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
-        
+
         NCCommunicationCommon.shared.writeLog("Start handle Events For Background URLSession: \(identifier)")
         backgroundSessionCompletionHandler = completionHandler
     }
-    
+
     // MARK: - Push Notifications
-    
+
     func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
         completionHandler(UNNotificationPresentationOptions.alert)
     }
-    
+
     func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
         completionHandler()
     }
-    
+
     func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
         NCNetworking.shared.checkPushNotificationServerProxyCertificateUntrusted(viewController: self.window?.rootViewController) { errorCode in
             if errorCode == 0 {
@@ -441,30 +443,30 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
             }
         }
     }
-    
-    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
-        NCPushNotification.shared().applicationdidReceiveRemoteNotification(userInfo) { (result) in
+
+    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
+        NCPushNotification.shared().applicationdidReceiveRemoteNotification(userInfo) { result in
             completionHandler(result)
         }
     }
-        
+
     // MARK: - Login & checkErrorNetworking
 
     @objc func openLogin(viewController: UIViewController?, selector: Int, openLoginWeb: Bool) {
-       
+
         // use appConfig [MDM]
         if NCBrandOptions.shared.use_configuration {
-            
+
             if activeAppConfigView?.view.window == nil {
                 activeAppConfigView = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCAppConfigView") as? NCAppConfigView
                 showLoginViewController(activeAppConfigView, contextViewController: viewController)
             }
             return
         }
-        
+
         // only for personalized LoginWeb [customer]
         if NCBrandOptions.shared.use_login_web_personalized {
-            
+
             if activeLoginWeb?.view.window == nil {
                 activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
                 activeLoginWeb?.urlBase = NCBrandOptions.shared.loginBaseUrl
@@ -472,10 +474,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
             }
             return
         }
-        
+
         // Nextcloud standard login
         if selector == NCGlobal.shared.introSignup {
-            
+
             if activeLoginWeb?.view.window == nil {
                 activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
                 if selector == NCGlobal.shared.introSignup {
@@ -485,25 +487,25 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
                 }
                 showLoginViewController(activeLoginWeb, contextViewController: viewController)
             }
-            
+
         } else if NCBrandOptions.shared.disable_intro && NCBrandOptions.shared.disable_request_login_url {
-            
+
             if activeLoginWeb?.view.window == nil {
                 activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
                 activeLoginWeb?.urlBase = NCBrandOptions.shared.loginBaseUrl
                 showLoginViewController(activeLoginWeb, contextViewController: viewController)
             }
-            
+
         } else if openLoginWeb {
-            
+
             if activeLoginWeb?.view.window == nil {
                 activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
                 activeLoginWeb?.urlBase = urlBase
                 showLoginViewController(activeLoginWeb, contextViewController: viewController)
             }
-            
+
         } else {
-            
+
             if activeLogin?.view.window == nil {
                 activeLogin = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLogin") as? NCLogin
                 showLoginViewController(activeLogin, contextViewController: viewController)
@@ -511,8 +513,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
         }
     }
 
-    func showLoginViewController(_ viewController:UIViewController?, contextViewController: UIViewController?) {
-        
+    func showLoginViewController(_ viewController: UIViewController?, contextViewController: UIViewController?) {
+
         if contextViewController == nil {
             if let viewController = viewController {
                 let navigationController = NCLoginNavigationController.init(rootViewController: viewController)
@@ -543,7 +545,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
     @objc func startTimerErrorNetworking() {
         timerErrorNetworking = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(checkErrorNetworking), userInfo: nil, repeats: true)
     }
-    
+
     @objc private func checkErrorNetworking() {
         
         // check unauthorized server (401/403)
@@ -586,23 +588,23 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
         
         window?.rootViewController?.present(alertController, animated: true)
     }
-    
+
     func viewCertificateDetailsDismiss(host: String) {
         trustCertificateError(host: host)
     }
-    
+
     // MARK: - Account
-    
+
     @objc func settingAccount(_ account: String, urlBase: String, user: String, userId: String, password: String) {
-        
+
         self.account = account
         self.urlBase = urlBase
         self.user = user
         self.userId = userId
         self.password = password
-        
+
         _ = NCFunctionCenter.shared
-        
+
         NCCommunicationCommon.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: urlBase)
         NCCommunicationCommon.shared.setup(webDav: NCUtilityFileSystem.shared.getWebDAV(account: account))
         let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
@@ -610,9 +612,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
             NCCommunicationCommon.shared.setup(nextcloudVersion: serverVersionMajor)
         }
     }
-    
+
     @objc func deleteAccount(_ account: String, wipe: Bool) {
-        
+
         if let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) {
             NCPushNotification.shared().unsubscribingNextcloudServerPushNotification(account.account, urlBase: account.urlBase, user: account.user, withSubscribing: false)
         }
@@ -626,7 +628,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
         CCUtility.clearAllKeysEnd(toEnd: account)
         CCUtility.clearAllKeysPushNotification(account)
         CCUtility.setPassword(account, password: nil)
-        
+
         if wipe {
             settingAccount("", urlBase: "", user: "", userId: "", password: "")
             let accounts = NCManageDatabase.shared.getAccounts()
@@ -639,25 +641,25 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
             }
         }
     }
-    
+
     @objc func changeAccount(_ account: String) {
-        
+
         NCManageDatabase.shared.setAccountActive(account)
         if let tableAccount = NCManageDatabase.shared.getActiveAccount() {
-            
+
             NCOperationQueue.shared.cancelAllQueue()
             NCNetworking.shared.cancelAllTask()
-            
+
             settingAccount(tableAccount.account, urlBase: tableAccount.urlBase, user: tableAccount.user, userId: tableAccount.userId, password: CCUtility.getPassword(tableAccount.account))
-            
+
             NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
         }
     }
-    
+
     // MARK: - Account Request
-    
+
     func accountRequestChangeAccount(account: String) {
-        
+
         changeAccount(account)
     }
     
@@ -671,28 +673,28 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
         if accounts.count > 1 {
             
             if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
-               
+
                 vcAccountRequest.activeAccount = NCManageDatabase.shared.getActiveAccount()
                 vcAccountRequest.accounts = accounts
                 vcAccountRequest.enableTimerProgress = true
                 vcAccountRequest.enableAddAccount = false
                 vcAccountRequest.dismissDidEnterBackground = false
                 vcAccountRequest.delegate = self
-                
+
                 let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/5)
                 let numberCell = accounts.count
                 let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
-                
+
                 let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height+20)
                 popup.backgroundAlpha = 0.8
-                
+
                 UIApplication.shared.keyWindow?.rootViewController?.present(popup, animated: true)
                 
                 vcAccountRequest.startTimer()
             }
         }
     }
-    
+
     // MARK: - Passcode
     
     func presentPasscode(completion: @escaping ()->()) {
@@ -767,11 +769,11 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
             }
         }
     }
-    
+
     func passcodeViewController(_ passcodeViewController: TOPasscodeViewController, isCorrectCode code: String) -> Bool {
         return code == CCUtility.getPasscode()
     }
-    
+
     // MARK: - Privacy Protection
        
     private func showPrivacyProtectionWindow() {
@@ -797,10 +799,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
     
     // MARK: - Open URL
 
-    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
-        
+    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
+
         if account == "" { return false }
-        
+
         let scheme = url.scheme
         let action = url.host
         var fileName: String = ""
@@ -808,16 +810,16 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
         var matchedAccount: tableAccount?
 
         if scheme == "nextcloud" && action == "open-file" {
-            
-            if let urlComponents = URLComponents.init(url: url, resolvingAgainstBaseURL: false) {
-                
+
+            if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
+
                 let queryItems = urlComponents.queryItems
                 guard let userScheme = CCUtility.value(forKey: "user", fromQueryItems: queryItems) else { return false }
                 guard let pathScheme = CCUtility.value(forKey: "path", fromQueryItems: queryItems) else { return false }
                 guard let linkScheme = CCUtility.value(forKey: "link", fromQueryItems: queryItems) else { return false }
-                
+
                 if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
-                    
+
                     let urlBase = URL(string: activeAccount.urlBase)
                     let user = activeAccount.user
                     if linkScheme.contains(urlBase?.host ?? "") && userScheme == user {
@@ -833,9 +835,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
                             }
                         }
                     }
-                    
+
                     if matchedAccount != nil {
-                        
+
                         let webDAV = NCUtilityFileSystem.shared.getWebDAV(account: self.account) + "/files/" + self.userId
                         if pathScheme.contains("/") {
                             fileName = (pathScheme as NSString).lastPathComponent
@@ -844,28 +846,28 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
                             fileName = pathScheme
                             serverUrl = matchedAccount!.urlBase + "/" + webDAV
                         }
-                        
+
                         DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                             NCFunctionCenter.shared.openFileViewInFolder(serverUrl: serverUrl, fileName: fileName)
                         }
-                        
+
                     } else {
-                        
+
                         guard let domain = URL(string: linkScheme)?.host else { return true }
                         fileName = (pathScheme as NSString).lastPathComponent
                         let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), userScheme, domain, fileName)
-                        
+
                         let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
                         alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
-                                           
+
                         window?.rootViewController?.present(alertController, animated: true, completion: { })
-                        
+
                         return false
                     }
                 }
             }
         }
-        
+
         return true
     }
 }
@@ -875,16 +877,16 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
 extension AppDelegate: NCAudioRecorderViewControllerDelegate {
 
     func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
-        
+
         guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() else { return }
         navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
         let appDelegate = UIApplication.shared.delegate as! AppDelegate
-        
+
         let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadVoiceNote
         viewController.setup(serverUrl: appDelegate.activeServerUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
         appDelegate.window?.rootViewController?.present(navigationController, animated: true, completion: nil)
     }
-    
+
     func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
     }
 }

+ 51 - 51
iOSClient/BackgroundImageColor/NCBackgroundImageColor.swift

@@ -24,7 +24,7 @@
 import UIKit
 import ChromaColorPicker
 
-public protocol NCBackgroundImageColorDelegate {
+public protocol NCBackgroundImageColorDelegate: AnyObject {
     func colorPickerCancel()
     func colorPickerWillChange(color: UIColor)
     func colorPickerDidChange(lightColor: String, darkColor: String)
@@ -41,7 +41,7 @@ class NCBackgroundImageColor: UIViewController {
 
     @IBOutlet weak var titleLabel: UILabel!
     @IBOutlet weak var chromaColorPickerView: UIView!
-    
+
     @IBOutlet weak var whiteButton: UIButton!
     @IBOutlet weak var orangeButton: UIButton!
     @IBOutlet weak var redButton: UIButton!
@@ -50,34 +50,34 @@ class NCBackgroundImageColor: UIViewController {
 
     @IBOutlet weak var darkmodeLabel: UILabel!
     @IBOutlet weak var darkmodeSwitch: UISwitch!
-    
+
     @IBOutlet weak var defaultButton: UIButton!
     @IBOutlet weak var cancelButton: UIButton!
     @IBOutlet weak var okButton: UIButton!
-    
+
     private let colorPicker = ChromaColorPicker()
     private let brightnessSlider = ChromaBrightnessSlider()
     private var colorHandle: ChromaColorHandle?
     private let defaultColorPickerSize = CGSize(width: 200, height: 200)
     private let brightnessSliderWidthHeightRatio: CGFloat = 0.1
-    
-    var delegate: NCBackgroundImageColorDelegate?
+
+    weak var delegate: NCBackgroundImageColorDelegate?
     var setupColor: UIColor?
     var darkColor = "#000000"
     var lightColor = "#FFFFFF"
-    
+
     let width: CGFloat = 300
     let height: CGFloat = 450
-    
+
     // MARK: - View Life Cycle
 
     override func viewDidLoad() {
         super.viewDidLoad()
-        
+
         setupColorPicker()
         setupBrightnessSlider()
         setupColorPickerHandles()
-        
+
         titleLabel.text = NSLocalizedString("_background_", comment: "")
         darkmodeLabel.text = NSLocalizedString("_dark_mode_", comment: "")
 
@@ -85,7 +85,7 @@ class NCBackgroundImageColor: UIViewController {
 
         cancelButton.setTitle(NSLocalizedString("_cancel_", comment: ""), for: .normal)
         okButton.setTitle(NSLocalizedString("_ok_", comment: ""), for: .normal)
-        
+
         whiteButton.backgroundColor = .white
         whiteButton.layer.cornerRadius = 5
         whiteButton.layer.borderWidth = 0.5
@@ -97,34 +97,34 @@ class NCBackgroundImageColor: UIViewController {
         orangeButton.layer.borderWidth = 0.5
         orangeButton.layer.borderColor = NCBrandColor.shared.label.cgColor
         orangeButton.layer.masksToBounds = true
-       
+
         redButton.backgroundColor = .red
         redButton.layer.cornerRadius = 5
         redButton.layer.borderWidth = 0.5
         redButton.layer.borderColor = NCBrandColor.shared.label.cgColor
         redButton.layer.masksToBounds = true
-        
+
         greenButton.backgroundColor = .green
         greenButton.layer.cornerRadius = 5
         greenButton.layer.borderWidth = 0.5
         greenButton.layer.borderColor = NCBrandColor.shared.label.cgColor
         greenButton.layer.masksToBounds = true
-        
+
         blackButton.backgroundColor = .black
         blackButton.layer.cornerRadius = 5
         blackButton.layer.borderWidth = 0.5
         blackButton.layer.borderColor = NCBrandColor.shared.label.cgColor
         blackButton.layer.masksToBounds = true
-        
+
         defaultButton.layer.cornerRadius = 15
         defaultButton.layer.borderWidth = 0.5
         defaultButton.layer.borderColor = UIColor.gray.cgColor
         defaultButton.layer.masksToBounds = true
     }
-    
+
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
-        
+
         if traitCollection.userInterfaceStyle == .dark {
             darkmodeSwitch.isOn = true
         } else {
@@ -140,52 +140,52 @@ class NCBackgroundImageColor: UIViewController {
                 lightColor = activeAccount.lightColorBackground
             }
         }
-       
+
         // set color
         if darkmodeSwitch.isOn {
-            if let color = UIColor.init(hex: darkColor) {
+            if let color = UIColor(hex: darkColor) {
                 changeColor(color)
             } else {
                 changeColor(.black)
             }
         } else {
-            if let color = UIColor.init(hex: lightColor) {
+            if let color = UIColor(hex: lightColor) {
                 changeColor(color)
             } else {
                 changeColor(.white)
             }
         }
     }
-    
+
     // MARK: - Action
-    
+
     @IBAction func whiteButtonAction(_ sender: UIButton) {
         changeColor(.white)
     }
-    
+
     @IBAction func orangeButtonAction(_ sender: UIButton) {
         changeColor(.orange)
     }
-    
+
     @IBAction func redButtonAction(_ sender: UIButton) {
         changeColor(.red)
     }
-    
+
     @IBAction func greenButtonAction(_ sender: UIButton) {
         changeColor(.green)
     }
-    
+
     @IBAction func blackButtonAction(_ sender: UIButton) {
         changeColor(.black)
     }
-    
+
     @IBAction func darkmodeAction(_ sender: UISwitch) {
-                
+
         if sender.isOn {
             if darkColor == "" {
                 changeColor(.black)
             } else {
-                if let color = UIColor.init(hex: darkColor) {
+                if let color = UIColor(hex: darkColor) {
                     changeColor(color)
                 }
             }
@@ -193,15 +193,15 @@ class NCBackgroundImageColor: UIViewController {
             if lightColor == "" {
                 changeColor(.white)
             } else {
-                if let color = UIColor.init(hex: lightColor) {
+                if let color = UIColor(hex: lightColor) {
                     changeColor(color)
                 }
             }
         }
     }
-    
+
     @IBAction func defaultAction(_ sender: Any) {
-        
+
         if darkmodeSwitch.isOn {
             darkColor = "#000000"
             changeColor(.black)
@@ -210,28 +210,28 @@ class NCBackgroundImageColor: UIViewController {
             changeColor(.white)
         }
     }
-    
+
     @IBAction func cancelAction(_ sender: Any) {
 
         self.delegate?.colorPickerCancel()
         dismiss(animated: true)
     }
-    
+
     @IBAction func okAction(_ sender: Any) {
-        
+
         var lightColor = self.lightColor
         var darkColor = self.darkColor
-        
+
         if lightColor == "#FFFFFF" { lightColor = "" }
         if darkColor == "#000000" { darkColor = "" }
-        
+
         self.delegate?.colorPickerDidChange(lightColor: lightColor, darkColor: darkColor)
-        
+
         dismiss(animated: true)
     }
-    
+
     // MARK: - ChromaColorPicker
-    
+
     private func setupColorPicker() {
         colorPicker.delegate = self
         colorPicker.translatesAutoresizingMaskIntoConstraints = false
@@ -244,18 +244,18 @@ class NCBackgroundImageColor: UIViewController {
             colorPicker.heightAnchor.constraint(equalToConstant: defaultColorPickerSize.height)
         ])
     }
-    
+
     private func setupBrightnessSlider() {
         brightnessSlider.connect(to: colorPicker)
-        
+
         // Style
         brightnessSlider.trackColor = UIColor.blue
         brightnessSlider.handle.borderWidth = 3.0 // Example of customizing the handle's properties.
-        
+
         // Layout
         brightnessSlider.translatesAutoresizingMaskIntoConstraints = false
         view.addSubview(brightnessSlider)
-        
+
         NSLayoutConstraint.activate([
             brightnessSlider.centerXAnchor.constraint(equalTo: colorPicker.centerXAnchor),
             brightnessSlider.topAnchor.constraint(equalTo: colorPicker.bottomAnchor, constant: 20),
@@ -263,36 +263,36 @@ class NCBackgroundImageColor: UIViewController {
             brightnessSlider.heightAnchor.constraint(equalTo: brightnessSlider.widthAnchor, multiplier: brightnessSliderWidthHeightRatio)
         ])
     }
-    
+
     private func setupColorPickerHandles() {
         colorHandle = colorPicker.addHandle(at: setupColor)
     }
-    
+
     private func changeColor(_ color: UIColor) {
-        
+
         colorHandle?.color = color
         colorPicker.setNeedsLayout()
         brightnessSlider.trackColor = color
-        
+
         if darkmodeSwitch.isOn {
             darkColor = color.hexString
         } else {
             lightColor = color.hexString
         }
-        
+
         self.delegate?.colorPickerWillChange(color: color)
     }
 }
 
 extension NCBackgroundImageColor: ChromaColorPickerDelegate {
     func colorPickerHandleDidChange(_ colorPicker: ChromaColorPicker, handle: ChromaColorHandle, to color: UIColor) {
-        
+
         if darkmodeSwitch.isOn {
             darkColor = color.hexString
         } else {
             lightColor = color.hexString
         }
-        
+
         self.delegate?.colorPickerWillChange(color: color)
     }
 }

+ 1 - 1
iOSClient/Brand/Intro/NCIntroCollectionViewCell.swift

@@ -29,7 +29,7 @@ class NCIntroCollectionViewCell: UICollectionViewCell {
 
     @IBOutlet weak var titleLabel: UILabel!
     @IBOutlet weak var imageView: UIImageView!
-    
+
     override func awakeFromNib() {
         super.awakeFromNib()
     }

+ 9 - 11
iOSClient/Brand/Intro/NCIntroViewController.swift

@@ -33,22 +33,22 @@ class NCIntroViewController: UIViewController, UICollectionViewDataSource, UICol
     @IBOutlet weak var introCollectionView: UICollectionView!
     @IBOutlet weak var pageControl: UIPageControl!
 
-    @objc var delegate: NCIntroViewController?
+    @objc weak var delegate: NCIntroViewController?
     private let appDelegate = UIApplication.shared.delegate as! AppDelegate
     private let titles = [NSLocalizedString("_intro_1_title_", comment: ""), NSLocalizedString("_intro_2_title_", comment: ""), NSLocalizedString("_intro_3_title_", comment: ""), NSLocalizedString("_intro_4_title_", comment: "")]
     private let images = [UIImage(named: "intro1"), UIImage(named: "intro2"), UIImage(named: "intro3"), UIImage(named: "intro4")]
     private var timerAutoScroll: Timer?
     private var textColor: UIColor = .white
     private var textColorOpponent: UIColor = .black
-    
+
     // MARK: - View Life Cycle
 
     override func viewDidLoad() {
         super.viewDidLoad()
-        
+
         let isTooLight = NCBrandColor.shared.customer.isTooLight()
         let isTooDark = NCBrandColor.shared.customer.isTooDark()
-        
+
         if isTooLight {
             textColor = .black
             textColorOpponent = .white
@@ -59,7 +59,7 @@ class NCIntroViewController: UIViewController, UICollectionViewDataSource, UICol
             textColor = .white
             textColorOpponent = .black
         }
-        
+
         if #available(iOS 13.0, *) {
             let navBarAppearance = UINavigationBarAppearance()
             navBarAppearance.configureWithTransparentBackground()
@@ -76,7 +76,6 @@ class NCIntroViewController: UIViewController, UICollectionViewDataSource, UICol
         }
         self.navigationController?.navigationBar.tintColor = textColor
 
-        
         pageControl.currentPageIndicatorTintColor = textColor
         pageControl.pageIndicatorTintColor = .lightGray
 
@@ -101,11 +100,11 @@ class NCIntroViewController: UIViewController, UICollectionViewDataSource, UICol
         introCollectionView.delegate = self
         introCollectionView.backgroundColor = NCBrandColor.shared.customer
         pageControl.numberOfPages = self.titles.count
-        
+
         view.backgroundColor = NCBrandColor.shared.customer
         timerAutoScroll = Timer.scheduledTimer(timeInterval: 5, target: self, selector: (#selector(NCIntroViewController.autoScroll)), userInfo: nil, repeats: true)
     }
-    
+
     override var preferredStatusBarStyle: UIStatusBarStyle {
         if #available(iOS 13.0, *) {
             if traitCollection.userInterfaceStyle == .light {
@@ -129,10 +128,9 @@ class NCIntroViewController: UIViewController, UICollectionViewDataSource, UICol
     }
 
     @objc func autoScroll() {
-        if(pageControl.currentPage + 1 >= titles.count) {
+        if pageControl.currentPage + 1 >= titles.count {
             pageControl.currentPage = 0
-        }
-        else {
+        } else {
             pageControl.currentPage += 1
         }
         introCollectionView.scrollToItem(at: IndexPath(row: pageControl.currentPage, section: 0), at: .centeredHorizontally, animated: true)

+ 89 - 89
iOSClient/Brand/NCBrand.swift

@@ -23,53 +23,53 @@
 
 import UIKit
 
-//MARK: - Configuration
+// MARK: - Configuration
 
 @objc class NCBrandConfiguration: NSObject {
     @objc static let shared: NCBrandConfiguration = {
         let instance = NCBrandConfiguration()
         return instance
     }()
-    
-    @objc public let configuration_bundleId:            String = "it.twsweb.Nextcloud"
-    @objc public let configuration_serverUrl:           String = "serverUrl"
-    @objc public let configuration_username:            String = "username"
-    @objc public let configuration_password:            String = "password"
+
+    @objc public let configuration_bundleId: String = "it.twsweb.Nextcloud"
+    @objc public let configuration_serverUrl: String = "serverUrl"
+    @objc public let configuration_username: String = "username"
+    @objc public let configuration_password: String = "password"
 }
 
-//MARK: - Options
+// MARK: - Options
 
 @objc class NCBrandOptions: NSObject {
     @objc static let shared: NCBrandOptions = {
         let instance = NCBrandOptions()
         return instance
     }()
-    
-    @objc public var brand:                             String = "Nextcloud"
-    //@objc public var mailMe:                            String = "ios@nextcloud.com"                              // Deprecated
-    @objc public var textCopyrightNextcloudiOS:         String = "Nextcloud Liquid for iOS %@ © 2021"
-    @objc public var textCopyrightNextcloudServer:      String = "Nextcloud Server %@"
-    @objc public var loginBaseUrl:                      String = "https://cloud.nextcloud.com"
-    @objc public var pushNotificationServerProxy:       String = "https://push-notifications.nextcloud.com"
-    @objc public var linkLoginHost:                     String = "https://nextcloud.com/install"
-    @objc public var linkloginPreferredProviders:       String = "https://nextcloud.com/signup-ios";
-    @objc public var webLoginAutenticationProtocol:     String = "nc://"                                            // example "abc://"
-    @objc public var privacy:                           String = "https://nextcloud.com/privacy"
-    @objc public var sourceCode:                        String = "https://github.com/nextcloud/ios"
+
+    @objc public var brand: String = "Nextcloud"
+    // @objc public var mailMe:                            String = "ios@nextcloud.com"                              // Deprecated
+    @objc public var textCopyrightNextcloudiOS: String = "Nextcloud Liquid for iOS %@ © 2021"
+    @objc public var textCopyrightNextcloudServer: String = "Nextcloud Server %@"
+    @objc public var loginBaseUrl: String = "https://cloud.nextcloud.com"
+    @objc public var pushNotificationServerProxy: String = "https://push-notifications.nextcloud.com"
+    @objc public var linkLoginHost: String = "https://nextcloud.com/install"
+    @objc public var linkloginPreferredProviders: String = "https://nextcloud.com/signup-ios"
+    @objc public var webLoginAutenticationProtocol: String = "nc://"                                            // example "abc://"
+    @objc public var privacy: String = "https://nextcloud.com/privacy"
+    @objc public var sourceCode: String = "https://github.com/nextcloud/ios"
 
     // Personalized
-    @objc public var webCloseViewProtocolPersonalized:  String = ""                                                 // example "abc://change/plan"      Don't touch me !!
-    @objc public var folderBrandAutoUpload:             String = ""                                                 // example "_auto_upload_folder_"   Don't touch me !!
-    
+    @objc public var webCloseViewProtocolPersonalized: String = ""                                                 // example "abc://change/plan"      Don't touch me !!
+    @objc public var folderBrandAutoUpload: String = ""                                                 // example "_auto_upload_folder_"   Don't touch me !!
+
     // Auto Upload default folder
-    @objc public var folderDefaultAutoUpload:           String = "Photos"
-    
+    @objc public var folderDefaultAutoUpload: String = "Photos"
+
     // Capabilities Group
-    @objc public var capabilitiesGroups:                String = "group.it.twsweb.Crypto-Cloud"
-    
+    @objc public var capabilitiesGroups: String = "group.it.twsweb.Crypto-Cloud"
+
     // User Agent
-    @objc public var userAgent:                         String = "Nextcloud-iOS"                                    // Don't touch me !!
-    
+    @objc public var userAgent: String = "Nextcloud-iOS"                                    // Don't touch me !!
+
     // Options
     @objc public var use_login_web_personalized:        Bool = false                                                // Don't touch me !!
     @objc public var use_default_auto_upload:           Bool = false
@@ -95,14 +95,14 @@ import UIKit
     @objc public var disable_ff:                        Bool = true
 
     override init() {
-        
+
         if folderBrandAutoUpload != "" {
             folderDefaultAutoUpload = folderBrandAutoUpload
         }
     }
 }
 
-//MARK: - Color
+// MARK: - Color
 
 class NCBrandColor: NSObject {
     @objc static let shared: NCBrandColor = {
@@ -111,14 +111,14 @@ class NCBrandColor: NSObject {
         instance.createUserColors()
         return instance
     }()
-    
+
     struct cacheImages {
         static var file = UIImage()
 
         static var shared = UIImage()
         static var canShare = UIImage()
         static var shareByLink = UIImage()
-        
+
         static var favorite = UIImage()
         static var comment = UIImage()
         static var livePhoto = UIImage()
@@ -132,28 +132,28 @@ class NCBrandColor: NSObject {
         static var folderExternal = UIImage()
         static var folderAutomaticUpload = UIImage()
         static var folder = UIImage()
-        
+
         static var checkedYes = UIImage()
         static var checkedNo = UIImage()
-        
+
         static var buttonMore = UIImage()
         static var buttonStop = UIImage()
         static var buttonRestore = UIImage()
     }
 
     // Color
-    @objc public let customer:              UIColor = UIColor(red: 0.0/255.0, green: 130.0/255.0, blue: 201.0/255.0, alpha: 1.0)    // BLU NC : #0082c9
-    @objc public var customerText:          UIColor = .white
-    
-    @objc public var brand:                 UIColor                                                                                 // don't touch me
-    @objc public var brandElement:          UIColor                                                                                 // don't touch me
-    @objc public var brandText:             UIColor                                                                                 // don't touch me
-    
-    @objc public let nextcloud:             UIColor = UIColor(red: 0.0/255.0, green: 130.0/255.0, blue: 201.0/255.0, alpha: 1.0)
-    @objc public let gray:                  UIColor = UIColor(red: 104.0/255.0, green: 104.0/255.0, blue: 104.0/255.0, alpha: 1.0)
-    @objc public let lightGray:             UIColor = UIColor(red: 229.0/255.0, green: 229.0/229.0, blue: 104.0/255.0, alpha: 1.0)
-    @objc public let yellowFavorite:        UIColor = UIColor(red: 248.0/255.0, green: 205.0/255.0, blue: 70.0/255.0, alpha: 1.0)
-    
+    @objc public let customer: UIColor = UIColor(red: 0.0/255.0, green: 130.0/255.0, blue: 201.0/255.0, alpha: 1.0)    // BLU NC : #0082c9
+    @objc public var customerText: UIColor = .white
+
+    @objc public var brand: UIColor                                                                                 // don't touch me
+    @objc public var brandElement: UIColor                                                                                 // don't touch me
+    @objc public var brandText: UIColor                                                                                 // don't touch me
+
+    @objc public let nextcloud: UIColor = UIColor(red: 0.0/255.0, green: 130.0/255.0, blue: 201.0/255.0, alpha: 1.0)
+    @objc public let gray: UIColor = UIColor(red: 104.0/255.0, green: 104.0/255.0, blue: 104.0/255.0, alpha: 1.0)
+    @objc public let lightGray: UIColor = UIColor(red: 229.0/255.0, green: 229.0/229.0, blue: 104.0/255.0, alpha: 1.0)
+    @objc public let yellowFavorite: UIColor = UIColor(red: 248.0/255.0, green: 205.0/255.0, blue: 70.0/255.0, alpha: 1.0)
+
     public var userColors: [CGColor] = []
 
     @objc public var systemBackground: UIColor {
@@ -165,7 +165,7 @@ class NCBrandColor: NSObject {
             }
         }
     }
-    
+
     @objc public var secondarySystemBackground: UIColor {
         get {
             if #available(iOS 13, *) {
@@ -175,7 +175,7 @@ class NCBrandColor: NSObject {
             }
         }
     }
-    
+
     @objc public var tertiarySystemBackground: UIColor {
         get {
             if #available(iOS 13, *) {
@@ -185,7 +185,7 @@ class NCBrandColor: NSObject {
             }
         }
     }
-    
+
     @objc public var systemGroupedBackground: UIColor {
         get {
             if #available(iOS 13, *) {
@@ -195,7 +195,7 @@ class NCBrandColor: NSObject {
             }
         }
     }
-    
+
     @objc public var secondarySystemGroupedBackground: UIColor {
         get {
             if #available(iOS 13, *) {
@@ -205,7 +205,7 @@ class NCBrandColor: NSObject {
             }
         }
     }
-    
+
     @objc public var label: UIColor {
         get {
             if #available(iOS 13, *) {
@@ -215,7 +215,7 @@ class NCBrandColor: NSObject {
             }
         }
     }
-    
+
     @objc public var separator: UIColor {
         get {
             if #available(iOS 13, *) {
@@ -225,7 +225,7 @@ class NCBrandColor: NSObject {
             }
         }
     }
-    
+
     @objc public var opaqueSeparator: UIColor {
         get {
             if #available(iOS 13, *) {
@@ -235,7 +235,7 @@ class NCBrandColor: NSObject {
             }
         }
     }
-    
+
     @objc public var systemGray: UIColor {
         get {
             if #available(iOS 13, *) {
@@ -245,7 +245,7 @@ class NCBrandColor: NSObject {
             }
         }
     }
-    
+
     @objc public var systemGray2: UIColor {
         get {
             if #available(iOS 13, *) {
@@ -255,7 +255,7 @@ class NCBrandColor: NSObject {
             }
         }
     }
-    
+
     @objc public var systemGray3: UIColor {
         get {
             if #available(iOS 13, *) {
@@ -265,7 +265,7 @@ class NCBrandColor: NSObject {
             }
         }
     }
-    
+
     @objc public var systemGray4: UIColor {
         get {
             if #available(iOS 13, *) {
@@ -275,7 +275,7 @@ class NCBrandColor: NSObject {
             }
         }
     }
-    
+
     @objc public var systemGray5: UIColor {
         get {
             if #available(iOS 13, *) {
@@ -285,7 +285,7 @@ class NCBrandColor: NSObject {
             }
         }
     }
-    
+
     @objc public var systemGray6: UIColor {
         get {
             if #available(iOS 13, *) {
@@ -295,7 +295,7 @@ class NCBrandColor: NSObject {
             }
         }
     }
-    
+
     @objc public var systemFill: UIColor {
         get {
             if #available(iOS 13, *) {
@@ -305,11 +305,11 @@ class NCBrandColor: NSObject {
             }
         }
     }
-    
+
     override init() {
         self.brand = self.customer
         self.brandElement = self.customer
-        self.brandText = self.customerText        
+        self.brandText = self.customerText
     }
 
     private func createUserColors() {
@@ -317,21 +317,21 @@ class NCBrandColor: NSObject {
     }
 
     public func createImagesThemingColor() {
-        
+
         let gray: UIColor = UIColor(red: 162.0/255.0, green: 162.0/255.0, blue: 162.0/255.0, alpha: 0.5)
 
-        cacheImages.file = UIImage.init(named: "file")!
-        
+        cacheImages.file = UIImage(named: "file")!
+
         cacheImages.shared = UIImage(named: "share")!.image(color: gray, size: 50)
         cacheImages.canShare = UIImage(named: "share")!.image(color: gray, size: 50)
         cacheImages.shareByLink = UIImage(named: "sharebylink")!.image(color: gray, size: 50)
-        
+
         cacheImages.favorite = NCUtility.shared.loadImage(named: "star.fill", color: yellowFavorite)
         cacheImages.comment = UIImage(named: "comment")!.image(color: gray, size: 50)
         cacheImages.livePhoto = NCUtility.shared.loadImage(named: "livephoto", color: label)
-        cacheImages.offlineFlag = UIImage.init(named: "offlineFlag")!
-        cacheImages.local = UIImage.init(named: "local")!
-            
+        cacheImages.offlineFlag = UIImage(named: "offlineFlag")!
+        cacheImages.local = UIImage(named: "local")!
+
         let folderWidth: CGFloat = UIScreen.main.bounds.width / 3
         cacheImages.folderEncrypted = UIImage(named: "folderEncrypted")!.image(color: brandElement, size: folderWidth)
         cacheImages.folderSharedWithMe = UIImage(named: "folder_shared_with_me")!.image(color: brandElement, size: folderWidth)
@@ -340,31 +340,31 @@ class NCBrandColor: NSObject {
         cacheImages.folderExternal = UIImage(named: "folder_external")!.image(color: brandElement, size: folderWidth)
         cacheImages.folderAutomaticUpload = UIImage(named: "folderAutomaticUpload")!.image(color: brandElement, size: folderWidth)
         cacheImages.folder =  UIImage(named: "folder")!.image(color: brandElement, size: folderWidth)
-        
+
         cacheImages.checkedYes = NCUtility.shared.loadImage(named: "checkmark.circle.fill", color: .systemBlue)
         cacheImages.checkedNo = NCUtility.shared.loadImage(named: "circle", color: gray)
-        
+
         cacheImages.buttonMore = UIImage(named: "more")!.image(color: gray, size: 50)
         cacheImages.buttonStop = UIImage(named: "stop")!.image(color: gray, size: 50)
         cacheImages.buttonRestore = UIImage(named: "restore")!.image(color: gray, size: 50)
     }
-    
+
     #if !EXTENSION
     public func settingThemingColor(account: String) {
-        
+
         let darker: CGFloat = 30    // %
         let lighter: CGFloat = 30   // %
 
         if NCBrandOptions.shared.use_themingColor {
-            
+
             let themingColor = NCManageDatabase.shared.getCapabilitiesServerString(account: account, elements: NCElementsJSON.shared.capabilitiesThemingColor)
-            
+
             let themingColorElement = NCManageDatabase.shared.getCapabilitiesServerString(account: account, elements: NCElementsJSON.shared.capabilitiesThemingColorElement)
-            
+
             let themingColorText = NCManageDatabase.shared.getCapabilitiesServerString(account: account, elements: NCElementsJSON.shared.capabilitiesThemingColorText)
-            
+
             settingBrandColor(themingColor, themingColorElement: themingColorElement, themingColorText: themingColorText)
-                        
+
             if NCBrandColor.shared.brandElement.isTooLight() {
                 if let color = NCBrandColor.shared.brandElement.darker(by: darker) {
                     NCBrandColor.shared.brandElement = color
@@ -373,10 +373,10 @@ class NCBrandColor: NSObject {
                 if let color = NCBrandColor.shared.brandElement.lighter(by: lighter) {
                     NCBrandColor.shared.brandElement = color
                 }
-            }           
-            
+            }
+
         } else {
-            
+
             if NCBrandColor.shared.customer.isTooLight() {
                 if let color = NCBrandColor.shared.customer.darker(by: darker) {
                     NCBrandColor.shared.brandElement = color
@@ -388,20 +388,20 @@ class NCBrandColor: NSObject {
             } else {
                 NCBrandColor.shared.brandElement = NCBrandColor.shared.customer
             }
-            
+
             NCBrandColor.shared.brand = NCBrandColor.shared.customer
             NCBrandColor.shared.brandText = NCBrandColor.shared.customerText
         }
-                
+
         DispatchQueue.main.async {
             self.createImagesThemingColor()
             NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeTheming)
         }
     }
     #endif
-    
+
     @objc func settingBrandColor(_ themingColor: String?, themingColorElement: String?, themingColorText: String?) {
-                
+
         // COLOR
         if themingColor?.first == "#" {
             if let color = UIColor(hex: themingColor!) {
@@ -412,7 +412,7 @@ class NCBrandColor: NSObject {
         } else {
             NCBrandColor.shared.brand = NCBrandColor.shared.customer
         }
-        
+
         // COLOR TEXT
         if themingColorText?.first == "#" {
             if let color = UIColor(hex: themingColorText!) {
@@ -423,7 +423,7 @@ class NCBrandColor: NSObject {
         } else {
             NCBrandColor.shared.brandText = NCBrandColor.shared.customerText
         }
-        
+
         // COLOR ELEMENT
         if themingColorElement?.first == "#" {
             if let color = UIColor(hex: themingColorElement!) {
@@ -447,13 +447,13 @@ class NCBrandColor: NSObject {
     private func mixPalette(steps: Int, color1: CGColor, color2: CGColor) -> [CGColor] {
         var palette = [color1]
         let step = stepCalc(steps: steps, color1: color1, color2: color2)
-        
+
         let c1Components = color1.components!
         for i in 1 ..< steps {
             let r = c1Components[0] + step[0] * CGFloat(i)
             let g = c1Components[1] + step[1] * CGFloat(i)
             let b = c1Components[2] + step[2] * CGFloat(i)
-            
+
             palette.append(UIColor(red: r, green: g, blue: b, alpha: 1).cgColor)
         }
         return palette

+ 29 - 30
iOSClient/BrowserWeb/NCBrowserWeb.swift

@@ -29,22 +29,21 @@ import WebKit
 }
 
 class NCBrowserWeb: UIViewController {
-    
+
     var webView: WKWebView?
-    let appDelegate = UIApplication.shared.delegate as! AppDelegate
-    
+
     @objc var urlBase = ""
     @objc var isHiddenButtonExit = false
-    @objc var titleBrowser: String? = nil
+    @objc var titleBrowser: String?
     @objc weak var delegate: NCBrowserWebDelegate?
-    
+
     @IBOutlet weak var buttonExit: UIButton!
-    
+
     // MARK: - View Life Cycle
 
     override func viewDidLoad() {
         super.viewDidLoad()
-        
+
         webView = WKWebView(frame: CGRect.zero)
         webView!.navigationDelegate = self
         view.addSubview(webView!)
@@ -53,7 +52,7 @@ class NCBrowserWeb: UIViewController {
         webView!.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
         webView!.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
         webView!.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
-        
+
         // button exit
         if isHiddenButtonExit {
             buttonExit.isHidden = true
@@ -62,29 +61,29 @@ class NCBrowserWeb: UIViewController {
             let image = NCUtility.shared.loadImage(named: "xmark", color: .systemBlue)
             buttonExit.setImage(image, for: .normal)
         }
-        
+
         if let url = URL(string: urlBase) {
             loadWebPage(webView: webView!, url: url)
         } else {
             let url = URL(fileURLWithPath: urlBase)
             loadWebPage(webView: webView!, url: url)
         }
-        
-        //navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "more")!.image(color: NCBrandColor.shared.label, size: 25), style: .plain, target: self, action: #selector(self.openMenuMore))
+
+        // navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "more")!.image(color: NCBrandColor.shared.label, size: 25), style: .plain, target: self, action: #selector(self.openMenuMore))
     }
-    
+
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
-        
+
         if let titleBrowser = titleBrowser {
             navigationItem.title = titleBrowser
         }
     }
-    
+
     deinit {
-        
+
     }
-    
+
     // MARK: - Action
 
     @IBAction func touchUpInsideButtonExit(_ sender: UIButton) {
@@ -92,14 +91,14 @@ class NCBrowserWeb: UIViewController {
             self.delegate?.browserWebDismiss?()
         }
     }
-    
+
     //
-    
-    func loadWebPage(webView: WKWebView, url: URL)  {
-        
+
+    func loadWebPage(webView: WKWebView, url: URL) {
+
         let language = NSLocale.preferredLanguages[0] as String
         var request = URLRequest(url: url)
-        
+
         request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
         request.addValue(language, forHTTPHeaderField: "Accept-Language")
         webView.customUserAgent = CCUtility.getUserAgent()
@@ -109,28 +108,28 @@ class NCBrowserWeb: UIViewController {
 }
 
 extension NCBrowserWeb: WKNavigationDelegate {
-    
+
     public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
         if let serverTrust = challenge.protectionSpace.serverTrust {
             completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
         } else {
-            completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil);
+            completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
         }
     }
-    
+
     public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
         decisionHandler(.allow)
     }
-    
+
     public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
-        print("didStartProvisionalNavigation");
+        print("didStartProvisionalNavigation")
     }
-    
+
     public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
-        print("didFinishProvisionalNavigation");
+        print("didFinishProvisionalNavigation")
     }
-    
+
     public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
-        print("didReceiveServerRedirectForProvisionalNavigation");
+        print("didReceiveServerRedirectForProvisionalNavigation")
     }
 }

+ 46 - 46
iOSClient/Data/NCDataSource.swift

@@ -24,9 +24,9 @@
 import UIKit
 
 class NCDataSource: NSObject {
-    
+
     public var metadatas: [tableMetadata] = []
-    public var metadataShare: [String:tableShare] = [:]
+    public var metadataShare: [String: tableShare] = [:]
     public var metadataOffLine: [String] = []
 
     private var ascending: Bool = true
@@ -34,39 +34,39 @@ class NCDataSource: NSObject {
     private var directoryOnTop: Bool = true
     private var favoriteOnTop: Bool = true
     private var filterLivePhoto: Bool = true
-    
+
     override init() {
         super.init()
     }
-    
+
     init(metadatasSource: [tableMetadata], sort: String? = "none", ascending: Bool? = false, directoryOnTop: Bool? = true, favoriteOnTop: Bool? = true, filterLivePhoto: Bool? = true) {
         super.init()
-        
+
         self.sort = sort ?? "none"
         self.ascending = ascending ?? false
         self.directoryOnTop = directoryOnTop ?? true
         self.favoriteOnTop = favoriteOnTop ?? true
         self.filterLivePhoto = filterLivePhoto ?? true
-        
+
         createMetadatas(metadatasSource: metadatasSource)
     }
-    
+
     // MARK: -
-    
+
     private func createMetadatas(metadatasSource: [tableMetadata]) {
-                
+
         var metadatasSourceSorted: [tableMetadata] = []
         var metadataFavoriteDirectory: [tableMetadata] = []
         var metadataFavoriteFile: [tableMetadata] = []
         var metadataDirectory: [tableMetadata] = []
         var metadataFile: [tableMetadata] = []
-        
+
         /*
         Metadata order
         */
-        
+
         if sort != "none" && sort != "" {
-            metadatasSourceSorted = metadatasSource.sorted { (obj1:tableMetadata, obj2:tableMetadata) -> Bool in
+            metadatasSourceSorted = metadatasSource.sorted { (obj1: tableMetadata, obj2: tableMetadata) -> Bool in
                 if sort == "date" {
                     if ascending {
                         return obj1.date.compare(obj2.date as Date) == ComparisonResult.orderedAscending
@@ -90,29 +90,29 @@ class NCDataSource: NSObject {
         } else {
             metadatasSourceSorted = metadatasSource
         }
-        
+
         /*
         Initialize datasource
         */
-        
+
         for metadata in metadatasSourceSorted {
-            
+
             // skipped the root file
             if metadata.fileName == "." || metadata.serverUrl == ".." {
                 continue
             }
-            
+
             // skipped livePhoto
             if metadata.ext == "mov" && metadata.livePhoto && filterLivePhoto {
                 continue
             }
-            
+
             // share
             let shares = NCManageDatabase.shared.getTableShares(account: metadata.account, serverUrl: metadata.serverUrl, fileName: metadata.fileName)
             if shares.count > 0 {
                 metadataShare[metadata.ocId] = shares.first
             }
-            
+
             // is Local / offline
             if !metadata.directory {
                 let size = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
@@ -126,7 +126,7 @@ class NCDataSource: NSObject {
                     }
                 }
             }
-               
+
             // Organized the metadata
             if metadata.favorite && favoriteOnTop {
                 if metadata.directory {
@@ -140,17 +140,17 @@ class NCDataSource: NSObject {
                 metadataFile.append(metadata)
             }
         }
-        
+
         metadatas.removeAll()
         metadatas += metadataFavoriteDirectory
         metadatas += metadataFavoriteFile
         metadatas += metadataDirectory
         metadatas += metadataFile
     }
-        
+
     // MARK: -
 
-    func getFilesInformation() -> (directories: Int,  files: Int, size: Int64) {
+    func getFilesInformation() -> (directories: Int, files: Int, size: Int64) {
 
         var directories: Int = 0
         var files: Int = 0
@@ -162,47 +162,47 @@ class NCDataSource: NSObject {
             } else {
                 files += 1
             }
-            size = size + metadata.size
+            size += metadata.size
         }
-        
+
         return (directories, files, size)
     }
-    
+
     func deleteMetadata(ocId: String) -> Int? {
-        
+
         if let index = self.getIndexMetadata(ocId: ocId) {
             metadatas.remove(at: index)
             return index
         }
-        
+
         return nil
     }
-    
+
     @discardableResult
     func reloadMetadata(ocId: String, ocIdTemp: String? = nil) -> Int? {
-        
+
         var index: Int?
-        
+
         if ocIdTemp != nil {
             index = self.getIndexMetadata(ocId: ocIdTemp!)
         } else {
             index = self.getIndexMetadata(ocId: ocId)
         }
-        
+
         if index != nil {
             if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
                 metadatas[index!] = metadata
-            } 
+            }
         }
-        
+
         return index
     }
-    
+
     @discardableResult
     func addMetadata(_ metadata: tableMetadata) -> Int? {
-        
+
         var index: Int = 0
-        
+
         // Already exists
         for metadataCount in metadatas {
             if metadataCount.fileNameView == metadata.fileNameView || metadataCount.ocId == metadata.ocId {
@@ -211,16 +211,16 @@ class NCDataSource: NSObject {
             }
             index += 1
         }
-        
+
         // Append & rebuild
         metadatas.append(metadata)
         createMetadatas(metadatasSource: metadatas)
-        
+
         return getIndexMetadata(ocId: metadata.ocId)
     }
-    
+
     func getIndexMetadata(ocId: String) -> Int? {
-        
+
         var index: Int = 0
 
         for metadataCount in metadatas {
@@ -229,19 +229,19 @@ class NCDataSource: NSObject {
             }
             index += 1
         }
-        
+
         return nil
     }
-    
+
     func numberOfItems() -> Int {
-        
+
         return metadatas.count
     }
-    
+
     func cellForItemAt(indexPath: IndexPath) -> tableMetadata? {
-        
+
         let row = indexPath.row
-        
+
         if row > metadatas.count - 1 {
             return nil
         } else {

+ 44 - 46
iOSClient/Data/NCDatabase.swift

@@ -76,7 +76,7 @@ class tableAccount: Object, NCUserBaseUrl {
     @objc dynamic var urlBase = ""
     @objc dynamic var user = ""
     @objc dynamic var userId = ""
-    @objc dynamic var userStatusClearAt: NSDate? = nil
+    @objc dynamic var userStatusClearAt: NSDate?
     @objc dynamic var userStatusIcon: String?
     @objc dynamic var userStatusMessage: String?
     @objc dynamic var userStatusMessageId: String?
@@ -85,7 +85,7 @@ class tableAccount: Object, NCUserBaseUrl {
     @objc dynamic var userStatusStatusIsUserDefined: Bool = false
     @objc dynamic var webpage = ""
     @objc dynamic var zip = ""
-    
+
     // COLOR Files
     @objc dynamic var darkColorBackground = ""
     @objc dynamic var lightColorBackground = ""
@@ -94,15 +94,15 @@ class tableAccount: Object, NCUserBaseUrl {
     @objc dynamic var hcIsTrial: Bool = false
     @objc dynamic var hcTrialExpired: Bool = false
     @objc dynamic var hcTrialRemainingSec: Int64 = 0
-    @objc dynamic var hcTrialEndTime: NSDate? = nil
+    @objc dynamic var hcTrialEndTime: NSDate?
     @objc dynamic var hcAccountRemoveExpired: Bool = false
     @objc dynamic var hcAccountRemoveRemainingSec: Int64 = 0
-    @objc dynamic var hcAccountRemoveTime: NSDate? = nil
+    @objc dynamic var hcAccountRemoveTime: NSDate?
     @objc dynamic var hcNextGroupExpirationGroup = ""
     @objc dynamic var hcNextGroupExpirationGroupExpired: Bool = false
-    @objc dynamic var hcNextGroupExpirationExpiresTime: NSDate? = nil
+    @objc dynamic var hcNextGroupExpirationExpiresTime: NSDate?
     @objc dynamic var hcNextGroupExpirationExpires = ""
-    
+
     override static func primaryKey() -> String {
         return "account"
     }
@@ -146,7 +146,7 @@ class tableActivityLatestId: Object {
 }
 
 class tableActivityPreview: Object {
-    
+
     @objc dynamic var account = ""
     @objc dynamic var filename = ""
     @objc dynamic var idPrimaryKey = ""
@@ -164,7 +164,7 @@ class tableActivityPreview: Object {
 }
 
 class tableActivitySubjectRich: Object {
-    
+
     @objc dynamic var account = ""
     @objc dynamic var idActivity: Int = 0
     @objc dynamic var idPrimaryKey = ""
@@ -174,14 +174,14 @@ class tableActivitySubjectRich: Object {
     @objc dynamic var name = ""
     @objc dynamic var path = ""
     @objc dynamic var type = ""
-    
+
     override static func primaryKey() -> String {
         return "idPrimaryKey"
     }
 }
 
 class tableAvatar: Object {
-    
+
     @objc dynamic var date = NSDate()
     @objc dynamic var etag = ""
     @objc dynamic var fileName = ""
@@ -193,17 +193,17 @@ class tableAvatar: Object {
 }
 
 class tableCapabilities: Object {
-    
+
     @objc dynamic var account = ""
-    @objc dynamic var jsondata: Data? = nil
-    
+    @objc dynamic var jsondata: Data?
+
     override static func primaryKey() -> String {
         return "account"
     }
 }
 
 class tableChunk: Object {
-    
+
     @objc dynamic var account = ""
     @objc dynamic var chunkFolder = ""
     @objc dynamic var fileName = ""
@@ -218,8 +218,7 @@ class tableChunk: Object {
 
 class tableComments: Object, DateCompareable {
     var dateKey: Date { creationDateTime as Date }
-    
-    
+
     @objc dynamic var account = ""
     @objc dynamic var actorDisplayName = ""
     @objc dynamic var actorId = ""
@@ -232,14 +231,14 @@ class tableComments: Object, DateCompareable {
     @objc dynamic var objectType = ""
     @objc dynamic var path = ""
     @objc dynamic var verb = ""
-    
+
     override static func primaryKey() -> String {
         return "messageId"
     }
 }
 
 class tableDirectEditingCreators: Object {
-    
+
     @objc dynamic var account = ""
     @objc dynamic var editor = ""
     @objc dynamic var ext = ""
@@ -250,7 +249,7 @@ class tableDirectEditingCreators: Object {
 }
 
 class tableDirectEditingEditors: Object {
-    
+
     @objc dynamic var account = ""
     @objc dynamic var editor = ""
     let mimetypes = List<String>()
@@ -260,7 +259,7 @@ class tableDirectEditingEditors: Object {
 }
 
 class tableDirectory: Object {
-    
+
     @objc dynamic var account = ""
     @objc dynamic var e2eEncrypted: Bool = false
     @objc dynamic var etag = ""
@@ -278,9 +277,9 @@ class tableDirectory: Object {
 }
 
 class tableE2eEncryption: Object {
-    
+
     @objc dynamic var account = ""
-    @objc dynamic var authenticationTag: String? = nil
+    @objc dynamic var authenticationTag: String?
     @objc dynamic var fileName = ""
     @objc dynamic var fileNameIdentifier = ""
     @objc dynamic var fileNamePath = ""
@@ -291,7 +290,7 @@ class tableE2eEncryption: Object {
     @objc dynamic var mimeType = ""
     @objc dynamic var serverUrl = ""
     @objc dynamic var version: Int = 1
-    
+
     override static func primaryKey() -> String {
         return "fileNamePath"
     }
@@ -304,14 +303,14 @@ class tableE2eEncryptionLock: Object {
     @objc dynamic var fileId = ""
     @objc dynamic var serverUrl = ""
     @objc dynamic var e2eToken = ""
-    
+
     override static func primaryKey() -> String {
         return "fileId"
     }
 }
 
 class tableExternalSites: Object {
-    
+
     @objc dynamic var account = ""
     @objc dynamic var icon = ""
     @objc dynamic var idExternalSite: Int = 0
@@ -322,7 +321,7 @@ class tableExternalSites: Object {
 }
 
 class tableGPS: Object {
-    
+
     @objc dynamic var latitude = ""
     @objc dynamic var location = ""
     @objc dynamic var longitude = ""
@@ -334,25 +333,25 @@ class tableGPS: Object {
 }
 
 class tableLocalFile: Object {
-    
+
     @objc dynamic var account = ""
     @objc dynamic var etag = ""
-    @objc dynamic var exifDate: NSDate? = nil
+    @objc dynamic var exifDate: NSDate?
     @objc dynamic var exifLatitude = ""
     @objc dynamic var exifLongitude = ""
-    @objc dynamic var exifLensModel: String? = nil
+    @objc dynamic var exifLensModel: String?
     @objc dynamic var favorite: Bool = false
     @objc dynamic var fileName = ""
     @objc dynamic var ocId = ""
     @objc dynamic var offline: Bool = false
-    
+
     override static func primaryKey() -> String {
         return "ocId"
     }
 }
 
 class tableMetadata: Object, NCUserBaseUrl {
-    
+
     @objc dynamic var account = ""
     @objc dynamic var assetLocalIdentifier = ""
     @objc dynamic var checksums = ""
@@ -415,12 +414,12 @@ class tableMetadata: Object, NCUserBaseUrl {
 }
 
 class tablePhotoLibrary: Object {
-    
+
     @objc dynamic var account = ""
     @objc dynamic var assetLocalIdentifier = ""
-    @objc dynamic var creationDate: NSDate? = nil
+    @objc dynamic var creationDate: NSDate?
     @objc dynamic var idAsset = ""
-    @objc dynamic var modificationDate: NSDate? = nil
+    @objc dynamic var modificationDate: NSDate?
     @objc dynamic var mediaType: Int = 0
 
     override static func primaryKey() -> String {
@@ -429,14 +428,14 @@ class tablePhotoLibrary: Object {
 }
 
 class tableShare: Object {
-    
+
     @objc dynamic var account = ""
     @objc dynamic var canEdit: Bool = false
     @objc dynamic var canDelete: Bool = false
-    @objc dynamic var date: NSDate? = nil
+    @objc dynamic var date: NSDate?
     @objc dynamic var displaynameFileOwner = ""
     @objc dynamic var displaynameOwner = ""
-    @objc dynamic var expirationDate: NSDate? = nil
+    @objc dynamic var expirationDate: NSDate?
     @objc dynamic var fileName = ""
     @objc dynamic var fileParent: Int = 0
     @objc dynamic var fileSource: Int = 0
@@ -464,7 +463,7 @@ class tableShare: Object {
     @objc dynamic var uidFileOwner = ""
     @objc dynamic var uidOwner = ""
     @objc dynamic var url = ""
-    @objc dynamic var userClearAt: NSDate? = nil
+    @objc dynamic var userClearAt: NSDate?
     @objc dynamic var userIcon = ""
     @objc dynamic var userMessage = ""
     @objc dynamic var userStatus = ""
@@ -475,18 +474,18 @@ class tableShare: Object {
 }
 
 class tableTag: Object {
-    
+
     @objc dynamic var account = ""
     @objc dynamic var ocId = ""
-    @objc dynamic var tagIOS: Data? = nil
-    
+    @objc dynamic var tagIOS: Data?
+
     override static func primaryKey() -> String {
         return "ocId"
     }
 }
 
 class tableTrash: Object {
-    
+
     @objc dynamic var account = ""
     @objc dynamic var classFile = ""
     @objc dynamic var contentType = ""
@@ -508,7 +507,7 @@ class tableTrash: Object {
 }
 
 class tableUserStatus: Object {
-    
+
     @objc dynamic var account = ""
     @objc dynamic var clearAt: NSDate?
     @objc dynamic var clearAtTime: String?
@@ -522,14 +521,13 @@ class tableUserStatus: Object {
 }
 
 class tableVideo: Object {
-    
+
     @objc dynamic var account = ""
     @objc dynamic var duration: Int64 = 0
     @objc dynamic var ocId = ""
     @objc dynamic var time: Int64 = 0
-    
+
     override static func primaryKey() -> String {
         return "ocId"
     }
 }
-

+ 30 - 30
iOSClient/Data/NCElementsJSON.swift

@@ -28,40 +28,40 @@ import UIKit
         let instance = NCElementsJSON()
         return instance
     }()
-    
-    @objc public let capabilitiesVersionString:                 Array = ["ocs","data","version","string"]
-    @objc public let capabilitiesVersionMajor:                  Array = ["ocs","data","version","major"]
-    
-    @objc public let capabilitiesFileSharingApiEnabled:         Array = ["ocs","data","capabilities","files_sharing","api_enabled"]
-    @objc public let capabilitiesFileSharingPubPasswdEnforced:  Array = ["ocs","data","capabilities","files_sharing","public","password","enforced"]
-    @objc public let capabilitiesFileSharingDefaultPermissions: Array = ["ocs","data","capabilities","files_sharing","default_permissions"]
+
+    @objc public let capabilitiesVersionString: Array = ["ocs", "data", "version", "string"]
+    @objc public let capabilitiesVersionMajor: Array = ["ocs", "data", "version", "major"]
+
+    @objc public let capabilitiesFileSharingApiEnabled: Array = ["ocs", "data", "capabilities", "files_sharing", "api_enabled"]
+    @objc public let capabilitiesFileSharingPubPasswdEnforced: Array = ["ocs", "data", "capabilities", "files_sharing", "public", "password", "enforced"]
+    @objc public let capabilitiesFileSharingDefaultPermissions: Array = ["ocs", "data", "capabilities", "files_sharing", "default_permissions"]
     // NC >= 23
-    @objc public let capabilitiesFileSharingSendPasswordMail:  Array = ["ocs","data","capabilities","files_sharing","sharebymail","send_password_by_mail"]
+    @objc public let capabilitiesFileSharingSendPasswordMail: Array = ["ocs", "data", "capabilities", "files_sharing", "sharebymail", "send_password_by_mail"]
+
+    @objc public let capabilitiesThemingColor: Array = ["ocs", "data", "capabilities", "theming", "color"]
+    @objc public let capabilitiesThemingColorElement: Array = ["ocs", "data", "capabilities", "theming", "color-element"]
+    @objc public let capabilitiesThemingColorText: Array = ["ocs", "data", "capabilities", "theming", "color-text"]
+    @objc public let capabilitiesThemingName: Array = ["ocs", "data", "capabilities", "theming", "name"]
+    @objc public let capabilitiesThemingSlogan: Array = ["ocs", "data", "capabilities", "theming", "slogan"]
+
+    @objc public let capabilitiesWebDavRoot: Array = ["ocs", "data", "capabilities", "core", "webdav-root"]
+
+    @objc public let capabilitiesE2EEEnabled: Array = ["ocs", "data", "capabilities", "end-to-end-encryption", "enabled"]
+    @objc public let capabilitiesE2EEApiVersion: Array = ["ocs", "data", "capabilities", "end-to-end-encryption", "api-version"]
+
+    @objc public let capabilitiesExternalSitesExists: Array = ["ocs", "data", "capabilities", "external"]
+
+    @objc public let capabilitiesRichdocumentsMimetypes: Array = ["ocs", "data", "capabilities", "richdocuments", "mimetypes"]
 
-    @objc public let capabilitiesThemingColor:                  Array = ["ocs","data","capabilities","theming","color"]
-    @objc public let capabilitiesThemingColorElement:           Array = ["ocs","data","capabilities","theming","color-element"]
-    @objc public let capabilitiesThemingColorText:              Array = ["ocs","data","capabilities","theming","color-text"]
-    @objc public let capabilitiesThemingName:                   Array = ["ocs","data","capabilities","theming","name"]
-    @objc public let capabilitiesThemingSlogan:                 Array = ["ocs","data","capabilities","theming","slogan"]
-       
-    @objc public let capabilitiesWebDavRoot:                    Array = ["ocs","data","capabilities","core","webdav-root"]
-    
-    @objc public let capabilitiesE2EEEnabled:                   Array = ["ocs","data","capabilities","end-to-end-encryption","enabled"]
-    @objc public let capabilitiesE2EEApiVersion:                Array = ["ocs","data","capabilities","end-to-end-encryption","api-version"]
-    
-    @objc public let capabilitiesExternalSitesExists:           Array = ["ocs","data","capabilities","external"]
+    @objc public let capabilitiesActivity: Array = ["ocs", "data", "capabilities", "activity", "apiv2"]
 
-    @objc public let capabilitiesRichdocumentsMimetypes:        Array = ["ocs","data","capabilities","richdocuments","mimetypes"]
+    @objc public let capabilitiesNotification: Array = ["ocs", "data", "capabilities", "notifications", "ocs-endpoints"]
 
-    @objc public let capabilitiesActivity:                      Array = ["ocs","data","capabilities","activity","apiv2"]
-    
-    @objc public let capabilitiesNotification:                  Array = ["ocs","data","capabilities","notifications","ocs-endpoints"]
+    @objc public let capabilitiesFilesUndelete: Array = ["ocs", "data", "capabilities", "files", "undelete"]
+    @objc public let capabilitiesFilesComments: Array = ["ocs", "data", "capabilities", "files", "comments"]                                            // NC 20
 
-    @objc public let capabilitiesFilesUndelete:                 Array = ["ocs","data","capabilities","files","undelete"]
-    @objc public let capabilitiesFilesComments:                 Array = ["ocs","data","capabilities","files","comments"]                                            // NC 20
+    @objc public let capabilitiesHWCEnabled: Array = ["ocs", "data", "capabilities", "handwerkcloud", "enabled"]
 
-    @objc public let capabilitiesHWCEnabled:                    Array = ["ocs","data","capabilities","handwerkcloud","enabled"]
-    
-    @objc public let capabilitiesUserStatusEnabled:             Array = ["ocs","data","capabilities","user_status","enabled"]
-    @objc public let capabilitiesUserStatusSupportsEmoji:       Array = ["ocs","data","capabilities","user_status","supports_emoji"]
+    @objc public let capabilitiesUserStatusEnabled: Array = ["ocs", "data", "capabilities", "user_status", "enabled"]
+    @objc public let capabilitiesUserStatusSupportsEmoji: Array = ["ocs", "data", "capabilities", "user_status", "supports_emoji"]
 }

+ 485 - 0
iOSClient/Data/NCManageDatabase+Account.swift

@@ -0,0 +1,485 @@
+//
+//  NCManageDatabase+Account.swift
+//  Nextcloud
+//
+//  Created by Henrik Storch on 30.11.21.
+//  Copyright © 2021 Marino Faggiana. All rights reserved.
+//
+
+import Foundation
+import RealmSwift
+import NCCommunication
+
+extension NCManageDatabase {
+
+    @objc func copyObject(account: tableAccount) -> tableAccount {
+        return tableAccount.init(value: account)
+    }
+
+    @objc func addAccount(_ account: String, urlBase: String, user: String, password: String) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                let addObject = tableAccount()
+
+                addObject.account = account
+
+                // Brand
+                if NCBrandOptions.shared.use_default_auto_upload {
+
+                    addObject.autoUpload = true
+                    addObject.autoUploadImage = true
+                    addObject.autoUploadVideo = true
+                    addObject.autoUploadWWAnVideo = true
+                }
+
+                CCUtility.setPassword(account, password: password)
+
+                addObject.urlBase = urlBase
+                addObject.user = user
+                addObject.userId = user
+
+                realm.add(addObject, update: .all)
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func updateAccount(_ account: tableAccount) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                realm.add(account, update: .all)
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func deleteAccount(_ account: String) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                let result = realm.objects(tableAccount.self).filter("account == %@", account)
+
+                realm.delete(result)
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func getActiveAccount() -> tableAccount? {
+
+        let realm = try! Realm()
+
+        guard let result = realm.objects(tableAccount.self).filter("active == true").first else {
+            return nil
+        }
+
+        return tableAccount.init(value: result)
+    }
+
+    @objc func getAccounts() -> [String]? {
+
+        let realm = try! Realm()
+
+        let results = realm.objects(tableAccount.self).sorted(byKeyPath: "account", ascending: true)
+
+        if results.count > 0 {
+            return Array(results.map { $0.account })
+        }
+
+        return nil
+    }
+
+    @objc func getAccount(predicate: NSPredicate) -> tableAccount? {
+
+        let realm = try! Realm()
+
+        guard let result = realm.objects(tableAccount.self).filter(predicate).first else {
+            return nil
+        }
+
+        return tableAccount.init(value: result)
+    }
+
+    @objc func getAllAccount() -> [tableAccount] {
+
+        let realm = try! Realm()
+
+        let sorted = [SortDescriptor(keyPath: "active", ascending: false), SortDescriptor(keyPath: "user", ascending: true)]
+        let results = realm.objects(tableAccount.self).sorted(by: sorted)
+
+        return Array(results.map { tableAccount.init(value: $0) })
+    }
+
+    @objc func getAllAccountOrderAlias() -> [tableAccount] {
+
+        let realm = try! Realm()
+
+        let sorted = [SortDescriptor(keyPath: "active", ascending: false), SortDescriptor(keyPath: "alias", ascending: true), SortDescriptor(keyPath: "user", ascending: true)]
+        let results = realm.objects(tableAccount.self).sorted(by: sorted)
+
+        return Array(results.map { tableAccount.init(value: $0) })
+    }
+
+    @objc func getAccountAutoUploadFileName() -> String {
+
+        let realm = try! Realm()
+
+        guard let result = realm.objects(tableAccount.self).filter("active == true").first else {
+            return ""
+        }
+
+        if result.autoUploadFileName.count > 0 {
+            return result.autoUploadFileName
+        } else {
+            return NCBrandOptions.shared.folderDefaultAutoUpload
+        }
+    }
+
+    @objc func getAccountAutoUploadDirectory(urlBase: String, account: String) -> String {
+
+        let realm = try! Realm()
+
+        guard let result = realm.objects(tableAccount.self).filter("active == true").first else {
+            return ""
+        }
+
+        if result.autoUploadDirectory.count > 0 {
+            // FIX change webdav -> /dav/files/
+            if result.autoUploadDirectory.contains("/webdav") {
+                return NCUtilityFileSystem.shared.getHomeServer(account: account)
+            } else {
+                return result.autoUploadDirectory
+            }
+        } else {
+            return NCUtilityFileSystem.shared.getHomeServer(account: account)
+        }
+    }
+
+    @objc func getAccountAutoUploadPath(urlBase: String, account: String) -> String {
+
+        let cameraFileName = self.getAccountAutoUploadFileName()
+        let cameraDirectory = self.getAccountAutoUploadDirectory(urlBase: urlBase, account: account)
+
+        let folderPhotos = CCUtility.stringAppendServerUrl(cameraDirectory, addFileName: cameraFileName)!
+
+        return folderPhotos
+    }
+
+    @discardableResult
+    @objc func setAccountActive(_ account: String) -> tableAccount? {
+
+        let realm = try! Realm()
+        var accountReturn = tableAccount()
+
+        do {
+            try realm.safeWrite {
+
+                let results = realm.objects(tableAccount.self)
+                for result in results {
+                    if result.account == account {
+                        result.active = true
+                        accountReturn = result
+                    } else {
+                        result.active = false
+                    }
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+            return nil
+        }
+
+        return tableAccount.init(value: accountReturn)
+    }
+
+    @objc func removePasswordAccount(_ account: String) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+
+                if let result = realm.objects(tableAccount.self).filter("account == %@", account).first {
+                    result.password = "********"
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func setAccountAutoUploadProperty(_ property: String, state: Bool) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                if let result = realm.objects(tableAccount.self).filter("active == true").first {
+                    if (tableAccount().objectSchema.properties.contains { $0.name == property }) {
+                        result[property] = state
+                    }
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func setAccountAutoUploadFileName(_ fileName: String?) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                if let result = realm.objects(tableAccount.self).filter("active == true").first {
+                    if let fileName = fileName {
+                        result.autoUploadFileName = fileName
+                    } else {
+                        result.autoUploadFileName = self.getAccountAutoUploadFileName()
+                    }
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func setAccountAutoUploadDirectory(_ serverUrl: String?, urlBase: String, account: String) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                if let result = realm.objects(tableAccount.self).filter("active == true").first {
+                    if let serverUrl = serverUrl {
+                        result.autoUploadDirectory = serverUrl
+                    } else {
+                        result.autoUploadDirectory = self.getAccountAutoUploadDirectory(urlBase: urlBase, account: account)
+                    }
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func setAccountUserProfile(_ userProfile: NCCommunicationUserProfile) -> tableAccount? {
+
+        let realm = try! Realm()
+
+        var returnAccount = tableAccount()
+
+        do {
+            guard let activeAccount = self.getActiveAccount() else {
+                return nil
+            }
+
+            try realm.safeWrite {
+
+                guard let result = realm.objects(tableAccount.self).filter("account == %@", activeAccount.account).first else {
+                    return
+                }
+
+                result.address = userProfile.address
+                result.backend = userProfile.backend
+                result.backendCapabilitiesSetDisplayName = userProfile.backendCapabilitiesSetDisplayName
+                result.backendCapabilitiesSetPassword = userProfile.backendCapabilitiesSetPassword
+                result.displayName = userProfile.displayName
+                result.email = userProfile.email
+                result.enabled = userProfile.enabled
+                result.groups = userProfile.groups.joined(separator: ",")
+                result.language = userProfile.language
+                result.lastLogin = userProfile.lastLogin
+                result.locale = userProfile.locale
+                result.phone = userProfile.phone
+                result.quota = userProfile.quota
+                result.quotaFree = userProfile.quotaFree
+                result.quotaRelative = userProfile.quotaRelative
+                result.quotaTotal = userProfile.quotaTotal
+                result.quotaUsed = userProfile.quotaUsed
+                result.storageLocation = userProfile.storageLocation
+                result.subadmin = userProfile.subadmin.joined(separator: ",")
+                result.twitter = userProfile.twitter
+                result.userId = userProfile.userId
+                result.webpage = userProfile.webpage
+
+                returnAccount = result
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+
+        return tableAccount.init(value: returnAccount)
+    }
+
+    @objc func setAccountUserProfileHC(businessSize: String, businessType: String, city: String, company: String, country: String, role: String, zip: String) -> tableAccount? {
+
+        let realm = try! Realm()
+
+        var returnAccount = tableAccount()
+
+        do {
+            guard let activeAccount = self.getActiveAccount() else {
+                return nil
+            }
+
+            try realm.safeWrite {
+
+                guard let result = realm.objects(tableAccount.self).filter("account == %@", activeAccount.account).first else {
+                    return
+                }
+
+                result.businessSize = businessSize
+                result.businessType = businessType
+                result.city = city
+                result.company = company
+                result.country = country
+                result.role = role
+                result.zip = zip
+
+                returnAccount = result
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+
+        return tableAccount.init(value: returnAccount)
+    }
+
+    /*
+    #if !EXTENSION
+    @objc func setAccountHCFeatures(_ features: HCFeatures) -> tableAccount? {
+        
+        let realm = try! Realm()
+        
+        var returnAccount = tableAccount()
+
+        do {
+            guard let account = self.getAccountActive() else {
+                return nil
+            }
+            
+            try realm.write {
+                
+                guard let result = realm.objects(tableAccount.self).filter("account == %@", account.account).first else {
+                    return
+                }
+                
+                result.hcIsTrial = features.isTrial
+                result.hcTrialExpired = features.trialExpired
+                result.hcTrialRemainingSec = features.trialRemainingSec
+                if features.trialEndTime > 0 {
+                    result.hcTrialEndTime = Date(timeIntervalSince1970: features.trialEndTime) as NSDate
+                } else {
+                    result.hcTrialEndTime = nil
+                }
+                
+                result.hcAccountRemoveExpired = features.accountRemoveExpired
+                result.hcAccountRemoveRemainingSec = features.accountRemoveRemainingSec
+                if features.accountRemoveTime > 0 {
+                    result.hcAccountRemoveTime = Date(timeIntervalSince1970: features.accountRemoveTime) as NSDate
+                } else {
+                    result.hcAccountRemoveTime = nil
+                }
+                
+                result.hcNextGroupExpirationGroup = features.nextGroupExpirationGroup
+                result.hcNextGroupExpirationGroupExpired = features.nextGroupExpirationGroupExpired
+                if features.nextGroupExpirationExpiresTime > 0 {
+                    result.hcNextGroupExpirationExpiresTime = Date(timeIntervalSince1970: features.nextGroupExpirationExpiresTime) as NSDate
+                } else {
+                    result.hcNextGroupExpirationExpiresTime = nil
+                }
+                result.hcNextGroupExpirationExpires = features.nextGroupExpirationExpires
+                
+                returnAccount = result
+            }
+        } catch let error {
+            print("[LOG] Could not write to database: ", error)
+        }
+        
+        return tableAccount.init(value: returnAccount)
+    }
+    #endif
+    */
+
+    @objc func setAccountMediaPath(_ path: String, account: String) {
+
+        let realm = try! Realm()
+        do {
+            try realm.safeWrite {
+                if let result = realm.objects(tableAccount.self).filter("account == %@", account).first {
+                    result.mediaPath = path
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func setAccountUserStatus(userStatusClearAt: NSDate?, userStatusIcon: String?, userStatusMessage: String?, userStatusMessageId: String?, userStatusMessageIsPredefined: Bool, userStatusStatus: String?, userStatusStatusIsUserDefined: Bool, account: String) {
+
+        let realm = try! Realm()
+        do {
+            try realm.safeWrite {
+                if let result = realm.objects(tableAccount.self).filter("account == %@", account).first {
+                    result.userStatusClearAt = userStatusClearAt
+                    result.userStatusIcon = userStatusIcon
+                    result.userStatusMessage = userStatusMessage
+                    result.userStatusMessageId = userStatusMessageId
+                    result.userStatusMessageIsPredefined = userStatusMessageIsPredefined
+                    result.userStatusStatus = userStatusStatus
+                    result.userStatusStatusIsUserDefined = userStatusStatusIsUserDefined
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func setAccountAlias(_ alias: String?) {
+
+        let realm = try! Realm()
+        let alias = alias?.trimmingCharacters(in: .whitespacesAndNewlines)
+
+        do {
+            try realm.safeWrite {
+                if let result = realm.objects(tableAccount.self).filter("active == true").first {
+                    if let alias = alias {
+                        result.alias = alias
+                    } else {
+                        result.alias = ""
+                    }
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func setAccountColorFiles(lightColorBackground: String, darkColorBackground: String) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                if let result = realm.objects(tableAccount.self).filter("active == true").first {
+                    result.lightColorBackground = lightColorBackground
+                    result.darkColorBackground = darkColorBackground
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+}

+ 235 - 0
iOSClient/Data/NCManageDatabase+Activity.swift

@@ -0,0 +1,235 @@
+//
+//  NCManageDatabase+Activity.swift
+//  Nextcloud
+//
+//  Created by Henrik Storch on 30.11.21.
+//  Copyright © 2021 Marino Faggiana. All rights reserved.
+//
+
+import Foundation
+import RealmSwift
+import NCCommunication
+import SwiftyJSON
+
+extension NCManageDatabase {
+    
+    // MARK: -
+    // MARK: Table Activity
+
+    @objc func addActivity(_ activities: [NCCommunicationActivity], account: String) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.write {
+
+                for activity in activities {
+
+                    let addObjectActivity = tableActivity()
+
+                    addObjectActivity.account = account
+                    addObjectActivity.idActivity = activity.idActivity
+                    addObjectActivity.idPrimaryKey = account + String(activity.idActivity)
+                    addObjectActivity.date = activity.date
+                    addObjectActivity.app = activity.app
+                    addObjectActivity.type = activity.type
+                    addObjectActivity.user = activity.user
+                    addObjectActivity.subject = activity.subject
+
+                    if let subject_rich = activity.subject_rich,
+                       let json = JSON(subject_rich).array {
+
+                        addObjectActivity.subjectRich = json[0].stringValue
+                        if json.count > 1,
+                           let dict = json[1].dictionary {
+
+                            for (key, value) in dict {
+                                let addObjectActivitySubjectRich = tableActivitySubjectRich()
+                                let dict = value as JSON
+                                addObjectActivitySubjectRich.account = account
+
+                                if dict["id"].intValue > 0 {
+                                    addObjectActivitySubjectRich.id = String(dict["id"].intValue)
+                                } else {
+                                    addObjectActivitySubjectRich.id = dict["id"].stringValue
+                                }
+
+                                addObjectActivitySubjectRich.name = dict["name"].stringValue
+                                addObjectActivitySubjectRich.idPrimaryKey = account
+                                + String(activity.idActivity)
+                                + addObjectActivitySubjectRich.id
+                                + addObjectActivitySubjectRich.name
+
+                                addObjectActivitySubjectRich.key = key
+                                addObjectActivitySubjectRich.idActivity = activity.idActivity
+                                addObjectActivitySubjectRich.link = dict["link"].stringValue
+                                addObjectActivitySubjectRich.path = dict["path"].stringValue
+                                addObjectActivitySubjectRich.type = dict["type"].stringValue
+
+                                realm.add(addObjectActivitySubjectRich, update: .all)
+                            }
+                        }
+                    }
+
+                    if let previews = activity.previews,
+                       let json = JSON(previews).array {
+                        for preview in json {
+                            let addObjectActivityPreview = tableActivityPreview()
+
+                            addObjectActivityPreview.account = account
+                            addObjectActivityPreview.idActivity = activity.idActivity
+                            addObjectActivityPreview.fileId = preview["fileId"].intValue
+                            addObjectActivityPreview.filename = preview["filename"].stringValue
+                            addObjectActivityPreview.idPrimaryKey = account + String(activity.idActivity) + String(addObjectActivityPreview.fileId)
+                            addObjectActivityPreview.source = preview["source"].stringValue
+                            addObjectActivityPreview.link = preview["link"].stringValue
+                            addObjectActivityPreview.mimeType = preview["mimeType"].stringValue
+                            addObjectActivityPreview.view = preview["view"].stringValue
+                            addObjectActivityPreview.isMimeTypeIcon = preview["isMimeTypeIcon"].boolValue
+
+                            realm.add(addObjectActivityPreview, update: .all)
+                        }
+                    }
+
+                    addObjectActivity.icon = activity.icon
+                    addObjectActivity.link = activity.link
+                    addObjectActivity.message = activity.message
+                    addObjectActivity.objectType = activity.object_type
+                    addObjectActivity.objectId = activity.object_id
+                    addObjectActivity.objectName = activity.object_name
+
+                    realm.add(addObjectActivity, update: .all)
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    func getActivity(predicate: NSPredicate, filterFileId: String?) -> (all: [tableActivity], filter: [tableActivity]) {
+
+        let realm = try! Realm()
+
+        let results = realm.objects(tableActivity.self).filter(predicate).sorted(byKeyPath: "idActivity", ascending: false)
+        let allActivity = Array(results.map(tableActivity.init))
+        guard let filterFileId = filterFileId else {
+            return (all: allActivity, filter: allActivity)
+        }
+
+        // comments are loaded seperately, see NCManageDatabase.getComments
+        let filtered = allActivity.filter({ String($0.objectId) == filterFileId && $0.type != "comments" })
+        return (all: allActivity, filter: filtered)
+    }
+
+    @objc func getActivitySubjectRich(account: String, idActivity: Int, key: String) -> tableActivitySubjectRich? {
+
+        let realm = try! Realm()
+
+        let results = realm.objects(tableActivitySubjectRich.self).filter("account == %@ && idActivity == %d && key == %@", account, idActivity, key).first
+
+        return results.map { tableActivitySubjectRich.init(value: $0) }
+    }
+
+    @objc func getActivitySubjectRich(account: String, idActivity: Int, id: String) -> tableActivitySubjectRich? {
+
+        let realm = try! Realm()
+
+        let results = realm.objects(tableActivitySubjectRich.self).filter("account == %@ && idActivity == %d && id == %@", account, idActivity, id).first
+
+        return results.map { tableActivitySubjectRich.init(value: $0) }
+    }
+
+    @objc func getActivityPreview(account: String, idActivity: Int, orderKeysId: [String]) -> [tableActivityPreview] {
+
+        let realm = try! Realm()
+
+        var results: [tableActivityPreview] = []
+
+        for id in orderKeysId {
+            if let result = realm.objects(tableActivityPreview.self).filter("account == %@ && idActivity == %d && fileId == %d", account, idActivity, Int(id) ?? 0).first {
+                results.append(result)
+            }
+        }
+
+        return results
+    }
+
+    @objc func updateLatestActivityId(_ activities: [NCCommunicationActivity], account: String) {
+        let realm = try! Realm()
+        let previousRecentId = getLatestActivityId(account: account)
+
+        do {
+            try realm.write {
+                guard
+                    let mostRecentActivityId = activities.map({ $0.idActivity }).max(),
+                    mostRecentActivityId > previousRecentId
+                else { return }
+
+                let newRecentActivity = tableActivityLatestId()
+                newRecentActivity.mostRecentlyLoadedActivityId = mostRecentActivityId
+                newRecentActivity.account = account
+                realm.add(newRecentActivity, update: .all)
+            }
+        } catch {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func getLatestActivityId(account: String) -> Int {
+
+        let realm = try! Realm()
+        guard let maxId = realm.objects(tableActivityLatestId.self)
+                .filter("account == %@", account)
+                .map({ $0.mostRecentlyLoadedActivityId }).max()
+        else { return 0 }
+
+        return maxId
+    }
+    
+    // MARK: -
+    // MARK: Table Comments
+
+    @objc func addComments(_ comments: [NCCommunicationComments], account: String, objectId: String) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+
+                let results = realm.objects(tableComments.self).filter("account == %@ AND objectId == %@", account, objectId)
+                realm.delete(results)
+
+                for comment in comments {
+
+                    let object = tableComments()
+
+                    object.account = account
+                    object.actorDisplayName = comment.actorDisplayName
+                    object.actorId = comment.actorId
+                    object.actorType = comment.actorType
+                    object.creationDateTime = comment.creationDateTime as NSDate
+                    object.isUnread = comment.isUnread
+                    object.message = comment.message
+                    object.messageId = comment.messageId
+                    object.objectId = comment.objectId
+                    object.objectType = comment.objectType
+                    object.path = comment.path
+                    object.verb = comment.verb
+
+                    realm.add(object, update: .all)
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func getComments(account: String, objectId: String) -> [tableComments] {
+
+        let realm = try! Realm()
+
+        let results = realm.objects(tableComments.self).filter("account == %@ AND objectId == %@", account, objectId).sorted(byKeyPath: "creationDateTime", ascending: false)
+
+        return Array(results.map(tableComments.init))
+    }
+}

Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 691 - 2163
iOSClient/Data/NCManageDatabase.swift


+ 789 - 0
iOSClient/Data/NCManageDatabse+Metadata.swift

@@ -0,0 +1,789 @@
+//
+//  NCManageDatabse+Metadata.swift
+//  Nextcloud
+//
+//  Created by Henrik Storch on 30.11.21.
+//  Copyright © 2021 Marino Faggiana. All rights reserved.
+//
+
+import Foundation
+import RealmSwift
+import NCCommunication
+
+extension NCManageDatabase {
+
+    @objc func copyObject(metadata: tableMetadata) -> tableMetadata {
+        return tableMetadata.init(value: metadata)
+    }
+
+    @objc func convertNCFileToMetadata(_ file: NCCommunicationFile, isEncrypted: Bool, account: String) -> tableMetadata {
+
+        let metadata = tableMetadata()
+
+        metadata.account = account
+        metadata.checksums = file.checksums
+        metadata.commentsUnread = file.commentsUnread
+        metadata.contentType = file.contentType
+        if let date = file.creationDate {
+            metadata.creationDate = date
+        } else {
+            metadata.creationDate = file.date
+        }
+        metadata.dataFingerprint = file.dataFingerprint
+        metadata.date = file.date
+        metadata.directory = file.directory
+        metadata.downloadURL = file.downloadURL
+        metadata.e2eEncrypted = file.e2eEncrypted
+        metadata.etag = file.etag
+        metadata.ext = file.ext
+        metadata.favorite = file.favorite
+        metadata.fileId = file.fileId
+        metadata.fileName = file.fileName
+        metadata.fileNameView = file.fileName
+        metadata.fileNameWithoutExt = file.fileNameWithoutExt
+        metadata.hasPreview = file.hasPreview
+        metadata.iconName = file.iconName
+        metadata.livePhoto = file.livePhoto
+        metadata.mountType = file.mountType
+        metadata.note = file.note
+        metadata.ocId = file.ocId
+        metadata.ownerId = file.ownerId
+        metadata.ownerDisplayName = file.ownerDisplayName
+        metadata.path = file.path
+        metadata.permissions = file.permissions
+        metadata.quotaUsedBytes = file.quotaUsedBytes
+        metadata.quotaAvailableBytes = file.quotaAvailableBytes
+        metadata.richWorkspace = file.richWorkspace
+        metadata.resourceType = file.resourceType
+        metadata.serverUrl = file.serverUrl
+        metadata.sharePermissionsCollaborationServices = file.sharePermissionsCollaborationServices
+        for element in file.sharePermissionsCloudMesh {
+            metadata.sharePermissionsCloudMesh.append(element)
+        }
+        for element in file.shareType {
+            metadata.shareType.append(element)
+        }
+        metadata.size = file.size
+        metadata.classFile = file.classFile
+        if let date = file.uploadDate {
+            metadata.uploadDate = date
+        } else {
+            metadata.uploadDate = file.date
+        }
+        metadata.urlBase = file.urlBase
+        metadata.user = file.user
+        metadata.userId = file.userId
+
+        // E2EE find the fileName for fileNameView
+        if isEncrypted || metadata.e2eEncrypted {
+            if let tableE2eEncryption = NCManageDatabase.shared.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", account, file.serverUrl, file.fileName)) {
+                metadata.fileNameView = tableE2eEncryption.fileName
+                let results = NCCommunicationCommon.shared.getInternalType(fileName: metadata.fileNameView, mimeType: file.contentType, directory: file.directory)
+                metadata.contentType = results.mimeType
+                metadata.iconName = results.iconName
+                metadata.classFile = results.classFile
+            }
+        }
+
+        // Live Photo "DETECT"
+        if !metadata.directory && !metadata.livePhoto && (metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue) {
+            var classFile = metadata.classFile
+            if classFile == NCCommunicationCommon.typeClassFile.image.rawValue {
+                classFile = NCCommunicationCommon.typeClassFile.video.rawValue
+            } else {
+                classFile = NCCommunicationCommon.typeClassFile.image.rawValue
+            }
+            if getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameWithoutExt == %@ AND ocId != %@ AND classFile == %@", metadata.account, metadata.serverUrl, metadata.fileNameWithoutExt, metadata.ocId, classFile)) != nil {
+                metadata.livePhoto = true
+            }
+        }
+
+        return metadata
+    }
+
+    @objc func convertNCCommunicationFilesToMetadatas(_ files: [NCCommunicationFile], useMetadataFolder: Bool, account: String, completion: @escaping (_ metadataFolder: tableMetadata, _ metadatasFolder: [tableMetadata], _ metadatas: [tableMetadata]) -> Void) {
+
+        var counter: Int = 0
+        var isEncrypted: Bool = false
+        var listServerUrl: [String: Bool] = [:]
+
+        var metadataFolder = tableMetadata()
+        var metadataFolders: [tableMetadata] = []
+        var metadatas: [tableMetadata] = []
+
+        for file in files {
+
+            if let key = listServerUrl[file.serverUrl] {
+                isEncrypted = key
+            } else {
+                isEncrypted = CCUtility.isFolderEncrypted(file.serverUrl, e2eEncrypted: file.e2eEncrypted, account: account, urlBase: file.urlBase)
+                listServerUrl[file.serverUrl] = isEncrypted
+            }
+
+            let metadata = convertNCFileToMetadata(file, isEncrypted: isEncrypted, account: account)
+
+            if counter == 0 && useMetadataFolder {
+                metadataFolder = tableMetadata.init(value: metadata)
+            } else {
+                metadatas.append(metadata)
+                if metadata.directory {
+                    metadataFolders.append(metadata)
+                }
+            }
+
+            counter += 1
+        }
+
+        completion(metadataFolder, metadataFolders, metadatas)
+    }
+
+    @objc func createMetadata(account: String, user: String, userId: String, fileName: String, fileNameView: String, ocId: String, serverUrl: String, urlBase: String, url: String, contentType: String, livePhoto: Bool) -> tableMetadata {
+
+        let metadata = tableMetadata()
+        let resultInternalType = NCCommunicationCommon.shared.getInternalType(fileName: fileName, mimeType: contentType, directory: false)
+
+        metadata.account = account
+        metadata.chunk = false
+        metadata.contentType = resultInternalType.mimeType
+        metadata.creationDate = Date() as NSDate
+        metadata.date = Date() as NSDate
+        metadata.hasPreview = true
+        metadata.iconName = resultInternalType.iconName
+        metadata.etag = ocId
+        metadata.ext = (fileName as NSString).pathExtension.lowercased()
+        metadata.fileName = fileName
+        metadata.fileNameView = fileName
+        metadata.fileNameWithoutExt = (fileName as NSString).deletingPathExtension
+        metadata.livePhoto = livePhoto
+        metadata.ocId = ocId
+        metadata.permissions = "RGDNVW"
+        metadata.serverUrl = serverUrl
+        metadata.classFile = resultInternalType.classFile
+        metadata.uploadDate = Date() as NSDate
+        metadata.url = url
+        metadata.urlBase = urlBase
+        metadata.user = user
+        metadata.userId = userId
+
+        return metadata
+    }
+
+    @objc func addMetadata(_ metadata: tableMetadata) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                realm.add(metadata, update: .all)
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func addMetadatas(_ metadatas: [tableMetadata]) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                for metadata in metadatas {
+                    realm.add(metadata, update: .all)
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func deleteMetadata(predicate: NSPredicate) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                let results = realm.objects(tableMetadata.self).filter(predicate)
+                realm.delete(results)
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func moveMetadata(ocId: String, serverUrlTo: String) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first {
+                    result.serverUrl = serverUrlTo
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func addMetadataServerUrl(ocId: String, serverUrl: String) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                let results = realm.objects(tableMetadata.self).filter("ocId == %@", ocId)
+                for result in results {
+                    result.serverUrl = serverUrl
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func renameMetadata(fileNameTo: String, ocId: String) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first {
+                    let resultsType = NCCommunicationCommon.shared.getInternalType(fileName: fileNameTo, mimeType: "", directory: result.directory)
+                    result.fileName = fileNameTo
+                    result.fileNameView = fileNameTo
+                    if result.directory {
+                        result.fileNameWithoutExt = fileNameTo
+                        result.ext = ""
+                    } else {
+                        result.fileNameWithoutExt = (fileNameTo as NSString).deletingPathExtension
+                        result.ext = resultsType.ext
+                    }
+                    result.iconName = resultsType.iconName
+                    result.contentType = resultsType.mimeType
+                    result.classFile = resultsType.classFile
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @discardableResult
+    func updateMetadatas(_ metadatas: [tableMetadata], metadatasResult: [tableMetadata], addCompareLivePhoto: Bool = true, addExistsInLocal: Bool = false, addCompareEtagLocal: Bool = false, addDirectorySynchronized: Bool = false) -> (metadatasUpdate: [tableMetadata], metadatasLocalUpdate: [tableMetadata], metadatasDelete: [tableMetadata]) {
+
+        let realm = try! Realm()
+        var ocIdsUdate: [String] = []
+        var ocIdsLocalUdate: [String] = []
+        var metadatasDelete: [tableMetadata] = []
+        var metadatasUpdate: [tableMetadata] = []
+        var metadatasLocalUpdate: [tableMetadata] = []
+
+        realm.refresh()
+
+        do {
+            try realm.safeWrite {
+
+                // DELETE
+                for metadataResult in metadatasResult {
+                    if metadatas.firstIndex(where: { $0.ocId == metadataResult.ocId }) == nil {
+                        if let result = realm.objects(tableMetadata.self).filter(NSPredicate(format: "ocId == %@", metadataResult.ocId)).first {
+                            metadatasDelete.append(tableMetadata.init(value: result))
+                            realm.delete(result)
+                        }
+                    }
+                }
+
+                // UPDATE/NEW
+                for metadata in metadatas {
+
+                    if let result = metadatasResult.first(where: { $0.ocId == metadata.ocId }) {
+                        // update
+                        if result.status == NCGlobal.shared.metadataStatusNormal && (result.etag != metadata.etag || result.fileNameView != metadata.fileNameView || result.date != metadata.date || result.permissions != metadata.permissions || result.hasPreview != metadata.hasPreview || result.note != metadata.note) {
+                            ocIdsUdate.append(metadata.ocId)
+                            realm.add(tableMetadata.init(value: metadata), update: .all)
+                        } else if result.status == NCGlobal.shared.metadataStatusNormal && addCompareLivePhoto && result.livePhoto != metadata.livePhoto {
+                            ocIdsUdate.append(metadata.ocId)
+                            realm.add(tableMetadata.init(value: metadata), update: .all)
+                        }
+                    } else {
+                        // new
+                        ocIdsUdate.append(metadata.ocId)
+                        realm.add(tableMetadata.init(value: metadata), update: .all)
+                    }
+
+                    if metadata.directory && !ocIdsUdate.contains(metadata.ocId) {
+                        let table = realm.objects(tableDirectory.self).filter(NSPredicate(format: "ocId == %@", metadata.ocId)).first
+                        if table?.etag != metadata.etag {
+                            ocIdsUdate.append(metadata.ocId)
+                        }
+                    }
+
+                    // Local
+                    if !metadata.directory && (addExistsInLocal || addCompareEtagLocal) {
+                        let localFile = realm.objects(tableLocalFile.self).filter(NSPredicate(format: "ocId == %@", metadata.ocId)).first
+                        if addCompareEtagLocal && localFile != nil && localFile?.etag != metadata.etag {
+                            ocIdsLocalUdate.append(metadata.ocId)
+                        }
+                        if addExistsInLocal && (localFile == nil || localFile?.etag != metadata.etag) && !ocIdsLocalUdate.contains(metadata.ocId) {
+                            ocIdsLocalUdate.append(metadata.ocId)
+                        }
+                    }
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+
+        for ocId in ocIdsUdate {
+            if let result = realm.objects(tableMetadata.self).filter(NSPredicate(format: "ocId == %@", ocId)).first {
+                metadatasUpdate.append(tableMetadata.init(value: result))
+            }
+        }
+
+        for ocId in ocIdsLocalUdate {
+            if let result = realm.objects(tableMetadata.self).filter(NSPredicate(format: "ocId == %@", ocId)).first {
+                metadatasLocalUpdate.append(tableMetadata.init(value: result))
+            }
+        }
+
+        return (metadatasUpdate, metadatasLocalUpdate, metadatasDelete)
+    }
+
+    func setMetadataSession(ocId: String, session: String? = nil, sessionError: String? = nil, sessionSelector: String? = nil, sessionTaskIdentifier: Int? = nil, status: Int? = nil, etag: String? = nil) {
+
+        let realm = try! Realm()
+        realm.refresh()
+
+        do {
+            try realm.safeWrite {
+                let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
+                if let session = session {
+                    result?.session = session
+                }
+                if let sessionError = sessionError {
+                    result?.sessionError = sessionError
+                }
+                if let sessionSelector = sessionSelector {
+                    result?.sessionSelector = sessionSelector
+                }
+                if let sessionTaskIdentifier = sessionTaskIdentifier {
+                    result?.sessionTaskIdentifier = sessionTaskIdentifier
+                }
+                if let status = status {
+                    result?.status = status
+                }
+                if let etag = etag {
+                    result?.etag = etag
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @discardableResult
+    func setMetadataStatus(ocId: String, status: Int) -> tableMetadata? {
+
+        let realm = try! Realm()
+        var result: tableMetadata?
+
+        do {
+            try realm.safeWrite {
+                result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
+                result?.status = status
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+
+        if let result = result {
+            return tableMetadata.init(value: result)
+        } else {
+            return nil
+        }
+    }
+
+    func setMetadataEtagResource(ocId: String, etagResource: String?) {
+
+        let realm = try! Realm()
+        var result: tableMetadata?
+        guard let etagResource = etagResource else { return }
+
+        do {
+            try realm.safeWrite {
+                result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
+                result?.etagResource = etagResource
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func setMetadataFavorite(ocId: String, favorite: Bool) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
+                result?.favorite = favorite
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func updateMetadatasFavorite(account: String, metadatas: [tableMetadata]) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                let results = realm.objects(tableMetadata.self).filter("account == %@ AND favorite == true", account)
+                for result in results {
+                    result.favorite = false
+                }
+                for metadata in metadatas {
+                    realm.add(metadata, update: .all)
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func setMetadataEncrypted(ocId: String, encrypted: Bool) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
+                result?.e2eEncrypted = encrypted
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func setMetadataFileNameView(serverUrl: String, fileName: String, newFileNameView: String, account: String) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                let result = realm.objects(tableMetadata.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", account, serverUrl, fileName).first
+                result?.fileNameView = newFileNameView
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func getMetadata(predicate: NSPredicate) -> tableMetadata? {
+
+        let realm = try! Realm()
+        realm.refresh()
+
+        guard let result = realm.objects(tableMetadata.self).filter(predicate).first else {
+            return nil
+        }
+
+        return tableMetadata.init(value: result)
+    }
+
+    @objc func getMetadata(predicate: NSPredicate, sorted: String, ascending: Bool) -> tableMetadata? {
+
+        let realm = try! Realm()
+        realm.refresh()
+
+        guard let result = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending).first else {
+            return nil
+        }
+
+        return tableMetadata.init(value: result)
+    }
+
+    @objc func getMetadatasViewer(predicate: NSPredicate, sorted: String, ascending: Bool) -> [tableMetadata]? {
+
+        let realm = try! Realm()
+        realm.refresh()
+
+        let results: Results<tableMetadata>
+        var finals: [tableMetadata] = []
+
+        if (tableMetadata().objectSchema.properties.contains { $0.name == sorted }) {
+            results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
+        } else {
+            results = realm.objects(tableMetadata.self).filter(predicate)
+        }
+
+        // For Live Photo
+        var fileNameImages: [String] = []
+        let filtered = results.filter { $0.classFile.contains(NCCommunicationCommon.typeClassFile.image.rawValue) }
+        filtered.forEach { print($0)
+            let fileName = ($0.fileNameView as NSString).deletingPathExtension
+            fileNameImages.append(fileName)
+        }
+
+        for result in results {
+
+            let ext = (result.fileNameView as NSString).pathExtension.uppercased()
+            let fileName = (result.fileNameView as NSString).deletingPathExtension
+
+            if !(ext == "MOV" && fileNameImages.contains(fileName)) {
+                finals.append(result)
+            }
+        }
+
+        if finals.count > 0 {
+            return Array(finals.map { tableMetadata.init(value: $0) })
+        } else {
+            return nil
+        }
+    }
+
+    @objc func getMetadatas(predicate: NSPredicate) -> [tableMetadata] {
+
+        let realm = try! Realm()
+        realm.refresh()
+
+        let results = realm.objects(tableMetadata.self).filter(predicate)
+
+        return Array(results.map { tableMetadata.init(value: $0) })
+    }
+
+    @objc func getAdvancedMetadatas(predicate: NSPredicate, page: Int = 0, limit: Int = 0, sorted: String, ascending: Bool) -> [tableMetadata] {
+
+        let realm = try! Realm()
+        realm.refresh()
+        var metadatas: [tableMetadata] = []
+
+        let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
+
+        if results.count > 0 {
+            if page == 0 || limit == 0 {
+                return Array(results.map { tableMetadata.init(value: $0) })
+            } else {
+
+                let nFrom = (page - 1) * limit
+                let nTo = nFrom + (limit - 1)
+
+                for n in nFrom...nTo {
+                    if n == results.count {
+                        break
+                    }
+                    metadatas.append(tableMetadata.init(value: results[n]))
+                }
+            }
+        }
+        return metadatas
+    }
+
+    @objc func getMetadataAtIndex(predicate: NSPredicate, sorted: String, ascending: Bool, index: Int) -> tableMetadata? {
+
+        let realm = try! Realm()
+        realm.refresh()
+
+        let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
+
+        if results.count > 0  && results.count > index {
+            return tableMetadata.init(value: results[index])
+        } else {
+            return nil
+        }
+    }
+
+    @objc func getMetadataFromOcId(_ ocId: String?) -> tableMetadata? {
+
+        let realm = try! Realm()
+        realm.refresh()
+
+        guard let ocId = ocId else { return nil }
+        guard let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first else { return nil }
+
+        return tableMetadata.init(value: result)
+    }
+
+    @objc func getMetadataFolder(account: String, urlBase: String, serverUrl: String) -> tableMetadata? {
+
+        let realm = try! Realm()
+        realm.refresh()
+        var serverUrl = serverUrl
+        var fileName = ""
+
+        let serverUrlHome = NCUtilityFileSystem.shared.getHomeServer(account: account)
+        if serverUrlHome == serverUrl {
+            fileName = "."
+            serverUrl = ".."
+        } else {
+            fileName = (serverUrl as NSString).lastPathComponent
+            serverUrl = NCUtilityFileSystem.shared.deletingLastPathComponent(account: account, serverUrl: serverUrl)
+        }
+
+        guard let result = realm.objects(tableMetadata.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", account, serverUrl, fileName).first else { return nil }
+
+        return tableMetadata.init(value: result)
+    }
+
+    @objc func getTableMetadatasDirectoryFavoriteIdentifierRank(account: String) -> [String: NSNumber] {
+
+        var listIdentifierRank: [String: NSNumber] = [:]
+        let realm = try! Realm()
+        var counter = 10 as Int64
+
+        let results = realm.objects(tableMetadata.self).filter("account == %@ AND directory == true AND favorite == true", account).sorted(byKeyPath: "fileNameView", ascending: true)
+
+        for result in results {
+            counter += 1
+            listIdentifierRank[result.ocId] = NSNumber(value: Int64(counter))
+        }
+
+        return listIdentifierRank
+    }
+
+    @objc func clearMetadatasUpload(account: String) {
+
+        let realm = try! Realm()
+        realm.refresh()
+
+        do {
+            try realm.safeWrite {
+
+                let results = realm.objects(tableMetadata.self).filter("account == %@ AND (status == %d OR status == %@)", account, NCGlobal.shared.metadataStatusWaitUpload, NCGlobal.shared.metadataStatusUploadError)
+                realm.delete(results)
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func readMarkerMetadata(account: String, fileId: String) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                let results = realm.objects(tableMetadata.self).filter("account == %@ AND fileId == %@", account, fileId)
+                for result in results {
+                    result.commentsUnread = false
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func getAssetLocalIdentifiersUploaded(account: String, sessionSelector: String) -> [String] {
+
+        let realm = try! Realm()
+        realm.refresh()
+
+        var assetLocalIdentifiers: [String] = []
+
+        let results = realm.objects(tableMetadata.self).filter("account == %@ AND assetLocalIdentifier != '' AND deleteAssetLocalIdentifier == true AND sessionSelector == %@", account, sessionSelector)
+        for result in results {
+            assetLocalIdentifiers.append(result.assetLocalIdentifier)
+        }
+
+        return assetLocalIdentifiers
+    }
+
+    @objc func clearAssetLocalIdentifiers(_ assetLocalIdentifiers: [String], account: String) {
+
+        let realm = try! Realm()
+
+        do {
+            try realm.safeWrite {
+                let results = realm.objects(tableMetadata.self).filter("account == %@ AND assetLocalIdentifier IN %@", account, assetLocalIdentifiers)
+                for result in results {
+                    result.assetLocalIdentifier = ""
+                    result.deleteAssetLocalIdentifier = false
+                }
+            }
+        } catch let error {
+            NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
+        }
+    }
+
+    @objc func getMetadataLivePhoto(metadata: tableMetadata) -> tableMetadata? {
+
+        let realm = try! Realm()
+        var classFile = metadata.classFile
+
+        realm.refresh()
+
+        if !metadata.livePhoto || !CCUtility.getLivePhoto() {
+            return nil
+        }
+
+        if classFile == NCCommunicationCommon.typeClassFile.image.rawValue {
+            classFile = NCCommunicationCommon.typeClassFile.video.rawValue
+        } else {
+            classFile = NCCommunicationCommon.typeClassFile.image.rawValue
+        }
+
+        guard let result = realm.objects(tableMetadata.self).filter(NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameWithoutExt == %@ AND ocId != %@ AND classFile == %@", metadata.account, metadata.serverUrl, metadata.fileNameWithoutExt, metadata.ocId, classFile)).first else {
+            return nil
+        }
+
+        return tableMetadata.init(value: result)
+    }
+
+    func getMetadatasMedia(predicate: NSPredicate, sort: String, ascending: Bool = false) -> [tableMetadata] {
+
+        let realm = try! Realm()
+        realm.refresh()
+
+        let sortProperties = [SortDescriptor(keyPath: sort, ascending: ascending), SortDescriptor(keyPath: "fileNameView", ascending: false)]
+        let results = realm.objects(tableMetadata.self).filter(predicate).sorted(by: sortProperties)
+
+        return Array(results.map { tableMetadata.init(value: $0) })
+    }
+
+    func isMetadataShareOrMounted(metadata: tableMetadata, metadataFolder: tableMetadata?) -> Bool {
+
+        var isShare = false
+        var isMounted = false
+
+        if metadataFolder != nil {
+
+            isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
+            isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
+
+        } else if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
+
+            isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !directory.permissions.contains(NCGlobal.shared.permissionShared)
+            isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !directory.permissions.contains(NCGlobal.shared.permissionMounted)
+        }
+
+        if isShare || isMounted {
+            return true
+        } else {
+            return false
+        }
+    }
+
+    func isDownloadMetadata(_ metadata: tableMetadata, download: Bool) -> Bool {
+
+        let localFile = getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
+        let fileSize = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
+        if (localFile != nil || download) && (localFile?.etag != metadata.etag || fileSize == 0) {
+            return true
+        }
+        return false
+    }
+
+    func getMetadataConflict(account: String, serverUrl: String, fileName: String) -> tableMetadata? {
+
+        // verify exists conflict
+        let fileNameExtension = (fileName as NSString).pathExtension.lowercased()
+        let fileNameWithoutExtension = (fileName as NSString).deletingPathExtension
+        var fileNameConflict = fileName
+
+        if fileNameExtension == "heic" && CCUtility.getFormatCompatibility() {
+            fileNameConflict = fileNameWithoutExtension + ".jpg"
+        }
+        return getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account, serverUrl, fileNameConflict))
+    }
+}

+ 60 - 60
iOSClient/Diagnostics/NCCapabilitiesViewController.swift

@@ -27,63 +27,63 @@ import NCCommunication
 class NCCapabilitiesViewController: UIViewController, UIDocumentInteractionControllerDelegate {
 
     @IBOutlet weak var textView: UITextView!
-    
+
     @IBOutlet weak var imageFileSharing: UIImageView!
     @IBOutlet weak var statusFileSharing: UILabel!
-    
+
     @IBOutlet weak var imageExternalSite: UIImageView!
     @IBOutlet weak var statusExternalSite: UILabel!
-    
+
     @IBOutlet weak var imageEndToEndEncryption: UIImageView!
     @IBOutlet weak var statusEndToEndEncryption: UILabel!
-        
+
     @IBOutlet weak var imageActivity: UIImageView!
     @IBOutlet weak var statusActivity: UILabel!
-   
+
     @IBOutlet weak var imageNotification: UIImageView!
     @IBOutlet weak var statusNotification: UILabel!
-    
+
     @IBOutlet weak var imageDeletedFiles: UIImageView!
     @IBOutlet weak var statusDeletedFiles: UILabel!
-    
+
     @IBOutlet weak var imageUserStatus: UIImageView!
     @IBOutlet weak var statusUserStatus: UILabel!
-    
+
     @IBOutlet weak var imageComments: UIImageView!
     @IBOutlet weak var statusComments: UILabel!
-    
+
     @IBOutlet weak var imageText: UIImageView!
     @IBOutlet weak var statusText: UILabel!
-    
+
     @IBOutlet weak var imageCollabora: UIImageView!
     @IBOutlet weak var statusCollabora: UILabel!
-    
+
     @IBOutlet weak var imageOnlyOffice: UIImageView!
     @IBOutlet weak var statusOnlyOffice: UILabel!
-    
+
     @IBOutlet weak var homeImage: UIImageView!
     @IBOutlet weak var homeServer: UILabel!
-       
+
     private let appDelegate = UIApplication.shared.delegate as! AppDelegate
     private var documentController: UIDocumentInteractionController?
     private var account: String = ""
     private var capabilitiesText = ""
-    //private var timer: Timer?
-    
+    // private var timer: Timer?
+
     // MARK: - View Life Cycle
 
     override func viewDidLoad() {
         super.viewDidLoad()
-        
+
         self.title = NSLocalizedString("_capabilities_", comment: "")
-               
-        let shareImage = UIImage.init(named: "shareFill")!.image(color: .gray, size: 25)
+
+        let shareImage = UIImage(named: "shareFill")!.image(color: .gray, size: 25)
         self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: shareImage, style: UIBarButtonItem.Style.plain, target: self, action: #selector(share))
         self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_done_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(close))
 
         textView.layer.cornerRadius = 15
         textView.layer.masksToBounds = true
-        
+
         statusFileSharing.layer.cornerRadius = 12.5
         statusFileSharing.layer.borderWidth = 0.5
         statusFileSharing.layer.borderColor = UIColor.gray.cgColor
@@ -139,77 +139,77 @@ class NCCapabilitiesViewController: UIViewController, UIDocumentInteractionContr
         statusComments.layer.borderColor = UIColor.gray.cgColor
         statusComments.layer.masksToBounds = true
 
-        imageFileSharing.image = UIImage.init(named: "share")!.image(color: NCBrandColor.shared.gray, size: 50)
+        imageFileSharing.image = UIImage(named: "share")!.image(color: NCBrandColor.shared.gray, size: 50)
         imageExternalSite.image = NCUtility.shared.loadImage(named: "network", color: NCBrandColor.shared.gray)
         imageEndToEndEncryption.image = NCUtility.shared.loadImage(named: "lock", color: NCBrandColor.shared.gray)
-        imageActivity.image = UIImage.init(named: "bolt")!.image(color: NCBrandColor.shared.gray, size: 50)
+        imageActivity.image = UIImage(named: "bolt")!.image(color: NCBrandColor.shared.gray, size: 50)
         imageNotification.image = NCUtility.shared.loadImage(named: "bell", color: NCBrandColor.shared.gray)
         imageDeletedFiles.image = NCUtility.shared.loadImage(named: "trash", color: NCBrandColor.shared.gray)
-        imageText.image = UIImage.init(named: "text")!.image(color: NCBrandColor.shared.gray, size: 50)
-        imageCollabora.image = UIImage.init(named: "collabora")!.image(color: NCBrandColor.shared.gray, size: 50)
-        imageOnlyOffice.image = UIImage.init(named: "onlyoffice")!.image(color: NCBrandColor.shared.gray, size: 50)
-        imageUserStatus.image = UIImage.init(named: "userStatusAway")!.image(color: NCBrandColor.shared.gray, size: 50)
-        imageComments.image = UIImage.init(named: "comments")!.image(color: NCBrandColor.shared.gray, size: 50)
+        imageText.image = UIImage(named: "text")!.image(color: NCBrandColor.shared.gray, size: 50)
+        imageCollabora.image = UIImage(named: "collabora")!.image(color: NCBrandColor.shared.gray, size: 50)
+        imageOnlyOffice.image = UIImage(named: "onlyoffice")!.image(color: NCBrandColor.shared.gray, size: 50)
+        imageUserStatus.image = UIImage(named: "userStatusAway")!.image(color: NCBrandColor.shared.gray, size: 50)
+        imageComments.image = UIImage(named: "comments")!.image(color: NCBrandColor.shared.gray, size: 50)
 
         guard let activeAccount = NCManageDatabase.shared.getActiveAccount() else { return }
         self.account = activeAccount.account
-        
+
         if let text = NCManageDatabase.shared.getCapabilities(account: activeAccount.account) {
             capabilitiesText = text
             updateCapabilities()
         } else {
             NCContentPresenter.shared.messageNotification("_error_", description: "_no_capabilities_found_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorInternalError, priority: .max)
-            
+
             DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                 self.dismiss(animated: true, completion: nil)
             }
         }
-        
-        homeImage.image = UIImage.init(named: "home")!.image(color: NCBrandColor.shared.gray, size: 50)
+
+        homeImage.image = UIImage(named: "home")!.image(color: NCBrandColor.shared.gray, size: 50)
         homeServer.text = NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account) + "/"
     }
 
     @objc func updateCapabilities() {
-        
-        NCCommunication.shared.getCapabilities() { (account, data, errorCode, errorDescription) in
+
+        NCCommunication.shared.getCapabilities { account, data, errorCode, _ in
             if errorCode == 0 && data != nil {
                 NCManageDatabase.shared.addCapabilitiesJSon(data!, account: account)
-                
+
                 // EDITORS
                 let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
                 if serverVersionMajor >= NCGlobal.shared.nextcloudVersion18 {
-                    NCCommunication.shared.NCTextObtainEditorDetails() { (account, editors, creators, errorCode, errorMessage) in
+                    NCCommunication.shared.NCTextObtainEditorDetails { account, editors, creators, errorCode, _ in
                         if errorCode == 0 && account == self.appDelegate.account {
                             NCManageDatabase.shared.addDirectEditing(account: account, editors: editors, creators: creators)
                             self.readCapabilities()
                         }
                         if self.view.window != nil {
-                            //self.timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.updateCapabilities), userInfo: nil, repeats: false)
+                            // self.timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.updateCapabilities), userInfo: nil, repeats: false)
                         }
                     }
                 } else {
                     if self.view.window != nil {
-                        //self.timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.updateCapabilities), userInfo: nil, repeats: false)
+                        // self.timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.updateCapabilities), userInfo: nil, repeats: false)
                     }
                 }
-                
+
                 if let text = NCManageDatabase.shared.getCapabilities(account: account) {
                     self.capabilitiesText = text
                 }
                 self.readCapabilities()
             }
         }
-        
+
         readCapabilities()
     }
-    
+
     @objc func share() {
-        //timer?.invalidate()
+        // timer?.invalidate()
         self.dismiss(animated: true) {
             let fileURL = NSURL.fileURL(withPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent("capabilities.txt")
             do {
                 try self.capabilitiesText.write(to: fileURL, atomically: true, encoding: .utf8)
-                
+
                 if let view = self.appDelegate.window?.rootViewController?.view {
                     self.documentController = UIDocumentInteractionController(url: fileURL)
                     self.documentController?.delegate = self
@@ -218,58 +218,58 @@ class NCCapabilitiesViewController: UIViewController, UIDocumentInteractionContr
             } catch { }
         }
     }
-    
+
     @objc func close() {
-        //timer?.invalidate()
+        // timer?.invalidate()
         self.dismiss(animated: true, completion: nil)
     }
-    
+
     func readCapabilities() {
-        
+
         textView.text = capabilitiesText
-        
+
         if NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesFileSharingApiEnabled, exists: false) {
             statusFileSharing.text = "✓ " + NSLocalizedString("_available_", comment: "")
         } else {
             statusFileSharing.text = NSLocalizedString("_not_available_", comment: "")
         }
-        
+
         if NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesExternalSitesExists, exists: true) {
             statusExternalSite.text = "✓ " + NSLocalizedString("_available_", comment: "")
         } else {
             statusExternalSite.text = NSLocalizedString("_not_available_", comment: "")
         }
-        
+
         let isE2EEEnabled = NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesE2EEEnabled, exists: false)
-        //let versionE2EE = NCManageDatabase.shared.getCapabilitiesServerString(account: account, elements: NCElementsJSON.shared.capabilitiesE2EEApiVersion)
-        
+        // let versionE2EE = NCManageDatabase.shared.getCapabilitiesServerString(account: account, elements: NCElementsJSON.shared.capabilitiesE2EEApiVersion)
+
         if isE2EEEnabled {
             statusEndToEndEncryption.text = "✓ " + NSLocalizedString("_available_", comment: "")
         } else {
             statusEndToEndEncryption.text = NSLocalizedString("_not_available_", comment: "")
         }
-      
+
         let activity = NCManageDatabase.shared.getCapabilitiesServerArray(account: account, elements: NCElementsJSON.shared.capabilitiesActivity)
         if activity != nil {
             statusActivity.text = "✓ " + NSLocalizedString("_available_", comment: "")
         } else {
             statusActivity.text = NSLocalizedString("_not_available_", comment: "")
         }
-        
+
         let notification = NCManageDatabase.shared.getCapabilitiesServerArray(account: account, elements: NCElementsJSON.shared.capabilitiesNotification)
         if notification != nil {
             statusNotification.text = "✓ " + NSLocalizedString("_available_", comment: "")
         } else {
             statusNotification.text = NSLocalizedString("_not_available_", comment: "")
         }
-        
+
         let deleteFiles = NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesFilesUndelete, exists: false)
         if deleteFiles {
             statusDeletedFiles.text = "✓ " + NSLocalizedString("_available_", comment: "")
         } else {
             statusDeletedFiles.text = NSLocalizedString("_not_available_", comment: "")
         }
-        
+
         var textEditor = false
         var onlyofficeEditors = false
         if let editors = NCManageDatabase.shared.getDirectEditingEditors(account: account) {
@@ -281,40 +281,40 @@ class NCCapabilitiesViewController: UIViewController, UIDocumentInteractionContr
                 }
             }
         }
-        
+
         if textEditor {
             statusText.text = "✓ " + NSLocalizedString("_available_", comment: "")
         } else {
             statusText.text = NSLocalizedString("_not_available_", comment: "")
         }
-        
+
         let richdocumentsMimetypes = NCManageDatabase.shared.getCapabilitiesServerArray(account: account, elements: NCElementsJSON.shared.capabilitiesRichdocumentsMimetypes)
         if richdocumentsMimetypes != nil {
             statusCollabora.text = "✓ " + NSLocalizedString("_available_", comment: "")
         } else {
             statusCollabora.text = NSLocalizedString("_not_available_", comment: "")
         }
-        
+
         if onlyofficeEditors {
             statusOnlyOffice.text = "✓ " + NSLocalizedString("_available_", comment: "")
         } else {
             statusOnlyOffice.text = NSLocalizedString("_not_available_", comment: "")
         }
-        
+
         let userStatus = NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesUserStatusEnabled, exists: false)
         if userStatus {
             statusUserStatus.text = "✓ " + NSLocalizedString("_available_", comment: "")
         } else {
             statusUserStatus.text = NSLocalizedString("_not_available_", comment: "")
         }
-        
+
         let comments = NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesFilesComments, exists: false)
         if comments {
             statusComments.text = "✓ " + NSLocalizedString("_available_", comment: "")
         } else {
             statusComments.text = NSLocalizedString("_not_available_", comment: "")
         }
-        
+
         print("end.")
     }
 }

+ 21 - 21
iOSClient/EmptyView/NCEmptyDataSet.swift

@@ -23,7 +23,7 @@
 
 import UIKit
 
-public protocol NCEmptyDataSetDelegate {
+public protocol NCEmptyDataSetDelegate: AnyObject {
     func emptyDataSetView(_ view: NCEmptyView)
 }
 
@@ -33,32 +33,32 @@ public extension NCEmptyDataSetDelegate {
 }
 
 class NCEmptyDataSet: NSObject {
-    
+
     private var emptyView: NCEmptyView?
     private var timer: Timer?
     private var numberItemsForSections: Int = 0
-    private var delegate: NCEmptyDataSetDelegate?
+    private weak var delegate: NCEmptyDataSetDelegate?
 
     private var fillBackgroundName: String = ""
     private var fillBackgroundView = UIImageView()
 
     init(view: UIView, offset: CGFloat = 0, delegate: NCEmptyDataSetDelegate?) {
         super.init()
-                
+
         if let emptyView = UINib(nibName: "NCEmptyView", bundle: nil).instantiate(withOwner: self, options: nil).first as? NCEmptyView {
-        
+
             self.delegate = delegate
             self.emptyView = emptyView
-            
+
             emptyView.isHidden = true
             emptyView.translatesAutoresizingMaskIntoConstraints = false
-            
+
 //            emptyView.backgroundColor = .red
 //            emptyView.isHidden = false
-            
+
             emptyView.emptyTitle.sizeToFit()
             emptyView.emptyDescription.sizeToFit()
-                          
+
             view.addSubview(emptyView)
 
             emptyView.widthAnchor.constraint(equalToConstant: 350).isActive = true
@@ -72,31 +72,31 @@ class NCEmptyDataSet: NSObject {
             }
         }
     }
-        
+
     func numberOfItemsInSection(_ num: Int, section: Int) {
-        
+
         if section == 0 {
             numberItemsForSections = num
         } else {
-            numberItemsForSections = numberItemsForSections + num
+            numberItemsForSections += num
         }
-        
+
         if let emptyView = emptyView {
-            
+
             self.delegate?.emptyDataSetView(emptyView)
-            
+
             if !(timer?.isValid ?? false) && emptyView.isHidden == true {
                 timer = Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(timerHandler(_:)), userInfo: nil, repeats: false)
             }
-            
+
             if numberItemsForSections > 0 {
                 self.emptyView?.isHidden = true
             }
         }
     }
-    
+
     @objc func timerHandler(_ timer: Timer) {
-        
+
         if numberItemsForSections == 0 {
             self.emptyView?.isHidden = false
         } else {
@@ -106,14 +106,14 @@ class NCEmptyDataSet: NSObject {
 }
 
 public class NCEmptyView: UIView {
-    
+
     @IBOutlet weak var emptyImage: UIImageView!
     @IBOutlet weak var emptyTitle: UILabel!
     @IBOutlet weak var emptyDescription: UILabel!
-    
+
     public override func awakeFromNib() {
         super.awakeFromNib()
-        
+
         emptyTitle.textColor = NCBrandColor.shared.label
     }
 }

+ 2 - 2
iOSClient/Extensions/NSMutableAttributedString+Extensions.swift

@@ -27,9 +27,9 @@ import UIKit
 extension NSMutableAttributedString {
 
     func setColor(color: UIColor, font: UIFont? = nil, forText stringValue: String) {
-        
+
         let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)
-        
+
         self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
         if let font = font {
             self.addAttribute(NSAttributedString.Key.font, value: font, range: range)

+ 2 - 3
iOSClient/Extensions/NotificationCenter+MainThread.swift

@@ -26,13 +26,12 @@ import UIKit
 
 extension NotificationCenter {
 
-    func postOnMainThread(name: String, object anObject: Any? = nil, userInfo aUserInfo: [AnyHashable : Any]? = nil, second: Double = 0) {
+    func postOnMainThread(name: String, object anObject: Any? = nil, userInfo aUserInfo: [AnyHashable: Any]? = nil, second: Double = 0) {
 //        if UIApplication.shared.applicationState == .background {
 //            return
 //        }
         DispatchQueue.main.asyncAfter(deadline: .now() + second) {
-            NotificationCenter.default.post(name: Notification.Name.init(rawValue: name), object: anObject, userInfo: aUserInfo)
+            NotificationCenter.default.post(name: Notification.Name(rawValue: name), object: anObject, userInfo: aUserInfo)
         }
     }
 }
-

+ 5 - 5
iOSClient/Extensions/String+Extensions.swift

@@ -34,7 +34,7 @@ extension String {
             })
         return initials.isEmpty ? nil : initials
     }
-    
+
     func formatSecondsToString(_ seconds: TimeInterval) -> String {
         if seconds.isNaN {
             return "00:00:00"
@@ -44,14 +44,14 @@ extension String {
         let hour = Int(seconds / 3600)
         return String(format: "%02d:%02d:%02d", hour, min, sec)
     }
-    
+
     func md5() -> String {
         //https://stackoverflow.com/a/32166735/9506784
 
         let length = Int(CC_MD5_DIGEST_LENGTH)
-        let messageData = self.data(using:.utf8)!
+        let messageData = self.data(using: .utf8)!
         var digestData = Data(count: length)
-        
+
         _ = digestData.withUnsafeMutableBytes { digestBytes -> UInt8 in
             messageData.withUnsafeBytes { messageBytes -> UInt8 in
                 if let messageBytesBaseAddress = messageBytes.baseAddress, let digestBytesBlindMemory = digestBytes.bindMemory(to: UInt8.self).baseAddress {
@@ -61,7 +61,7 @@ extension String {
                 return 0
             }
         }
-        
+
         return digestData.map { String(format: "%02hhx", $0) }.joined()
     }
 }

+ 19 - 19
iOSClient/Extensions/UIColor+Extensions.swift

@@ -25,9 +25,9 @@ import Foundation
 import UIKit
 
 extension UIColor {
-    
+
     var hexString: String {
-            
+
         let cgColorInRGB = cgColor.converted(to: CGColorSpace(name: CGColorSpace.sRGB)!, intent: .defaultIntent, options: nil)!
         let colorRef = cgColorInRGB.components
         let r = colorRef?[0] ?? 0
@@ -48,29 +48,29 @@ extension UIColor {
 
         return color
     }
-    
+
     @objc convenience init?(hex: String) {
 
         let r, g, b, a: CGFloat
-        
+
         if hex.hasPrefix("#") {
-            
+
             let start = hex.index(hex.startIndex, offsetBy: 1)
             let hexColor = String(hex[start...])
             let scanner = Scanner(string: hexColor)
             var hexNumber: UInt64 = 0
-            
+
             if hexColor.count == 6 && scanner.scanHexInt64(&hexNumber) {
-                
+
                 r = CGFloat((hexNumber & 0xff0000) >> 16) / 255.0
                 g = CGFloat((hexNumber & 0x00ff00) >> 8) / 255.0
                 b = CGFloat(hexNumber & 0x0000ff) / 255.0
 
                 self.init(red: r, green: g, blue: b, alpha: 1)
                 return
-                
+
             } else if hexColor.count == 7 && scanner.scanHexInt64(&hexNumber) {
-                    
+
                 r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
                 g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
                 b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
@@ -80,10 +80,10 @@ extension UIColor {
                 return
             }
         }
-        
+
         return nil
     }
-    
+
     @objc func lighter(by percentage: CGFloat = 30.0) -> UIColor? {
         return self.adjust(by: abs(percentage) )
     }
@@ -103,29 +103,29 @@ extension UIColor {
             return nil
         }
     }
-    
+
     @objc func isTooLight() -> Bool {
-        
+
         var white: CGFloat = 0.0
         self.getWhite(&white, alpha: nil)
         if white == 1 { return true }
-        
+
         guard let components = cgColor.components, components.count > 2 else {return false}
         let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000
         return (brightness > 0.95)
     }
-    
+
     @objc func isTooDark() -> Bool {
-        
+
         var white: CGFloat = 0.0
         self.getWhite(&white, alpha: nil)
         if white == 0 { return true }
-        
+
         guard let components = cgColor.components, components.count > 2 else {return false}
         let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000
         return (brightness < 0.05)
     }
-    
+
     func isLight(threshold: Float = 0.7) -> Bool {
         let originalCGColor = self.cgColor
 
@@ -138,7 +138,7 @@ extension UIColor {
         let brightness = Float(((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000)
         return (brightness > threshold)
     }
-    
+
     func image(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
         return UIGraphicsImageRenderer(size: size).image { rendererContext in
             self.setFill()

+ 6 - 6
iOSClient/Extensions/UIControl+Extensions.swift

@@ -25,16 +25,16 @@
 import Foundation
 
 public class ActionClosure {
-    
-    public let selector : Selector
-    private let closure : (_ sendersender: Any?) -> ()
-    
-    init(_ attachObj: AnyObject, closure: @escaping (_ sender: Any?) -> ()) {
+
+    public let selector: Selector
+    private let closure : (_ sendersender: Any?) -> Void
+
+    init(_ attachObj: AnyObject, closure: @escaping (_ sender: Any?) -> Void) {
         self.closure = closure
         self.selector = #selector(target(_ :))
         objc_setAssociatedObject(attachObj, UUID().uuidString, self, .OBJC_ASSOCIATION_RETAIN)
     }
-    
+
     @objc func target(_ sender: Any?) {
         closure(sender)
     }

+ 24 - 24
iOSClient/Extensions/UIImage+Extensions.swift

@@ -26,9 +26,9 @@ import UIKit
 import Accelerate
 
 extension UIImage {
-    
+
     @objc func resizeImage(size: CGSize, isAspectRation: Bool) -> UIImage? {
-        
+
         let originRatio = self.size.width / self.size.height
         let newRatio = size.width / size.height
         var newSize = size
@@ -38,11 +38,11 @@ extension UIImage {
                 newSize.height = size.height
                 newSize.width = size.height * originRatio
             } else {
-                newSize.width = size.width;
+                newSize.width = size.width
                 newSize.height = size.width / originRatio
             }
         }
-        
+
         UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
         self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
         let newImage = UIGraphicsGetImageFromCurrentImageContext()
@@ -52,25 +52,25 @@ extension UIImage {
         }
         return self
     }
-    
+
     func fixedOrientation() -> UIImage? {
-        
+
         guard imageOrientation != UIImage.Orientation.up else {
             // This is default orientation, don't need to do anything
             return self.copy() as? UIImage
         }
-        
+
         guard let cgImage = self.cgImage else {
             // CGImage is not available
             return nil
         }
-        
+
         guard let colorSpace = cgImage.colorSpace, let ctx = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
             return nil // Not able to create CGContext
         }
-        
+
         var transform: CGAffineTransform = CGAffineTransform.identity
-        
+
         switch imageOrientation {
         case .down, .downMirrored:
             transform = transform.translatedBy(x: size.width, y: size.height)
@@ -86,7 +86,7 @@ extension UIImage {
         @unknown default:
             break
         }
-        
+
         // Flip image one more time if needed to, this is to prevent flipped image
         switch imageOrientation {
         case .upMirrored, .downMirrored:
@@ -100,9 +100,9 @@ extension UIImage {
         @unknown default:
             break
         }
-        
+
         ctx.concatenate(transform)
-        
+
         switch imageOrientation {
         case .left, .leftMirrored, .right, .rightMirrored:
             ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
@@ -110,16 +110,16 @@ extension UIImage {
             ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
             break
         }
-        
+
         guard let newCGImage = ctx.makeImage() else { return nil }
-        return UIImage.init(cgImage: newCGImage, scale: 1, orientation: .up)
+        return UIImage(cgImage: newCGImage, scale: 1, orientation: .up)
     }
-    
+
     @objc func image(color: UIColor, size: CGFloat) -> UIImage {
-        
+
         return autoreleasepool { () -> UIImage in
             let size = CGSize(width: size, height: size)
-            
+
             UIGraphicsBeginImageContextWithOptions(size, false, self.scale)
             color.setFill()
 
@@ -135,13 +135,13 @@ extension UIImage {
 
             let newImage = UIGraphicsGetImageFromCurrentImageContext() ?? self
             UIGraphicsEndImageContext()
-            
+
             return newImage
         }
     }
-    
+
     func imageColor(_ color: UIColor) -> UIImage {
-                
+
         if #available(iOS 13.0, *) {
             return self.withTintColor(color, renderingMode: .alwaysOriginal)
         } else {
@@ -151,21 +151,21 @@ extension UIImage {
             }
         }
     }
-    
+
     func isEqualToImage(image: UIImage?) -> Bool {
         if image == nil { return false }
         let data1: NSData = self.pngData()! as NSData
         let data2: NSData = image!.pngData()! as NSData
         return data1.isEqual(data2)
     }
-    
+
     class func imageWithView(_ view: UIView) -> UIImage {
         UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0)
         defer { UIGraphicsEndImageContext() }
         view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
         return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
     }
-    
+
     func image(alpha: CGFloat) -> UIImage? {
         UIGraphicsBeginImageContextWithOptions(size, false, scale)
         draw(at: .zero, blendMode: .normal, alpha: alpha)

+ 23 - 24
iOSClient/Favorites/NCFavorite.swift

@@ -24,74 +24,74 @@
 import UIKit
 import NCCommunication
 
-class NCFavorite: NCCollectionViewCommon  {
-    
+class NCFavorite: NCCollectionViewCommon {
+
     // MARK: - View Life Cycle
 
     required init?(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)
-        
+
         titleCurrentFolder = NSLocalizedString("_favorites_", comment: "")
         layoutKey = NCGlobal.shared.layoutViewFavorite
         enableSearchBar = true
-        emptyImage = UIImage.init(named: "star.fill")?.image(color: NCBrandColor.shared.yellowFavorite, size: UIScreen.main.bounds.width)
+        emptyImage = UIImage(named: "star.fill")?.image(color: NCBrandColor.shared.yellowFavorite, size: UIScreen.main.bounds.width)
         emptyTitle = "_favorite_no_files_"
         emptyDescription = "_tutorial_favorite_view_"
     }
-    
+
     // MARK: - DataSource + NC Endpoint
-    
+
     override func reloadDataSource() {
         super.reloadDataSource()
-        
+
         DispatchQueue.global().async {
-            
+
             if !self.isSearching {
-           
+
                 if self.serverUrl == "" {
                     self.metadatasSource = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND favorite == true", self.appDelegate.account))
                 } else {
                     self.metadatasSource = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
                 }
             }
-            
-            self.dataSource = NCDataSource.init(metadatasSource: self.metadatasSource, sort:self.layoutForView?.sort, ascending: self.layoutForView?.ascending, directoryOnTop: self.layoutForView?.directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
-            
+
+            self.dataSource = NCDataSource(metadatasSource: self.metadatasSource, sort: self.layoutForView?.sort, ascending: self.layoutForView?.ascending, directoryOnTop: self.layoutForView?.directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
+
             DispatchQueue.main.async {
                 self.refreshControl.endRefreshing()
                 self.collectionView.reloadData()
             }
         }
     }
-    
+
     override func reloadDataSourceNetwork(forced: Bool = false) {
         super.reloadDataSourceNetwork(forced: forced)
-        
+
         if isSearching {
             networkSearch()
             return
         }
-        
+
         isReloadDataSourceNetworkInProgress = true
         collectionView?.reloadData()
-        
+
         if serverUrl == "" {
-            
-            NCNetworking.shared.listingFavoritescompletion(selector: NCGlobal.shared.selectorListingFavorite) { (account, metadatas, errorCode, errorDescription) in
+
+            NCNetworking.shared.listingFavoritescompletion(selector: NCGlobal.shared.selectorListingFavorite) { _, _, errorCode, errorDescription in
                 if errorCode != 0 {
                     NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
                 }
-                
+
                 DispatchQueue.main.async {
                     self.refreshControl.endRefreshing()
                     self.isReloadDataSourceNetworkInProgress = false
                     self.reloadDataSource()
                 }
             }
-            
+
         } else {
-            
-            networkReadFolder(forced: forced) { (tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, errorDescription) in
+
+            networkReadFolder(forced: forced) { tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, _ in
                 if errorCode == 0 {
                     for metadata in metadatas ?? [] {
                         if !metadata.directory {
@@ -101,7 +101,7 @@ class NCFavorite: NCCollectionViewCommon  {
                         }
                     }
                 }
-                
+
                 DispatchQueue.main.async {
                     self.refreshControl.endRefreshing()
                     self.isReloadDataSourceNetworkInProgress = false
@@ -116,4 +116,3 @@ class NCFavorite: NCCollectionViewCommon  {
         }
     }
 }
-

+ 27 - 28
iOSClient/FileViewInFolder/NCFileViewInFolder.swift

@@ -25,39 +25,39 @@ import UIKit
 import NCCommunication
 
 class NCFileViewInFolder: NCCollectionViewCommon {
-    
+
     internal var fileName: String?
 
     // MARK: - View Life Cycle
 
     required init?(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)
-        
+
         appDelegate.activeFileViewInFolder = self
         titleCurrentFolder = NCBrandOptions.shared.brand
         layoutKey = NCGlobal.shared.layoutViewViewInFolder
         enableSearchBar = false
-        emptyImage = UIImage.init(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
+        emptyImage = UIImage(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
         emptyTitle = "_files_no_files_"
         emptyDescription = "_no_file_pull_down_"
     }
-    
+
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
-        
+
         appDelegate.activeViewController = self
-        
+
         if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account) {
             self.navigationItem.title = NCBrandOptions.shared.brand
         } else {
             self.navigationItem.title = (serverUrl as NSString).lastPathComponent
         }
-        
+
         presentationController?.delegate = self
-        
+
         layoutForView = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
         gridLayout.itemForLine = CGFloat(layoutForView?.itemForLine ?? 3)
-        
+
         if layoutForView?.layout == NCGlobal.shared.layoutList {
             collectionView?.collectionViewLayout = listLayout
         } else {
@@ -65,7 +65,7 @@ class NCFileViewInFolder: NCCollectionViewCommon {
         }
 
         self.navigationItem.leftBarButtonItem = nil
-        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_close_", comment: ""), style: .plain, target: self, action: #selector(tapClose(sender:)))       
+        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_close_", comment: ""), style: .plain, target: self, action: #selector(tapClose(sender:)))
     }
 
     // MARK: - TAP EVENT
@@ -73,28 +73,28 @@ class NCFileViewInFolder: NCCollectionViewCommon {
     @objc func tapClose(sender: Any) {
         dismiss(animated: true)
     }
-    
+
     // MARK: - DataSource + NC Endpoint
-    
+
     override func reloadDataSource() {
         super.reloadDataSource()
-        
+
         DispatchQueue.global().async {
-            
+
             if !self.isSearching {
                 self.metadatasSource = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
                 if self.metadataFolder == nil {
-                    self.metadataFolder = NCManageDatabase.shared.getMetadataFolder(account: self.appDelegate.account, urlBase: self.appDelegate.urlBase, serverUrl:  self.serverUrl)
+                    self.metadataFolder = NCManageDatabase.shared.getMetadataFolder(account: self.appDelegate.account, urlBase: self.appDelegate.urlBase, serverUrl: self.serverUrl)
                 }
             }
-            
-            self.dataSource = NCDataSource.init(metadatasSource: self.metadatasSource, sort: self.layoutForView?.sort, ascending: self.layoutForView?.ascending, directoryOnTop: self.layoutForView?.directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
-            
+
+            self.dataSource = NCDataSource(metadatasSource: self.metadatasSource, sort: self.layoutForView?.sort, ascending: self.layoutForView?.ascending, directoryOnTop: self.layoutForView?.directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
+
             DispatchQueue.main.async {
-            
+
                 self.refreshControl.endRefreshing()
                 self.collectionView.reloadData()
-                
+
                 // Blink file
                 if self.fileName != nil {
                     if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileName == %@", self.appDelegate.account, self.serverUrl, self.fileName!)) {
@@ -102,7 +102,7 @@ class NCFileViewInFolder: NCCollectionViewCommon {
                             DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                 UIView.animate(withDuration: 0.3) {
                                     self.collectionView.scrollToItem(at: IndexPath(row: row, section: 0), at: .centeredVertically, animated: false)
-                                } completion: { (_) in
+                                } completion: { _ in
                                     if let cell = self.collectionView.cellForItem(at: IndexPath(row: row, section: 0)) {
                                         cell.backgroundColor = .darkGray
                                         UIView.animate(withDuration: 2) {
@@ -118,19 +118,19 @@ class NCFileViewInFolder: NCCollectionViewCommon {
             }
         }
     }
-    
+
     override func reloadDataSourceNetwork(forced: Bool = false) {
         super.reloadDataSourceNetwork(forced: forced)
-        
+
         if isSearching {
             networkSearch()
             return
         }
-        
+
         isReloadDataSourceNetworkInProgress = true
         collectionView?.reloadData()
-               
-        networkReadFolder(forced: forced) { (tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, errorDescription) in
+
+        networkReadFolder(forced: forced) { tableDirectory, metadatas, _, _, errorCode, _ in
             if errorCode == 0 {
                 for metadata in metadatas ?? [] {
                     if !metadata.directory {
@@ -140,7 +140,7 @@ class NCFileViewInFolder: NCCollectionViewCommon {
                     }
                 }
             }
-            
+
             DispatchQueue.main.async {
                 self.refreshControl.endRefreshing()
                 self.isReloadDataSourceNetworkInProgress = false
@@ -150,4 +150,3 @@ class NCFileViewInFolder: NCCollectionViewCommon {
         }
     }
 }
-

+ 25 - 26
iOSClient/Files/NCFiles.swift

@@ -24,82 +24,82 @@
 import UIKit
 import NCCommunication
 
-class NCFiles: NCCollectionViewCommon  {
-    
+class NCFiles: NCCollectionViewCommon {
+
     internal var isRoot: Bool = true
 
     // MARK: - View Life Cycle
 
     required init?(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)
-        
+
         appDelegate.activeFiles = self
         titleCurrentFolder = NCBrandOptions.shared.brand
         layoutKey = NCGlobal.shared.layoutViewFiles
         enableSearchBar = true
-        emptyImage = UIImage.init(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
+        emptyImage = UIImage(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
         emptyTitle = "_files_no_files_"
         emptyDescription = "_no_file_pull_down_"
     }
-    
+
     override func viewWillAppear(_ animated: Bool) {
-        
+
         if isRoot {
             serverUrl = NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account)
             titleCurrentFolder = getNavigationTitle()
         }
-        
+
         super.viewWillAppear(animated)
     }
-    
+
     // MARK: - NotificationCenter
-    
+
     override func initialize() {
-        
+
         if isRoot {
             serverUrl = NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account)
             titleCurrentFolder = getNavigationTitle()
             reloadDataSourceNetwork(forced: true)
         }
-        
+
         super.initialize()
     }
-    
+
     // MARK: - DataSource + NC Endpoint
-    
+
     override func reloadDataSource() {
         super.reloadDataSource()
-        
+
         DispatchQueue.global(qos: .background).async {
-                        
+
             if !self.isSearching && self.appDelegate.account != "" && self.appDelegate.urlBase != "" {
                 self.metadatasSource = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
                 if self.metadataFolder == nil {
                     self.metadataFolder = NCManageDatabase.shared.getMetadataFolder(account: self.appDelegate.account, urlBase: self.appDelegate.urlBase, serverUrl: self.serverUrl)
                 }
             }
-            
-            self.dataSource = NCDataSource.init(metadatasSource: self.metadatasSource, sort: self.layoutForView?.sort, ascending: self.layoutForView?.ascending, directoryOnTop: self.layoutForView?.directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
-            
+
+            self.dataSource = NCDataSource(metadatasSource: self.metadatasSource, sort: self.layoutForView?.sort, ascending: self.layoutForView?.ascending, directoryOnTop: self.layoutForView?.directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
+
             DispatchQueue.main.async { [weak self] in
                 self?.refreshControl.endRefreshing()
-                self?.collectionView.reloadData()                
+                self?.collectionView.reloadData()
             }
         }
     }
-    
+
     override func reloadDataSourceNetwork(forced: Bool = false) {
         super.reloadDataSourceNetwork(forced: forced)
-        
+
         if isSearching {
             networkSearch()
             return
         }
-        
+
         isReloadDataSourceNetworkInProgress = true
         collectionView?.reloadData()
-               
-        networkReadFolder(forced: forced) { (tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, errorDescription) in
+
+        networkReadFolder(forced: forced) { tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, _ in
             if errorCode == 0 {
                 for metadata in metadatas ?? [] {
                     if !metadata.directory {
@@ -109,7 +109,7 @@ class NCFiles: NCCollectionViewCommon  {
                     }
                 }
             }
-            
+
             DispatchQueue.main.async {
                 self.refreshControl.endRefreshing()
                 self.isReloadDataSourceNetworkInProgress = false
@@ -123,4 +123,3 @@ class NCFiles: NCCollectionViewCommon  {
         }
     }
 }
-

+ 17 - 17
iOSClient/Login/NCAppConfigView.swift

@@ -31,20 +31,20 @@ class NCAppConfigView: UIViewController {
     private var serverUrl: String?
     private var username: String?
     private var password: String?
-    
+
     @IBOutlet weak var logoImage: UIImageView!
     @IBOutlet weak var titleLabel: UILabel!
-    
+
     // MARK: - View Life Cycle
 
     override func viewDidLoad() {
         super.viewDidLoad()
-        
+
         self.view.backgroundColor = NCBrandColor.shared.brandElement
         titleLabel.textColor = NCBrandColor.shared.brandText
-        
+
         titleLabel.text = NSLocalizedString("_appconfig_view_title_", comment: "")
-        
+
         if let serverConfig = UserDefaults.standard.dictionary(forKey: NCBrandConfiguration.shared.configuration_bundleId) {
             serverUrl = serverConfig[NCBrandConfiguration.shared.configuration_serverUrl] as? String
             username = serverConfig[NCBrandConfiguration.shared.configuration_username] as? String
@@ -55,13 +55,13 @@ class NCAppConfigView: UIViewController {
             password = UserDefaults.standard.string(forKey: NCBrandConfiguration.shared.configuration_password)
         }
     }
-    
+
     override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)
-        
+
         // Stop timer error network
         appDelegate.timerErrorNetworking?.invalidate()
-        
+
         guard let serverUrl = self.serverUrl else {
             NCContentPresenter.shared.messageNotification("_error_", description: "User Default, serverUrl not found", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError)
             return
@@ -74,28 +74,28 @@ class NCAppConfigView: UIViewController {
             NCContentPresenter.shared.messageNotification("_error_", description: "User Default, password not found", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError)
             return
         }
-        
-        NCCommunication.shared.getAppPassword(serverUrl: serverUrl, username: username, password: password, userAgent: nil) { (token, errorCode, errorDescription) in
+
+        NCCommunication.shared.getAppPassword(serverUrl: serverUrl, username: username, password: password, userAgent: nil) { token, errorCode, errorDescription in
             DispatchQueue.main.async {
                 if errorCode == 0 && token != nil {
                     let account: String = "\(username) \(serverUrl)"
-                    
+
                     // NO account found, clear
                     if NCManageDatabase.shared.getAccounts() == nil { NCUtility.shared.removeAllSettings() }
-                    
+
                     // Add new account
                     NCManageDatabase.shared.deleteAccount(account)
                     NCManageDatabase.shared.addAccount(account, urlBase: serverUrl, user: username, password: token!)
-                    
+
                     guard let tableAccount = NCManageDatabase.shared.setAccountActive(account) else {
                         NCContentPresenter.shared.messageNotification("_error_", description: "setAccountActive error", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError)
                         self.dismiss(animated: true, completion: nil)
                         return
                     }
-                    
+
                     self.appDelegate.settingAccount(account, urlBase: serverUrl, user: username, userId: tableAccount.userId, password: token!)
                     NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
-                    
+
                     self.dismiss(animated: true) {}
                 } else {
                     NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
@@ -103,10 +103,10 @@ class NCAppConfigView: UIViewController {
             }
         }
     }
-    
+
     override func viewDidDisappear(_ animated: Bool) {
         super.viewDidDisappear(animated)
-        
+
         // Start timer error network
         appDelegate.startTimerErrorNetworking()
     }

+ 110 - 110
iOSClient/Login/NCLogin.swift

@@ -25,7 +25,7 @@ import UIKit
 import NCCommunication
 
 class NCLogin: UIViewController, UITextFieldDelegate, NCLoginQRCodeDelegate {
-    
+
     @IBOutlet weak var imageBrand: UIImageView!
     @IBOutlet weak var imageBrandConstraintY: NSLayoutConstraint!
     @IBOutlet weak var baseUrl: UITextField!
@@ -45,7 +45,7 @@ class NCLogin: UIViewController, UITextFieldDelegate, NCLoginQRCodeDelegate {
 
     override func viewDidLoad() {
         super.viewDidLoad()
-                
+
         // Text color
         if NCBrandColor.shared.customer.isTooLight() {
             textColor = .black
@@ -57,10 +57,10 @@ class NCLogin: UIViewController, UITextFieldDelegate, NCLoginQRCodeDelegate {
             textColor = .white
             textColorOpponent = .black
         }
-        
+
         // Image Brand
         imageBrand.image = UIImage(named: "logo")
-        
+
         // Url
         baseUrl.textColor = textColor
         baseUrl.tintColor = textColor
@@ -73,28 +73,28 @@ class NCLogin: UIViewController, UITextFieldDelegate, NCLoginQRCodeDelegate {
         baseUrl.rightViewMode = .always
         baseUrl.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("_login_url_", comment: ""), attributes: [NSAttributedString.Key.foregroundColor: textColor.withAlphaComponent(0.5)])
         baseUrl.delegate = self
-        
+
         // Login button
         loginAddressDetail.textColor = textColor
         loginAddressDetail.text = String.localizedStringWithFormat(NSLocalizedString("_login_address_detail_", comment: ""), NCBrandOptions.shared.brand)
-                
+
         // Login Image
         loginImage.image = UIImage(named: "arrow.right")?.image(color: textColor, size: 100)
-        
+
         // brand
         if NCBrandOptions.shared.disable_request_login_url {
             baseUrl.text = NCBrandOptions.shared.loginBaseUrl
             baseUrl.isHidden = true
         }
-        
+
         // qrcode
         qrCode.setImage(UIImage(named: "qrcode")?.image(color: textColor, size: 100), for: .normal)
-        
+
         // certificate
         certificate.setImage(UIImage(named: "certificate")?.image(color: textColor, size: 100), for: .normal)
         certificate.isHidden = true
         certificate.isEnabled = false
-        
+
         // navigation
         if #available(iOS 13.0, *) {
             let navBarAppearance = UINavigationBarAppearance()
@@ -111,55 +111,55 @@ class NCLogin: UIViewController, UITextFieldDelegate, NCLoginQRCodeDelegate {
             self.navigationController?.navigationBar.barTintColor = NCBrandColor.shared.customer
         }
         self.navigationController?.navigationBar.tintColor = textColor
-        
+
         if NCManageDatabase.shared.getAccounts()?.count ?? 0 == 0 {
-            
+
         } else {
-            
+
             // Cancel Button
-            let navigationItemCancel = UIBarButtonItem.init(barButtonSystemItem: .stop, target: self, action: #selector(self.actionCancel))
+            let navigationItemCancel = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(self.actionCancel))
             navigationItemCancel.tintColor = textColor
-            navigationItem.leftBarButtonItem = navigationItemCancel            
+            navigationItem.leftBarButtonItem = navigationItemCancel
         }
-        
+
         self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
         view.backgroundColor = NCBrandColor.shared.customer
-        
+
         NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
         NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
     }
-    
+
     override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)
-        
+
         appDelegate.timerErrorNetworking?.invalidate()
     }
-    
+
     override func viewDidDisappear(_ animated: Bool) {
         super.viewDidDisappear(animated)
 
         appDelegate.startTimerErrorNetworking()
     }
-    
+
     // MARK: - TextField
-    
+
     func textFieldShouldReturn(_ textField: UITextField) -> Bool {
         textField.resignFirstResponder()
         actionButtonLogin(self)
         return false
     }
-    
+
     func textFieldDidBeginEditing(_ textField: UITextField) {
-   
+
         self.activeTextField = textField
     }
-        
+
     // MARK: - Keyboard notification
-    
-    @objc internal func keyboardWillShow(_ notification : Notification?) {
-                
+
+    @objc internal func keyboardWillShow(_ notification: Notification?) {
+
         activeTextfieldDiff = 0
-        
+
         if let info = notification?.userInfo, let centerObject = self.activeTextField.superview?.convert(self.activeTextField.center, to: nil) {
 
             let frameEndUserInfoKey = UIResponder.keyboardFrameEndUserInfoKey
@@ -172,11 +172,11 @@ class NCLogin: UIViewController, UITextFieldDelegate, NCLoginQRCodeDelegate {
             }
         }
     }
-    
+
     @objc func keyboardWillHide(_ notification: Notification) {
         imageBrandConstraintY.constant -= activeTextfieldDiff
     }
-    
+
     // MARK: - Action
 
     @objc func actionCancel() {
@@ -184,11 +184,11 @@ class NCLogin: UIViewController, UITextFieldDelegate, NCLoginQRCodeDelegate {
     }
 
     @IBAction func actionButtonLogin(_ sender: Any) {
-        
+
         guard var url = baseUrl.text?.trimmingCharacters(in: .whitespacesAndNewlines) else { return }
         if url.hasSuffix("/") { url = String(url.dropLast()) }
         if url.count == 0 { return }
-        
+
         // Check whether baseUrl contain protocol. If not add https:// by default.
         if url.hasPrefix("https") == false && url.hasPrefix("http") == false {
             url = "https://" + url
@@ -196,87 +196,87 @@ class NCLogin: UIViewController, UITextFieldDelegate, NCLoginQRCodeDelegate {
         self.baseUrl.text = url
         isUrlValid(url: url)
     }
-    
+
     @IBAction func actionQRCode(_ sender: Any) {
-        
-        let qrCode = NCLoginQRCode.init(delegate: self)
+
+        let qrCode = NCLoginQRCode(delegate: self)
         qrCode.scan()
     }
-    
+
     @IBAction func actionCertificate(_ sender: Any) {
-        
+
     }
-    
+
     // MARK: - Login
 
     func isUrlValid(url: String) {
-            
+
         loginButton.isEnabled = false
-        
-        NCCommunication.shared.getServerStatus(serverUrl: url) { (serverProductName, serverVersion, versionMajor, versionMinor, versionMicro, extendedSupport, errorCode ,errorDescription) in
-            
+
+        NCCommunication.shared.getServerStatus(serverUrl: url) { _, _, versionMajor, _, _, _, errorCode, errorDescription in
+
             if errorCode == 0 {
-                
+
                 if let host = URL(string: url)?.host {
                     NCNetworking.shared.writeCertificate(host: host)
                 }
-                
-                NCCommunication.shared.getLoginFlowV2(serverUrl: url) { (token, endpoint, login, errorCode, errorDescription) in
-                    
+
+                NCCommunication.shared.getLoginFlowV2(serverUrl: url) { token, endpoint, login, errorCode, _ in
+
                     self.loginButton.isEnabled = true
-                                        
+
                     // Login Flow V2
                     if errorCode == 0 && NCBrandOptions.shared.use_loginflowv2 && token != nil && endpoint != nil && login != nil {
-                        
+
                         if let loginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb {
-                            
+
                             loginWeb.urlBase = url
                             loginWeb.loginFlowV2Available = true
                             loginWeb.loginFlowV2Token = token!
                             loginWeb.loginFlowV2Endpoint = endpoint!
                             loginWeb.loginFlowV2Login = login!
-                            
+
                             self.navigationController?.pushViewController(loginWeb, animated: true)
                         }
-                        
+
                     // Login Flow
                     } else if versionMajor >= NCGlobal.shared.nextcloudVersion12 {
-                        
+
                         if let loginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb {
-                            
+
                             loginWeb.urlBase = url
 
                             self.navigationController?.pushViewController(loginWeb, animated: true)
                         }
-                        
+
                     // NO Login flow available
                     } else if versionMajor < NCGlobal.shared.nextcloudVersion12 {
-                        
+
                         let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_webflow_not_available_", comment: ""), preferredStyle: .alert)
 
-                        alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in }))
-                        
+                        alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
+
                         self.present(alertController, animated: true, completion: { })
                     }
                 }
-                
+
             } else {
-               
+
                 self.loginButton.isEnabled = true
-                
+
                 if errorCode == NSURLErrorServerCertificateUntrusted {
-                    
+
                     let alertController = UIAlertController(title: NSLocalizedString("_ssl_certificate_untrusted_", comment: ""), message: NSLocalizedString("_connect_server_anyway_", comment: ""), preferredStyle: .alert)
-                                
-                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { action in
+
+                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
                         if let host = URL(string: url)?.host {
                             NCNetworking.shared.writeCertificate(host: host)
                         }
                     }))
-                    
-                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { action in }))
-                    
-                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { action in
+
+                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in }))
+
+                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
                         if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController {
                             let viewController = navigationController.topViewController as! NCViewCertificateDetails
                             if let host = URL(string: url)?.host {
@@ -285,123 +285,123 @@ class NCLogin: UIViewController, UITextFieldDelegate, NCLoginQRCodeDelegate {
                             self.present(navigationController, animated: true)
                         }
                     }))
-                    
+
                     self.present(alertController, animated: true)
-                    
+
                 } else {
-                    
+
                     let alertController = UIAlertController(title: NSLocalizedString("_connection_error_", comment: ""), message: errorDescription, preferredStyle: .alert)
 
-                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in }))
-                    
+                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
+
                     self.present(alertController, animated: true, completion: { })
                 }
             }
         }
     }
-    
+
     // MARK: - QRCode
 
     func dismissQRCode(_ value: String?, metadataType: String?) {
-        
+
         guard var value = value else { return }
-        
+
         let protocolLogin = NCBrandOptions.shared.webLoginAutenticationProtocol + "login/"
-        
+
         if value.hasPrefix(protocolLogin) && value.contains("user:") && value.contains("password:") && value.contains("server:") {
-            
+
             value = value.replacingOccurrences(of: protocolLogin, with: "")
             let valueArray = value.components(separatedBy: "&")
             if valueArray.count == 3 {
-                
+
                 let user = valueArray[0].replacingOccurrences(of: "user:", with: "")
                 let password = valueArray[1].replacingOccurrences(of: "password:", with: "")
                 let urlBase = valueArray[2].replacingOccurrences(of: "server:", with: "")
                 let webDAV = NCUtilityFileSystem.shared.getWebDAV(account: appDelegate.account)
                 let serverUrl = urlBase + "/" + webDAV
-                
+
                 loginButton.isEnabled = false
-                
-                NCCommunication.shared.checkServer(serverUrl: serverUrl) { (errorCode, errorDescription) in
-                
+
+                NCCommunication.shared.checkServer(serverUrl: serverUrl) { errorCode, errorDescription in
+
                     self.loginButton.isEnabled = true
                     self.standardLogin(url: urlBase, user: user, password: password, errorCode: errorCode, errorDescription: errorDescription)
                 }
             }
         }
     }
-    
+
     func standardLogin(url: String, user: String, password: String, errorCode: Int, errorDescription: String) {
-        
+
         if errorCode == 0 {
-            
+
             if let host = URL(string: url)?.host {
                 NCNetworking.shared.writeCertificate(host: host)
             }
-            
+
             let account = user + " " + url
-            
+
             if NCManageDatabase.shared.getAccounts() == nil {
                 NCUtility.shared.removeAllSettings()
             }
                            
             NCManageDatabase.shared.deleteAccount(account)
             NCManageDatabase.shared.addAccount(account, urlBase: url, user: user, password: password)
-            
+
             if let activeAccount = NCManageDatabase.shared.setAccountActive(account) {
                 appDelegate.settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
             }
-            
+
             if CCUtility.getIntro() {
-                
+
                 NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
                 self.dismiss(animated: true)
-                
+
             } else {
-                
+
                 CCUtility.setIntro(true)
-                
+
                 if self.presentingViewController == nil {
-                    
+
                     let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
                     viewController?.modalPresentationStyle = .fullScreen
                     NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
                     self.appDelegate.window?.rootViewController = viewController
                     self.appDelegate.window?.makeKey()
-                    
+
                 } else {
-                    
+
                     NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
                     self.dismiss(animated: true)
                 }
             }
-        
+
         } else if errorCode == NSURLErrorServerCertificateUntrusted {
-            
+
             let alertController = UIAlertController(title: NSLocalizedString("_ssl_certificate_untrusted_", comment: ""), message: NSLocalizedString("_connect_server_anyway_", comment: ""), preferredStyle: .alert)
-                        
-            alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { action in
+
+            alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
                 if let host = URL(string: url)?.host {
                     NCNetworking.shared.writeCertificate(host: host)
                 }
             }))
-            
-            alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { action in }))
-            
-            alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { action in
+
+            alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in }))
+
+            alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
                 if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() {
                     self.present(navigationController, animated: true)
                 }
             }))
-            
+
             self.present(alertController, animated: true)
-            
+
         } else {
-            
+
             let message = NSLocalizedString("_not_possible_connect_to_server_", comment: "") + ".\n" + errorDescription
             let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: message, preferredStyle: .alert)
-            
-            alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in }))
+
+            alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
 
             self.present(alertController, animated: true, completion: { })
         }

+ 23 - 23
iOSClient/Login/NCLoginQRCode.swift

@@ -29,11 +29,11 @@ import QRCodeReader
 }
 
 class NCLoginQRCode: NSObject, QRCodeReaderViewControllerDelegate {
-    
+
     lazy var reader: QRCodeReader = QRCodeReader()
-    
+
     weak var delegate: UIViewController?
-    
+
     lazy var readerVC: QRCodeReaderViewController = {
         let builder = QRCodeReaderViewControllerBuilder {
             $0.reader = QRCodeReader(metadataObjectTypes: [.qr], captureDevicePosition: .back)
@@ -41,73 +41,73 @@ class NCLoginQRCode: NSObject, QRCodeReaderViewControllerDelegate {
             $0.preferredStatusBarStyle = .lightContent
             $0.showOverlayView = true
             $0.rectOfInterest = CGRect(x: 0.2, y: 0.2, width: 0.6, height: 0.6)
-            
+
             $0.reader.stopScanningWhenCodeIsFound = false
         }
-        
+
         return QRCodeReaderViewController(builder: builder)
     }()
 
     override init() {
-        
+
     }
-    
+
     @objc public init(delegate: UIViewController) {
         self.delegate = delegate
     }
-    
+
     @objc func scan() {
         guard checkScanPermissions() else { return }
-        
+
         readerVC.modalPresentationStyle = .formSheet
         readerVC.delegate = self
-        
-        readerVC.completionBlock = { (result: QRCodeReaderResult?) in
+
+        readerVC.completionBlock = { (_: QRCodeReaderResult?) in
             self.readerVC.dismiss(animated: true, completion: nil)
         }
-        
+
         delegate?.present(readerVC, animated: true, completion: nil)
     }
-    
+
     private func checkScanPermissions() -> Bool {
         do {
             return try QRCodeReader.supportsMetadataObjectTypes()
         } catch let error as NSError {
             let alert: UIAlertController
-            
+
             switch error.code {
             case -11852:
                 alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_qrcode_not_authorized_", comment: ""), preferredStyle: .alert)
-                
-                alert.addAction(UIAlertAction(title: NSLocalizedString("_settings_", comment: ""), style: .default, handler: { (_) in
+
+                alert.addAction(UIAlertAction(title: NSLocalizedString("_settings_", comment: ""), style: .default, handler: { _ in
                     DispatchQueue.main.async {
                         if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
                             UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
                         }
                     }
                 }))
-                
+
                 alert.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil))
             default:
                 alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_qrcode_not_supported_", comment: ""), preferredStyle: .alert)
                 alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .cancel, handler: nil))
             }
-            
+
             delegate?.present(alert, animated: true, completion: nil)
-            
+
             return false
         }
     }
-    
+
     func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) {
         reader.stopScanning()
-        
+
         (self.delegate as? NCLoginQRCodeDelegate)?.dismissQRCode(result.value, metadataType: result.metadataType)
     }
-    
+
     func readerDidCancel(_ reader: QRCodeReaderViewController) {
         reader.stopScanning()
-        
+
         (self.delegate as? NCLoginQRCodeDelegate)?.dismissQRCode(nil, metadataType: nil)
     }
 }

+ 70 - 70
iOSClient/Login/NCLoginWeb.swift

@@ -27,83 +27,83 @@ import NCCommunication
 import FloatingPanel
 
 class NCLoginWeb: UIViewController {
-    
+
     var activityIndicator: UIActivityIndicatorView!
     var webView: WKWebView?
     let appDelegate = UIApplication.shared.delegate as! AppDelegate
 
     @objc var urlBase = ""
-    
+
     @objc var loginFlowV2Available = false
     @objc var loginFlowV2Token = ""
     @objc var loginFlowV2Endpoint = ""
     @objc var loginFlowV2Login = ""
-    
+
     // MARK: - View Life Cycle
 
     override func viewDidLoad() {
         super.viewDidLoad()
-        
+
         let accountCount = NCManageDatabase.shared.getAccounts()?.count ?? 0
-        
+
         if NCBrandOptions.shared.use_login_web_personalized  && accountCount > 0 {
-            navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .stop, target: self, action: #selector(self.closeView(sender:)))
+            navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(self.closeView(sender:)))
         }
-        
+
         if accountCount > 0 {
-            navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "users")!.image(color: NCBrandColor.shared.label, size: 35), style: .plain, target: self, action:  #selector(self.changeUser(sender:)))
+            navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "users")!.image(color: NCBrandColor.shared.label, size: 35), style: .plain, target: self, action: #selector(self.changeUser(sender:)))
         }
-        
+
         let config = WKWebViewConfiguration()
         config.websiteDataStore = WKWebsiteDataStore.nonPersistent()
 
         webView = WKWebView(frame: CGRect.zero, configuration: config)
         webView!.navigationDelegate = self
         view.addSubview(webView!)
-        
+
         webView!.translatesAutoresizingMaskIntoConstraints = false
         webView!.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
         webView!.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
         webView!.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
         webView!.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
-        
+
         // ADD end point for Web Flow
         if urlBase != NCBrandOptions.shared.linkloginPreferredProviders {
             if loginFlowV2Available {
                 urlBase = loginFlowV2Login
             } else {
-                urlBase = urlBase + "/index.php/login/flow"
+                urlBase += "/index.php/login/flow"
             }
         }
-        
+
         activityIndicator = UIActivityIndicatorView(style: .gray)
         activityIndicator.center = self.view.center
         activityIndicator.startAnimating()
         self.view.addSubview(activityIndicator)
-        
+
         if let url = URL(string: urlBase) {
             loadWebPage(webView: webView!, url: url)
         } else {
             NCContentPresenter.shared.messageNotification("_error_", description: "_login_url_error_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError, priority: .max)
         }
     }
-    
+
     override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)
-        
+
         // Stop timer error network
         appDelegate.timerErrorNetworking?.invalidate()
     }
-    
+
     override func viewDidDisappear(_ animated: Bool) {
         super.viewDidDisappear(animated)
-        
+
         // Start timer error network
         appDelegate.startTimerErrorNetworking()
     }
-    
-    func loadWebPage(webView: WKWebView, url: URL)  {
-        
+
+    func loadWebPage(webView: WKWebView, url: URL) {
+
         let language = NSLocale.preferredLanguages[0] as String
         var request = URLRequest(url: url)
 
@@ -119,88 +119,88 @@ class NCLoginWeb: UIViewController {
 
         webView.load(request)
     }
-    
+
     @objc func closeView(sender: UIBarButtonItem) {
         self.dismiss(animated: true, completion: nil)
     }
-    
+
     @objc func changeUser(sender: UIBarButtonItem) {
         toggleMenu()
     }
 }
 
 extension NCLoginWeb: WKNavigationDelegate {
-    
+
     func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
-        
+
         guard let url = webView.url else { return }
-        
+
         let urlString: String = url.absoluteString.lowercased()
-        
+
         // prevent http redirection
         if urlBase.lowercased().hasPrefix("https://") && urlString.lowercased().hasPrefix("http://") {
             let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_prevent_http_redirection_", comment: ""), preferredStyle: .alert)
-            alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in
+            alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
                 _ = self.navigationController?.popViewController(animated: true)
             }))
             self.present(alertController, animated: true)
             return
         }
-        
-        if (urlString.hasPrefix(NCBrandOptions.shared.webLoginAutenticationProtocol) == true && urlString.contains("login") == true) {
-            
+
+        if urlString.hasPrefix(NCBrandOptions.shared.webLoginAutenticationProtocol) == true && urlString.contains("login") == true {
+
             var server: String = ""
             var user: String = ""
             var password: String = ""
-            
+
             let keyValue = url.path.components(separatedBy: "&")
             for value in keyValue {
                 if value.contains("server:") { server = value }
                 if value.contains("user:") { user = value }
                 if value.contains("password:") { password = value }
             }
-            
+
             if server != "" && user != "" && password != "" {
-                
+
                 let server: String = server.replacingOccurrences(of: "/server:", with: "")
                 let username: String = user.replacingOccurrences(of: "user:", with: "").replacingOccurrences(of: "+", with: " ")
                 let password: String = password.replacingOccurrences(of: "password:", with: "")
-                
+
                 createAccount(server: server, username: username, password: password)
             }
         }
     }
-    
+
     func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
-        
+
     }
-    
+
     func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
-        
+
         var errorMessage = error.localizedDescription
-        
+
         for (key, value) in (error as NSError).userInfo {
             let message = "\(key) \(value)\n"
-            errorMessage = errorMessage + message
+            errorMessage += message
         }
-        
+
         let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorMessage, preferredStyle: .alert)
-                    
-        alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in }))
-        
+
+        alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
+
         self.present(alertController, animated: true)
     }
-    
+
     func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
         if let serverTrust = challenge.protectionSpace.serverTrust {
             completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
         } else {
-            completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil);
+            completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
         }
     }
-    
+
     func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
-        
+
         decisionHandler(.allow)
 
         /* TEST NOT GOOD DON'T WORKS
@@ -235,18 +235,18 @@ extension NCLoginWeb: WKNavigationDelegate {
         webView.load(request)
         */
     }
-    
+
     func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
-        print("didStartProvisionalNavigation");
+        print("didStartProvisionalNavigation")
     }
-    
+
     func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
         activityIndicator.stopAnimating()
-        print("didFinishProvisionalNavigation");
-                
+        print("didFinishProvisionalNavigation")
+
         if loginFlowV2Available {
             DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
-                NCCommunication.shared.getLoginFlowV2Poll(token: self.loginFlowV2Token, endpoint: self.loginFlowV2Endpoint) { (server, loginName, appPassword, errorCode, errorDescription) in
+                NCCommunication.shared.getLoginFlowV2Poll(token: self.loginFlowV2Token, endpoint: self.loginFlowV2Endpoint) { server, loginName, appPassword, errorCode, _ in
                     if errorCode == 0 && server != nil && loginName != nil && appPassword != nil {
                         self.createAccount(server: server!, username: loginName!, password: appPassword!)
                     }
@@ -254,21 +254,21 @@ extension NCLoginWeb: WKNavigationDelegate {
             }
         }
     }
-    
-    //MARK: -
+
+    // MARK: -
 
     func createAccount(server: String, username: String, password: String) {
-        
+
         var urlBase = server
-        
+
         // Normalized
-        if (urlBase.last == "/") {
+        if urlBase.last == "/" {
             urlBase = String(urlBase.dropLast())
         }
-        
+
         // Create account
         let account: String = "\(username) \(urlBase)"
-        
+
         // NO account found, clear all
         if NCManageDatabase.shared.getAccounts() == nil {
             NCUtility.shared.removeAllSettings()
@@ -277,23 +277,23 @@ extension NCLoginWeb: WKNavigationDelegate {
         // Add new account
         NCManageDatabase.shared.deleteAccount(account)
         NCManageDatabase.shared.addAccount(account, urlBase: urlBase, user: username, password: password)
-            
+
         guard let tableAccount = NCManageDatabase.shared.setAccountActive(account) else {
             self.dismiss(animated: true, completion: nil)
             return
         }
-            
+
         appDelegate.settingAccount(account, urlBase: urlBase, user: username, userId: tableAccount.userId, password: password)
-            
-        if (CCUtility.getIntro()) {
-            
+
+        if CCUtility.getIntro() {
+
             NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
             self.dismiss(animated: true)
-                
+
         } else {
-            
+
             CCUtility.setIntro(true)
-            if (self.presentingViewController == nil) {
+            if self.presentingViewController == nil {
                 if let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() {
                     viewController.modalPresentationStyle = .fullScreen
                     NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)

+ 46 - 46
iOSClient/Main/Account Request/NCAccountRequest.swift

@@ -24,7 +24,7 @@
 import UIKit
 import NCCommunication
 
-public protocol NCAccountRequestDelegate {
+public protocol NCAccountRequestDelegate: AnyObject {
     func accountRequestAddAccount()
     func accountRequestChangeAccount(account: String)
 }
@@ -41,28 +41,28 @@ class NCAccountRequest: UIViewController {
     @IBOutlet weak var closeButton: UIButton!
     @IBOutlet weak var tableView: UITableView!
     @IBOutlet weak var progressView: UIProgressView!
-    
+
     public var accounts: [tableAccount] = []
     public var activeAccount: tableAccount?
     public let heightCell: CGFloat = 60
     public var enableTimerProgress: Bool = true
     public var enableAddAccount: Bool = false
     public var dismissDidEnterBackground: Bool = false
-    public var delegate: NCAccountRequestDelegate?
+    public weak var delegate: NCAccountRequestDelegate?
 
     private var timer: Timer?
     private var time: Float = 0
     private let secondsAutoDismiss: Float = 3
-    
+
     // MARK: - View Life Cycle
 
     override func viewDidLoad() {
         super.viewDidLoad()
-        
+
         titleLabel.text = NSLocalizedString("_account_select_", comment: "")
 
         closeButton.setImage(NCUtility.shared.loadImage(named: "xmark", color: NCBrandColor.shared.label), for: .normal)
-        
+
         tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 1))
         tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
 
@@ -73,70 +73,70 @@ class NCAccountRequest: UIViewController {
         } else {
             progressView.isHidden = true
         }
-        
+
         NotificationCenter.default.addObserver(self, selector: #selector(startTimer), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
         NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
-        
+
         changeTheming()
     }
-    
+
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
     }
-    
+
     override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)
-        
+
         let visibleCells = tableView.visibleCells
         var numAccounts = accounts.count
         if enableAddAccount { numAccounts += 1 }
-        
+
         if visibleCells.count == numAccounts {
             tableView.isScrollEnabled = false
         }
     }
-    
+
     override func viewWillDisappear(_ animated: Bool) {
         super.viewWillDisappear(animated)
-        
+
         timer?.invalidate()
     }
-    
+
     override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
         super.traitCollectionDidChange(previousTraitCollection)
-        
+
         changeTheming()
     }
-    
+
     // MARK: - Theming
-    
+
     @objc func changeTheming() {
-        
+
         view.backgroundColor = NCBrandColor.shared.secondarySystemBackground
         tableView.backgroundColor = NCBrandColor.shared.secondarySystemBackground
-        
+
         tableView.reloadData()
     }
-    
+
     // MARK: - Action
-    
+
     @IBAction func actionClose(_ sender: UIButton) {
         dismiss(animated: true)
     }
-    
+
     // MARK: - NotificationCenter
 
     @objc func applicationDidEnterBackground() {
-        
+
         if dismissDidEnterBackground {
             dismiss(animated: false)
         }
     }
 
     // MARK: - Progress
-    
+
     @objc func startTimer() {
-        
+
         if enableTimerProgress {
             time = 0
             timer?.invalidate()
@@ -146,9 +146,9 @@ class NCAccountRequest: UIViewController {
             progressView.isHidden = true
         }
     }
-    
+
     @objc func updateProgress() {
-        
+
         time += 0.1
         if time >= secondsAutoDismiss {
             dismiss(animated: true)
@@ -159,36 +159,36 @@ class NCAccountRequest: UIViewController {
 }
 
 extension NCAccountRequest: UITableViewDelegate {
-    
+
     func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
-        
+
         timer?.invalidate()
         progressView.progress = 0
     }
-    
+
     func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
         if decelerate {
 //            startTimer()
         }
     }
-    
+
     func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
 //        startTimer()
     }
-    
+
     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
         return heightCell
     }
-    
+
     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
-        
+
         if indexPath.row == accounts.count {
-            
+
             dismiss(animated: true)
             delegate?.accountRequestAddAccount()
-            
+
         } else {
-        
+
             let account = accounts[indexPath.row]
             if account.account != activeAccount?.account {
                 dismiss(animated: true) {
@@ -202,7 +202,7 @@ extension NCAccountRequest: UITableViewDelegate {
 }
 
 extension NCAccountRequest: UITableViewDataSource {
-    
+
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         if enableAddAccount {
             return accounts.count + 1
@@ -210,12 +210,12 @@ extension NCAccountRequest: UITableViewDataSource {
             return accounts.count
         }
     }
-    
+
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
-               
+
         let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
         cell.backgroundColor = tableView.backgroundColor
-        
+
         let avatarImage = cell.viewWithTag(10) as? UIImageView
         let userLabel = cell.viewWithTag(20) as? UILabel
         let urlLabel = cell.viewWithTag(30) as? UILabel
@@ -223,9 +223,9 @@ extension NCAccountRequest: UITableViewDataSource {
 
         userLabel?.text = ""
         urlLabel?.text = ""
-        
+
         if indexPath.row == accounts.count {
-           
+
             avatarImage?.image = NCUtility.shared.loadImage(named: "plus").image(color: .systemBlue, size: 15)
             avatarImage?.contentMode = .center
             userLabel?.text = NSLocalizedString("_add_account_", comment: "")
@@ -233,7 +233,7 @@ extension NCAccountRequest: UITableViewDataSource {
             userLabel?.font = UIFont.systemFont(ofSize: 15)
 
         } else {
-        
+
             let account = accounts[indexPath.row]
 
             avatarImage?.image = NCUtility.shared.loadUserImage(
@@ -254,7 +254,7 @@ extension NCAccountRequest: UITableViewDataSource {
                 activeImage?.image = nil
             }
         }
-        
+
         return cell
     }
 }

+ 72 - 73
iOSClient/Main/AudioRecorder/NCAudioRecorderViewController.swift

@@ -28,59 +28,58 @@ import UIKit
 import AVFoundation
 import QuartzCore
 
-@objc protocol NCAudioRecorderViewControllerDelegate : AnyObject {
+@objc protocol NCAudioRecorderViewControllerDelegate: AnyObject {
     func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String)
     func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String)
 }
 
-class NCAudioRecorderViewController: UIViewController , NCAudioRecorderDelegate {
-    
+class NCAudioRecorderViewController: UIViewController, NCAudioRecorderDelegate {
+
     open weak var delegate: NCAudioRecorderViewControllerDelegate?
     var recording: NCAudioRecorder!
     var recordDuration: TimeInterval = 0
     var fileName: String = ""
-    let appDelegate = UIApplication.shared.delegate as! AppDelegate
 
     @IBOutlet weak var contentContainerView: UIView!
     @IBOutlet weak var durationLabel: UILabel!
     @IBOutlet weak var startStopLabel: UILabel!
     @IBOutlet weak var voiceRecordHUD: VoiceRecordHUD!
-    
+
     // MARK: - View Life Cycle
 
     override func viewDidLoad() {
         super.viewDidLoad()
-        
+
         voiceRecordHUD.update(0.0)
         durationLabel.text = ""
         startStopLabel.text = NSLocalizedString("_voice_memo_start_", comment: "")
-        
+
         changeTheming()
     }
-    
+
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
     }
-    
+
     override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
         super.traitCollectionDidChange(previousTraitCollection)
-        
+
         changeTheming()
     }
-    
+
     // MARK: - Colors
-    
+
     func changeTheming() {
-        
+
         view.backgroundColor = .clear
         contentContainerView.backgroundColor = UIColor.lightGray
         voiceRecordHUD.fillColor = UIColor.green
     }
-    
+
     // MARK: - Action
-    
+
     @IBAction func touchViewController() {
-        
+
         if recording.state == .record {
             startStop()
         } else {
@@ -89,21 +88,21 @@ class NCAudioRecorderViewController: UIViewController , NCAudioRecorderDelegate
             }
         }
     }
-    
+
     @IBAction func startStop() {
-        
+
         if recording.state == .record {
-        
+
             recordDuration = 0
             recording.stop()
             voiceRecordHUD.update(0.0)
-        
+
             dismiss(animated: true) {
                 self.delegate?.didFinishRecording(self, fileName: self.fileName)
             }
-            
+
         } else {
-            
+
             recordDuration = 0
             do {
                 try recording.record()
@@ -113,11 +112,11 @@ class NCAudioRecorderViewController: UIViewController , NCAudioRecorderDelegate
             }
         }
     }
-    
+
     // MARK: - Code
-    
+
     func createRecorder(fileName: String) {
-        
+
         self.fileName = fileName
         recording = NCAudioRecorder(to: fileName)
         recording.delegate = self
@@ -131,27 +130,27 @@ class NCAudioRecorderViewController: UIViewController , NCAudioRecorderDelegate
             }
         }
     }
-    
+
     func audioMeterDidUpdate(_ db: Float) {
-        
-        //print("db level: %f", db)
-        
+
+        // print("db level: %f", db)
+
         self.recording.recorder?.updateMeters()
         let ALPHA = 0.05
         let peakPower = pow(10, (ALPHA * Double((self.recording.recorder?.peakPower(forChannel: 0))!)))
         var rate: Double = 0.0
-        if (peakPower <= 0.2) {
+        if peakPower <= 0.2 {
             rate = 0.2
-        } else if (peakPower > 0.9) {
+        } else if peakPower > 0.9 {
             rate = 1.0
         } else {
             rate = peakPower
         }
-        
+
         voiceRecordHUD.update(CGFloat(rate))
         voiceRecordHUD.fillColor = UIColor.green
         recordDuration += 1
-        durationLabel.text =  String.init().formatSecondsToString(recordDuration/60)
+        durationLabel.text =  String().formatSecondsToString(recordDuration/60)
     }
 }
 
@@ -159,24 +158,24 @@ class NCAudioRecorderViewController: UIViewController , NCAudioRecorderDelegate
     @objc optional func audioMeterDidUpdate(_ dB: Float)
 }
 
-open class NCAudioRecorder : NSObject {
-    
+open class NCAudioRecorder: NSObject {
+
     @objc public enum State: Int {
         case none, record, play
     }
-    
+
     static var directory: String {
         return NSTemporaryDirectory()
     }
-    
+
     open weak var delegate: NCAudioRecorderDelegate?
     open fileprivate(set) var url: URL
     open fileprivate(set) var state: State = .none
-    
+
     open var bitRate = 192000
     open var sampleRate = 44100.0
     open var channels = 1
-    
+
     var recorder: AVAudioRecorder?
     fileprivate var player: AVAudioPlayer?
     fileprivate var link: CADisplayLink?
@@ -184,13 +183,13 @@ open class NCAudioRecorder : NSObject {
     var metering: Bool {
         return delegate?.responds(to: #selector(NCAudioRecorderDelegate.audioMeterDidUpdate(_:))) == true
     }
-    
+
     // MARK: - Initializers
-    
+
     public init(to: String) {
         url = URL(fileURLWithPath: NCAudioRecorder.directory).appendingPathComponent(to)
         super.init()
-        
+
         do {
             try AVAudioSession.sharedInstance().setCategory(.playAndRecord)
             try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
@@ -199,50 +198,50 @@ open class NCAudioRecorder : NSObject {
             print(error)
         }
     }
-    
+
     deinit {
         print("deinit NCAudioRecorder")
-        
+
         do {
             try AVAudioSession.sharedInstance().setActive(false)
         } catch {
             print(error)
         }
     }
-    
+
     // MARK: - Record
-    
+
     open func prepare() throws {
-        
+
         let settings: [String: AnyObject] = [
-            AVFormatIDKey : NSNumber(value: Int32(kAudioFormatAppleLossless) as Int32),
+            AVFormatIDKey: NSNumber(value: Int32(kAudioFormatAppleLossless) as Int32),
             AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue as AnyObject,
             AVEncoderBitRateKey: bitRate as AnyObject,
             AVNumberOfChannelsKey: channels as AnyObject,
             AVSampleRateKey: sampleRate as AnyObject
         ]
-        
+
         recorder = try AVAudioRecorder(url: url, settings: settings)
         recorder?.prepareToRecord()
         recorder?.delegate = delegate
         recorder?.isMeteringEnabled = metering
     }
-    
+
     open func record() throws {
-        
+
         if recorder == nil {
             try prepare()
         }
-        
+
         self.state = .record
         if self.metering {
             self.startMetering()
         }
         self.recorder?.record()
     }
-    
+
     open func stop() {
-        
+
         switch state {
         case .play:
             player?.stop()
@@ -254,30 +253,30 @@ open class NCAudioRecorder : NSObject {
         default:
             break
         }
-        
+
         state = .none
     }
-    
+
     // MARK: - Metering
-    
+
     @objc func updateMeter() {
         guard let recorder = recorder else { return }
-        
+
         recorder.updateMeters()
-        
+
         let dB = recorder.averagePower(forChannel: 0)
-        
+
         delegate?.audioMeterDidUpdate?(dB)
     }
-    
+
     fileprivate func startMetering() {
-        
+
         link = CADisplayLink(target: self, selector: #selector(NCAudioRecorder.updateMeter))
         link?.add(to: RunLoop.current, forMode: RunLoop.Mode.common)
     }
-    
+
     fileprivate func stopMetering() {
-        
+
         link?.invalidate()
         link = nil
     }
@@ -286,48 +285,48 @@ open class NCAudioRecorder : NSObject {
 @IBDesignable
 class VoiceRecordHUD: UIView {
     @IBInspectable var rate: CGFloat = 0.0
-    
+
     @IBInspectable var fillColor: UIColor = UIColor.green {
         didSet {
             setNeedsDisplay()
         }
     }
-    
+
     var image: UIImage! {
         didSet {
             setNeedsDisplay()
         }
     }
-    
+
     // MARK: - View Life Cycle
 
     override init(frame: CGRect) {
         super.init(frame: frame)
         image = UIImage(named: "microphone")
     }
-    
+
     required init?(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)
         image = UIImage(named: "microphone")
     }
-    
+
     func update(_ rate: CGFloat) {
         self.rate = rate
         setNeedsDisplay()
     }
-    
+
     override func draw(_ rect: CGRect) {
         let context = UIGraphicsGetCurrentContext()
         context?.translateBy(x: 0, y: bounds.size.height)
         context?.scaleBy(x: 1, y: -1)
-        
+
         context?.draw(image.cgImage!, in: bounds)
         context?.clip(to: bounds, mask: image.cgImage!)
-        
+
         context?.setFillColor(fillColor.cgColor.components!)
         context?.fill(CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height * rate))
     }
-    
+
     override func prepareForInterfaceBuilder() {
         let bundle = Bundle(for: type(of: self))
         image = UIImage(named: "microphone", in: bundle, compatibleWith: self.traitCollection)

Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 214 - 214
iOSClient/Main/Collection Common/NCCollectionViewCommon.swift


+ 29 - 29
iOSClient/Main/Collection Common/NCGridCell.swift

@@ -24,7 +24,7 @@
 import UIKit
 
 class NCGridCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProtocol {
-    
+
     @IBOutlet weak var imageItem: UIImageView!
     @IBOutlet weak var imageSelect: UIImageView!
     @IBOutlet weak var imageStatus: UIImageView!
@@ -38,7 +38,7 @@ class NCGridCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProto
     private var objectId = ""
     private var user = ""
 
-    var delegate: NCGridCellDelegate?
+    weak var delegate: NCGridCellDelegate?
     var namedButtonMore = ""
 
     var fileAvatarImageView: UIImageView? {
@@ -67,13 +67,13 @@ class NCGridCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProto
             user = newValue ?? ""
         }
     }
-    
+
     override func awakeFromNib() {
         super.awakeFromNib()
-        
+
         imageItem.layer.cornerRadius = 6
         imageItem.layer.masksToBounds = true
-        
+
         imageVisualEffect.layer.cornerRadius = 6
         imageVisualEffect.clipsToBounds = true
         imageVisualEffect.alpha = 0.5
@@ -81,46 +81,46 @@ class NCGridCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProto
         progressView.tintColor = NCBrandColor.shared.brandElement
         progressView.transform = CGAffineTransform(scaleX: 1.0, y: 0.5)
         progressView.trackTintColor = .clear
-        
+
         let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gestureRecognizer:)))
         longPressedGesture.minimumPressDuration = 0.5
         longPressedGesture.delegate = self
         longPressedGesture.delaysTouchesBegan = true
         self.addGestureRecognizer(longPressedGesture)
-        
+
         let longPressedGestureMore = UILongPressGestureRecognizer(target: self, action: #selector(longPressInsideMore(gestureRecognizer:)))
         longPressedGestureMore.minimumPressDuration = 0.5
         longPressedGestureMore.delegate = self
         longPressedGestureMore.delaysTouchesBegan = true
-        buttonMore.addGestureRecognizer(longPressedGestureMore)        
+        buttonMore.addGestureRecognizer(longPressedGestureMore)
     }
-    
+
     override func prepareForReuse() {
         super.prepareForReuse()
         imageItem.backgroundColor = nil
     }
-    
+
     @IBAction func touchUpInsideMore(_ sender: Any) {
         delegate?.tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: imageItem.image, sender: sender)
     }
-    
+
     @objc func longPressInsideMore(gestureRecognizer: UILongPressGestureRecognizer) {
         delegate?.longPressMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, gestureRecognizer: gestureRecognizer)
     }
-    
+
     @objc func longPress(gestureRecognizer: UILongPressGestureRecognizer) {
         delegate?.longPressGridItem(with: objectId, gestureRecognizer: gestureRecognizer)
     }
-    
+
     func setButtonMore(named: String, image: UIImage) {
         namedButtonMore = named
         buttonMore.setImage(image, for: .normal)
     }
-    
+
     func hideButtonMore(_ status: Bool) {
         buttonMore.isHidden = status
     }
-    
+
     func selectMode(_ status: Bool) {
         if status {
             imageSelect.isHidden = false
@@ -129,7 +129,7 @@ class NCGridCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProto
             imageVisualEffect.isHidden = true
         }
     }
-    
+
     func selected(_ status: Bool) {
         if status {
             if traitCollection.userInterfaceStyle == .dark {
@@ -148,7 +148,7 @@ class NCGridCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProto
     }
 }
 
-protocol NCGridCellDelegate {
+protocol NCGridCellDelegate: AnyObject {
     func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any)
     func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer)
     func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer)
@@ -164,7 +164,7 @@ extension NCGridCellDelegate {
 // MARK: - Grid Layout
 
 class NCGridLayout: UICollectionViewFlowLayout {
-    
+
     var heightLabelPlusButton: CGFloat = 45
     var marginLeftRight: CGFloat = 6
     var itemForLine: CGFloat = 3
@@ -174,36 +174,36 @@ class NCGridLayout: UICollectionViewFlowLayout {
 
     override init() {
         super.init()
-        
+
         sectionHeadersPinToVisibleBounds = false
-        
+
         minimumInteritemSpacing = 1
         minimumLineSpacing = marginLeftRight
-        
+
         self.scrollDirection = .vertical
-        self.sectionInset = UIEdgeInsets(top: 10, left: marginLeftRight, bottom: 0, right:  marginLeftRight)
+        self.sectionInset = UIEdgeInsets(top: 10, left: marginLeftRight, bottom: 0, right: marginLeftRight)
     }
-    
+
     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
-    
+
     override var itemSize: CGSize {
         get {
             if let collectionView = collectionView {
-                
+
                 if collectionView.frame.width < 400 {
                     itemForLine = 3
                 } else {
                     itemForLine = collectionView.frame.width / itemWidthDefault
                 }
-                
+
                 let itemWidth: CGFloat = (collectionView.frame.width - marginLeftRight * 2 - marginLeftRight * (itemForLine - 1)) / itemForLine
                 let itemHeight: CGFloat = itemWidth + heightLabelPlusButton
-                
+
                 return CGSize(width: itemWidth, height: itemHeight)
             }
-            
+
             // Default fallback
             return CGSize(width: itemWidthDefault, height: itemWidthDefault)
         }
@@ -211,7 +211,7 @@ class NCGridLayout: UICollectionViewFlowLayout {
             super.itemSize = newValue
         }
     }
-    
+
     override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
         return proposedContentOffset
     }

+ 28 - 28
iOSClient/Main/Collection Common/NCListCell.swift

@@ -24,7 +24,7 @@
 import UIKit
 
 class NCListCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProtocol {
-    
+
     @IBOutlet weak var imageItem: UIImageView!
     @IBOutlet weak var imageItemLeftConstraint: NSLayoutConstraint!
     @IBOutlet weak var imageSelect: UIImageView!
@@ -44,7 +44,7 @@ class NCListCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProto
     private var objectId = ""
     private var user = ""
 
-    var delegate: NCListCellDelegate?
+    weak var delegate: NCListCellDelegate?
     var namedButtonMore = ""
 
     var fileAvatarImageView: UIImageView? {
@@ -60,7 +60,7 @@ class NCListCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProto
             objectId = newValue ?? ""
         }
     }
-    var filePreviewImageView : UIImageView? {
+    var filePreviewImageView: UIImageView? {
         get {
             return imageItem
         }
@@ -73,13 +73,13 @@ class NCListCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProto
             user = newValue ?? ""
         }
     }
-    
+
     override func awakeFromNib() {
         super.awakeFromNib()
-               
+
         imageItem.layer.cornerRadius = 6
         imageItem.layer.masksToBounds = true
-        
+
         progressView.tintColor = NCBrandColor.shared.brandElement
         progressView.transform = CGAffineTransform(scaleX: 1.0, y: 0.5)
         progressView.trackTintColor = .clear
@@ -89,53 +89,53 @@ class NCListCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProto
         longPressedGesture.delegate = self
         longPressedGesture.delaysTouchesBegan = true
         self.addGestureRecognizer(longPressedGesture)
-        
+
         let longPressedGestureMore = UILongPressGestureRecognizer(target: self, action: #selector(longPressInsideMore(gestureRecognizer:)))
         longPressedGestureMore.minimumPressDuration = 0.5
         longPressedGestureMore.delegate = self
         longPressedGestureMore.delaysTouchesBegan = true
         buttonMore.addGestureRecognizer(longPressedGestureMore)
-        
+
         separator.backgroundColor = NCBrandColor.shared.separator
         separatorHeightConstraint.constant = 0.5
     }
-    
+
     override func prepareForReuse() {
         super.prepareForReuse()
         imageItem.backgroundColor = nil
     }
-    
+
     @IBAction func touchUpInsideShare(_ sender: Any) {
         delegate?.tapShareListItem(with: objectId, sender: sender)
     }
-    
+
     @IBAction func touchUpInsideMore(_ sender: Any) {
         delegate?.tapMoreListItem(with: objectId, namedButtonMore: namedButtonMore, image: imageItem.image, sender: sender)
     }
-    
+
     @objc func longPressInsideMore(gestureRecognizer: UILongPressGestureRecognizer) {
         delegate?.longPressMoreListItem(with: objectId, namedButtonMore: namedButtonMore, gestureRecognizer: gestureRecognizer)
     }
-    
+
     @objc func longPress(gestureRecognizer: UILongPressGestureRecognizer) {
         delegate?.longPressListItem(with: objectId, gestureRecognizer: gestureRecognizer)
     }
-    
+
     func setButtonMore(named: String, image: UIImage) {
         namedButtonMore = named
         imageMore.image = image
     }
-    
+
     func hideButtonMore(_ status: Bool) {
         imageMore.isHidden = status
         buttonMore.isHidden = status
     }
-    
+
     func hideButtonShare(_ status: Bool) {
         imageShared.isHidden = status
         buttonShared.isHidden = status
     }
-    
+
     func selectMode(_ status: Bool) {
         if status {
             imageItemLeftConstraint.constant = 45
@@ -146,7 +146,7 @@ class NCListCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProto
             backgroundView = nil
         }
     }
-    
+
     func selected(_ status: Bool) {
         if status {
             var blurEffect: UIVisualEffect?
@@ -173,7 +173,7 @@ class NCListCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProto
     }
 }
 
-protocol NCListCellDelegate {
+protocol NCListCellDelegate: AnyObject {
     func tapShareListItem(with objectId: String, sender: Any)
     func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any)
     func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer)
@@ -191,34 +191,34 @@ extension NCListCellDelegate {
 // MARK: - List Layout
 
 class NCListLayout: UICollectionViewFlowLayout {
-    
+
     var itemHeight: CGFloat = 60
-    
+
     // MARK: - View Life Cycle
 
     override init() {
         super.init()
-        
+
         sectionHeadersPinToVisibleBounds = false
-        
+
         minimumInteritemSpacing = 0
         minimumLineSpacing = 1
-        
+
         self.scrollDirection = .vertical
         self.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
     }
-    
+
     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
-    
+
     override var itemSize: CGSize {
         get {
             if let collectionView = collectionView {
                 let itemWidth: CGFloat = collectionView.frame.width
                 return CGSize(width: itemWidth, height: self.itemHeight)
             }
-            
+
             // Default fallback
             return CGSize(width: 100, height: 100)
         }
@@ -226,7 +226,7 @@ class NCListLayout: UICollectionViewFlowLayout {
             super.itemSize = newValue
         }
     }
-    
+
     override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
         return proposedContentOffset
     }

+ 163 - 167
iOSClient/Main/Create cloud/NCCreateFormUploadAssets.swift

@@ -24,32 +24,34 @@
 import UIKit
 import Queuer
 import NCCommunication
+import XLForm
+import Photos
 
-protocol createFormUploadAssetsDelegate {
+protocol createFormUploadAssetsDelegate: AnyObject {
     func dismissFormUploadAssets()
 }
 
 class NCCreateFormUploadAssets: XLFormViewController, NCSelectDelegate {
-    
+
     var serverUrl: String = ""
     var titleServerUrl: String?
     var assets: [PHAsset] = []
     var cryptated: Bool = false
     var session: String = ""
-    var delegate: createFormUploadAssetsDelegate?
+    weak var delegate: createFormUploadAssetsDelegate?
     let requestOptions = PHImageRequestOptions()
     var imagePreview: UIImage?
-    let targetSizeImagePreview = CGSize(width:100, height: 100)
+    let targetSizeImagePreview = CGSize(width: 100, height: 100)
     let appDelegate = UIApplication.shared.delegate as! AppDelegate
-    
+
     var cellBackgoundColor = NCBrandColor.shared.secondarySystemGroupedBackground
-        
+
     // MARK: - View Life Cycle
 
     convenience init(serverUrl: String, assets: [PHAsset], cryptated: Bool, session: String, delegate: createFormUploadAssetsDelegate?) {
-        
+
         self.init()
-        
+
         if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account) {
             titleServerUrl = "/"
         } else {
@@ -59,80 +61,79 @@ class NCCreateFormUploadAssets: XLFormViewController, NCSelectDelegate {
                 } else { titleServerUrl = (serverUrl as NSString).lastPathComponent }
             } else { titleServerUrl = (serverUrl as NSString).lastPathComponent }
         }
-        
+
         self.serverUrl = serverUrl
         self.assets = assets
         self.cryptated = cryptated
         self.session = session
         self.delegate = delegate
-        
+
         requestOptions.resizeMode = PHImageRequestOptionsResizeMode.exact
         requestOptions.deliveryMode = PHImageRequestOptionsDeliveryMode.highQualityFormat
         requestOptions.isSynchronous = true
     }
-    
+
     override func viewDidLoad() {
-        
+
         super.viewDidLoad()
-        
+
         self.title = NSLocalizedString("_upload_photos_videos_", comment: "")
-        
+
         self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(cancel))
         self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
-        
+
         self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
-        
+
         if assets.count == 1 && assets[0].mediaType == PHAssetMediaType.image {
-            PHImageManager.default().requestImage(for: assets[0], targetSize: targetSizeImagePreview, contentMode: PHImageContentMode.aspectFill, options: requestOptions, resultHandler: { (image, info) in
+            PHImageManager.default().requestImage(for: assets[0], targetSize: targetSizeImagePreview, contentMode: PHImageContentMode.aspectFill, options: requestOptions, resultHandler: { image, _ in
                 self.imagePreview = image
             })
         }
-        
+
         changeTheming()
-        
+
         initializeForm()
         reloadForm()
     }
-    
-    override func viewWillDisappear(_ animated: Bool)
-    {
+
+    override func viewWillDisappear(_ animated: Bool) {
         super.viewWillDisappear(animated)
-        
+
         self.delegate?.dismissFormUploadAssets()
     }
-    
+
     override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
         super.traitCollectionDidChange(previousTraitCollection)
-        
+
         changeTheming()
     }
-    
+
     // MARK: - Theming
-    
+
     func changeTheming() {
-        
+
         view.backgroundColor = NCBrandColor.shared.systemGroupedBackground
         tableView.backgroundColor = NCBrandColor.shared.systemGroupedBackground
         cellBackgoundColor = NCBrandColor.shared.secondarySystemGroupedBackground
-        
+
         tableView.reloadData()
     }
-    
-    //MARK: XLForm
-    
+
+    // MARK: XLForm
+
     func initializeForm() {
-        
-        let form : XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor
+
+        let form: XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor
         form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
-        
-        var section : XLFormSectionDescriptor
-        var row : XLFormRowDescriptor
-        
+
+        var section: XLFormSectionDescriptor
+        var row: XLFormRowDescriptor
+
         // Section: Destination Folder
-        
+
         section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: ""))
         form.addFormSection(section)
-        
+
         row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: self.titleServerUrl)
         row.action.formSelector = #selector(changeDestinationFolder(_:))
         row.cellConfig["backgroundColor"] = cellBackgoundColor
@@ -141,9 +142,9 @@ class NCCreateFormUploadAssets: XLFormViewController, NCSelectDelegate {
         row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
         row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
-        
+
         section.addFormRow(row)
-        
+
         // User folder Autoupload
         row = XLFormRowDescriptor(tag: "useFolderAutoUpload", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_use_folder_auto_upload_", comment: ""))
         row.value = 0
@@ -151,9 +152,9 @@ class NCCreateFormUploadAssets: XLFormViewController, NCSelectDelegate {
 
         row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
-        
+
         section.addFormRow(row)
-        
+
         // Use Sub folder
         row = XLFormRowDescriptor(tag: "useSubFolder", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_autoupload_create_subfolder_", comment: ""))
         let activeAccount = NCManageDatabase.shared.getActiveAccount()
@@ -163,30 +164,30 @@ class NCCreateFormUploadAssets: XLFormViewController, NCSelectDelegate {
             row.value = 0
         }
         row.hidden = "$\("useFolderAutoUpload") == 0"
-        
+
         row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
-        
+
         section.addFormRow(row)
 
         // Section Mode filename
-        
+
         section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_mode_filename_", comment: ""))
         form.addFormSection(section)
-        
+
         // Maintain the original fileName
-        
+
         row = XLFormRowDescriptor(tag: "maintainOriginalFileName", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_maintain_original_filename_", comment: ""))
         row.value = CCUtility.getOriginalFileName(NCGlobal.shared.keyFileNameOriginal)
         row.cellConfig["backgroundColor"] = cellBackgoundColor
 
         row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
-        
+
         section.addFormRow(row)
-        
+
         // Add File Name Type
-        
+
         row = XLFormRowDescriptor(tag: "addFileNameType", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_add_filenametype_", comment: ""))
         row.value = CCUtility.getFileNameType(NCGlobal.shared.keyFileNameType)
         row.hidden = "$\("maintainOriginalFileName") == 1"
@@ -194,16 +195,16 @@ class NCCreateFormUploadAssets: XLFormViewController, NCSelectDelegate {
 
         row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
-        
+
         section.addFormRow(row)
-        
+
         // Section: Rename File Name
-        
+
         section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_filename_", comment: ""))
         form.addFormSection(section)
-        
+
         row = XLFormRowDescriptor(tag: "maskFileName", rowType: XLFormRowDescriptorTypeText, title: (NSLocalizedString("_filename_", comment: "")))
-        let fileNameMask : String = CCUtility.getFileNameMask(NCGlobal.shared.keyFileNameMask)
+        let fileNameMask: String = CCUtility.getFileNameMask(NCGlobal.shared.keyFileNameMask)
         if fileNameMask.count > 0 {
             row.value = fileNameMask
         }
@@ -212,15 +213,15 @@ class NCCreateFormUploadAssets: XLFormViewController, NCSelectDelegate {
 
         row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
-        
+
         row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
         row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textField.textColor"] = NCBrandColor.shared.label
 
         section.addFormRow(row)
-        
+
         // Section: Preview File Name
-        
+
         row = XLFormRowDescriptor(tag: "previewFileName", rowType: XLFormRowDescriptorTypeTextView, title: "")
         row.height = 180
         row.disabled = true
@@ -231,114 +232,109 @@ class NCCreateFormUploadAssets: XLFormViewController, NCSelectDelegate {
         row.cellConfig["textView.textColor"] = NCBrandColor.shared.label
 
         section.addFormRow(row)
-        
+
         self.form = form
     }
-    
+
     override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
-        
+
         super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
-        
+
         if formRow.tag == "useFolderAutoUpload" {
-            
+
             if (formRow.value! as AnyObject).boolValue  == true {
-                
-                let buttonDestinationFolder : XLFormRowDescriptor  = self.form.formRow(withTag: "ButtonDestinationFolder")!
+
+                let buttonDestinationFolder: XLFormRowDescriptor  = self.form.formRow(withTag: "ButtonDestinationFolder")!
                 buttonDestinationFolder.hidden = true
-                
-            } else{
-                
-                let buttonDestinationFolder : XLFormRowDescriptor  = self.form.formRow(withTag: "ButtonDestinationFolder")!
+
+            } else {
+
+                let buttonDestinationFolder: XLFormRowDescriptor  = self.form.formRow(withTag: "ButtonDestinationFolder")!
                 buttonDestinationFolder.hidden = false
             }
-        }
-        else if formRow.tag == "useSubFolder" {
-            
+        } else if formRow.tag == "useSubFolder" {
+
             if (formRow.value! as AnyObject).boolValue  == true {
-                
-            } else{
-                
+
+            } else {
+
             }
-        }
-        else if formRow.tag == "maintainOriginalFileName" {
+        } else if formRow.tag == "maintainOriginalFileName" {
             CCUtility.setOriginalFileName((formRow.value! as AnyObject).boolValue, key: NCGlobal.shared.keyFileNameOriginal)
             self.reloadForm()
-        }
-        else if formRow.tag == "addFileNameType" {
+        } else if formRow.tag == "addFileNameType" {
             CCUtility.setFileNameType((formRow.value! as AnyObject).boolValue, key: NCGlobal.shared.keyFileNameType)
             self.reloadForm()
-        }
-        else if formRow.tag == "maskFileName" {
-            
+        } else if formRow.tag == "maskFileName" {
+
             let fileName = formRow.value as? String
-            
+
             self.form.delegate = nil
-            
+
             if let fileName = fileName {
                 formRow.value = CCUtility.removeForbiddenCharactersServer(fileName)
             }
-            
+
             self.form.delegate = self
-            
-            let previewFileName : XLFormRowDescriptor  = self.form.formRow(withTag: "previewFileName")!
+
+            let previewFileName: XLFormRowDescriptor  = self.form.formRow(withTag: "previewFileName")!
             previewFileName.value = self.previewFileName(valueRename: formRow.value as? String)
-            
+
             // reload cell
             if fileName != nil {
-                
+
                 if newValue as! String != formRow.value as! String {
-                    
+
                     self.reloadFormRow(formRow)
-                    
+
                     NCContentPresenter.shared.messageNotification("_info_", description: "_forbidden_characters_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorCharactersForbidden)
                 }
             }
-            
+
             self.reloadFormRow(previewFileName)
         }
     }
-    
+
     func reloadForm() {
-        
+
         self.form.delegate = nil
-        
-        let buttonDestinationFolder : XLFormRowDescriptor  = self.form.formRow(withTag: "ButtonDestinationFolder")!
+
+        let buttonDestinationFolder: XLFormRowDescriptor  = self.form.formRow(withTag: "ButtonDestinationFolder")!
         buttonDestinationFolder.title = self.titleServerUrl
-        
-        let maskFileName : XLFormRowDescriptor = self.form.formRow(withTag: "maskFileName")!
-        let previewFileName : XLFormRowDescriptor  = self.form.formRow(withTag: "previewFileName")!
+
+        let maskFileName: XLFormRowDescriptor = self.form.formRow(withTag: "maskFileName")!
+        let previewFileName: XLFormRowDescriptor  = self.form.formRow(withTag: "previewFileName")!
         previewFileName.value = self.previewFileName(valueRename: maskFileName.value as? String)
-        
+
         self.tableView.reloadData()
         self.form.delegate = self
     }
-    
+
     // MARK: - Action
-         
+
     func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
-        
+
         if serverUrl != nil {
-            
+
             self.serverUrl = serverUrl!
-            
+
             if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account) {
                 self.titleServerUrl = "/"
             } else {
-                if let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account
-                    , self.serverUrl)) {
+                if let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, self.serverUrl)) {
                     if let metadata = NCManageDatabase.shared.getMetadataFromOcId(tableDirectory.ocId) {
                         titleServerUrl = metadata.fileNameView
                     } else { titleServerUrl = (self.serverUrl as NSString).lastPathComponent }
-                } else { titleServerUrl = (self.serverUrl as NSString).lastPathComponent }                
+                } else { titleServerUrl = (self.serverUrl as NSString).lastPathComponent }
             }
-            
+
             // Update
-            let row : XLFormRowDescriptor  = self.form.formRow(withTag: "ButtonDestinationFolder")!
+            let row: XLFormRowDescriptor  = self.form.formRow(withTag: "ButtonDestinationFolder")!
             row.title = self.titleServerUrl
             self.updateFormRow(row)
         }
     }
-    
+
     /*
     func save() {
         
@@ -358,11 +354,11 @@ class NCCreateFormUploadAssets: XLFormViewController, NCSelectDelegate {
         })
     }
     */
-    
+
     @objc func save() {
-         
+
         DispatchQueue.global().async {
-        
+
             let useFolderPhotoRow: XLFormRowDescriptor  = self.form.formRow(withTag: "useFolderAutoUpload")!
             let useSubFolderRow: XLFormRowDescriptor  = self.form.formRow(withTag: "useSubFolder")!
             var useSubFolder: Bool = false
@@ -374,7 +370,7 @@ class NCCreateFormUploadAssets: XLFormViewController, NCSelectDelegate {
                 self.serverUrl = NCManageDatabase.shared.getAccountAutoUploadPath(urlBase: self.appDelegate.urlBase, account: self.appDelegate.account)
                 useSubFolder = (useSubFolderRow.value! as AnyObject).boolValue
             }
-            
+
             let autoUploadPath = NCManageDatabase.shared.getAccountAutoUploadPath(urlBase: self.appDelegate.urlBase, account: self.appDelegate.account)
             if autoUploadPath == self.serverUrl {
                 if !NCNetworking.shared.createFolder(assets: self.assets, selector: NCGlobal.shared.selectorUploadFile, useSubFolder: useSubFolder, account: self.appDelegate.account, urlBase: self.appDelegate.urlBase) {
@@ -384,59 +380,59 @@ class NCCreateFormUploadAssets: XLFormViewController, NCSelectDelegate {
             }
 
             for asset in self.assets {
-                    
+
                 var serverUrl = self.serverUrl
                 var livePhoto: Bool = false
                 let fileName = CCUtility.createFileName(asset.value(forKey: "filename") as? String, fileDate: asset.creationDate, fileType: asset.mediaType, keyFileName: NCGlobal.shared.keyFileNameMask, keyFileNameType: NCGlobal.shared.keyFileNameType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal, forcedNewFileName: false)!
                 let assetDate = asset.creationDate ?? Date()
                 let dateFormatter = DateFormatter()
-                
+
                 // Detect LivePhoto Upload
                 if asset.mediaSubtypes.contains(.photoLive) && CCUtility.getLivePhoto() {
                     livePhoto = true
-                } 
-                
+                }
+
                 // Create serverUrl if use sub folder
                 if useSubFolder {
-                    
+
                     dateFormatter.dateFormat = "yyyy"
                     let yearString = dateFormatter.string(from: assetDate)
-                   
+
                     dateFormatter.dateFormat = "MM"
                     let monthString = dateFormatter.string(from: assetDate)
-                    
+
                     serverUrl = autoUploadPath + "/" + yearString + "/" + monthString
                 }
-                
+
                 // Check if is in upload
                 let isRecordInSessions = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileName == %@ AND session != ''", self.appDelegate.account, serverUrl, fileName), sorted: "fileName", ascending: false)
                 if isRecordInSessions.count > 0 {
                     continue
                 }
-                
+
                 let metadataForUpload = NCManageDatabase.shared.createMetadata(account: self.appDelegate.account, user: self.appDelegate.user, userId: self.appDelegate.userId, fileName: fileName, fileNameView: fileName, ocId: NSUUID().uuidString, serverUrl: serverUrl, urlBase: self.appDelegate.urlBase, url: "", contentType: "", livePhoto: livePhoto)
-                
+
                 metadataForUpload.assetLocalIdentifier = asset.localIdentifier
                 metadataForUpload.session = self.session
                 metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile
                 metadataForUpload.size = NCUtilityFileSystem.shared.getFileSize(asset: asset)
                 metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
-                
+
                 if livePhoto {
-                    
+
                     let fileNameMove = (fileName as NSString).deletingPathExtension + ".mov"
                     let ocId = NSUUID().uuidString
                     let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameMove)!
-                    
+
                     let semaphore = Semaphore()
-                    CCUtility.extractLivePhotoAsset(asset, filePath: filePath) { (url) in
+                    CCUtility.extractLivePhotoAsset(asset, filePath: filePath) { url in
                         if let url = url {
                             let fileSize = NCUtilityFileSystem.shared.getFileSize(filePath: url.path)
-                            let metadataMOVForUpload = NCManageDatabase.shared.createMetadata(account: self.appDelegate.account, user: self.appDelegate.user, userId: self.appDelegate.userId, fileName: fileNameMove, fileNameView: fileNameMove, ocId:ocId, serverUrl: serverUrl, urlBase: self.appDelegate.urlBase, url: "", contentType: "", livePhoto: livePhoto)
+                            let metadataMOVForUpload = NCManageDatabase.shared.createMetadata(account: self.appDelegate.account, user: self.appDelegate.user, userId: self.appDelegate.userId, fileName: fileNameMove, fileNameView: fileNameMove, ocId: ocId, serverUrl: serverUrl, urlBase: self.appDelegate.urlBase, url: "", contentType: "", livePhoto: livePhoto)
 
                             metadataForUpload.livePhoto = true
                             metadataMOVForUpload.livePhoto = true
-                            
+
                             metadataMOVForUpload.session = self.session
                             metadataMOVForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile
                             metadataMOVForUpload.size = fileSize
@@ -449,94 +445,94 @@ class NCCreateFormUploadAssets: XLFormViewController, NCSelectDelegate {
                     }
                     semaphore.wait()
                 }
-                
+
                 if NCManageDatabase.shared.getMetadataConflict(account: self.appDelegate.account, serverUrl: serverUrl, fileName: fileName) != nil {
                     metadatasUploadInConflict.append(metadataForUpload)
                 } else {
                     metadatasNOConflict.append(metadataForUpload)
                 }
             }
-            
+
             // Verify if file(s) exists
             if metadatasUploadInConflict.count > 0 {
-                
+
                 DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
-                    if let conflict = UIStoryboard.init(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict {
-                        
+                    if let conflict = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict {
+
                         conflict.serverUrl = self.serverUrl
                         conflict.metadatasNOConflict = metadatasNOConflict
                         conflict.metadatasMOV = metadatasMOV
                         conflict.metadatasUploadInConflict = metadatasUploadInConflict
-                    
+
                         self.appDelegate.window?.rootViewController?.present(conflict, animated: true, completion: nil)
                     }
                 }
-                
+
             } else {
-                
+
                 self.appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: metadatasNOConflict)
-                self.appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: metadatasMOV)                
+                self.appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: metadatasMOV)
             }
-        
+
             DispatchQueue.main.async {self.dismiss(animated: true, completion: nil)  }
         }
     }
-    
+
     @objc func cancel() {
-        
+
         self.dismiss(animated: true, completion: nil)
     }
-    
+
     // MARK: - Utility
-    
-    func previewFileName(valueRename : String?) -> String {
-        
+
+    func previewFileName(valueRename: String?) -> String {
+
         var returnString: String = ""
         let asset = assets[0]
-        
-        if (CCUtility.getOriginalFileName(NCGlobal.shared.keyFileNameOriginal)) {
-            
+
+        if CCUtility.getOriginalFileName(NCGlobal.shared.keyFileNameOriginal) {
+
             return (NSLocalizedString("_filename_", comment: "") + ": " + (asset.value(forKey: "filename") as! String))
-            
+
         } else if let valueRename = valueRename {
-            
+
             let valueRenameTrimming = valueRename.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
-            
+
             if valueRenameTrimming.count > 0 {
-                
+
                 self.form.delegate = nil
                 CCUtility.setFileNameMask(valueRename, key: NCGlobal.shared.keyFileNameMask)
                 self.form.delegate = self
-                
+
                 returnString = CCUtility.createFileName(asset.value(forKey: "filename") as! String?, fileDate: asset.creationDate, fileType: asset.mediaType, keyFileName: NCGlobal.shared.keyFileNameMask, keyFileNameType: NCGlobal.shared.keyFileNameType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal, forcedNewFileName: false)
-                
+
             } else {
-                
+
                 CCUtility.setFileNameMask("", key: NCGlobal.shared.keyFileNameMask)
                 returnString = CCUtility.createFileName(asset.value(forKey: "filename") as! String?, fileDate: asset.creationDate, fileType: asset.mediaType, keyFileName: nil, keyFileNameType: NCGlobal.shared.keyFileNameType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal, forcedNewFileName: false)
             }
-            
+
         } else {
-            
+
             CCUtility.setFileNameMask("", key: NCGlobal.shared.keyFileNameMask)
             returnString = CCUtility.createFileName(asset.value(forKey: "filename") as! String?, fileDate: asset.creationDate, fileType: asset.mediaType, keyFileName: nil, keyFileNameType: NCGlobal.shared.keyFileNameType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal, forcedNewFileName: false)
         }
-        
+
         return String(format: NSLocalizedString("_preview_filename_", comment: ""), "MM, MMM, DD, YY, YYYY, HH, hh, mm, ss, ampm") + ":" + "\n\n" + returnString
     }
-    
+
     @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
-        
+
         self.deselectFormRow(sender)
-        
+
         let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
         let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
         let viewController = navigationController.topViewController as! NCSelect
-        
+
         viewController.delegate = self
         viewController.typeOfCommandView = .selectCreateFolder
         viewController.includeDirectoryE2EEncryption = true
-        
+
         self.present(navigationController, animated: true, completion: nil)
     }
 }

+ 115 - 116
iOSClient/Main/Create cloud/NCCreateFormUploadConflict.swift

@@ -49,7 +49,7 @@ extension NCCreateFormUploadConflictDelegate {
     @IBOutlet weak var viewButton: UIView!
     @IBOutlet weak var buttonCancel: UIButton!
     @IBOutlet weak var buttonContinue: UIButton!
-        
+
     @objc var metadatasNOConflict: [tableMetadata]
     @objc var metadatasUploadInConflict: [tableMetadata]
     @objc var metadatasMOV: [tableMetadata]
@@ -57,7 +57,7 @@ extension NCCreateFormUploadConflictDelegate {
     @objc weak var delegate: NCCreateFormUploadConflictDelegate?
     @objc var alwaysNewFileNameNumber: Bool = false
     @objc var textLabelDetailNewFile: String?
-    
+
     let appDelegate = UIApplication.shared.delegate as! AppDelegate
     var metadatasConflictNewFiles: [String] = []
     var metadatasConflictAlreadyExistingFiles: [String] = []
@@ -72,17 +72,17 @@ extension NCCreateFormUploadConflictDelegate {
         self.metadatasUploadInConflict = []
         super.init(coder: aDecoder)
     }
-    
+
     override func viewDidLoad() {
         super.viewDidLoad()
-        
+
         tableView.dataSource = self
         tableView.delegate = self
         tableView.allowsSelection = false
         tableView.tableFooterView = UIView()
-        
-        tableView.register(UINib.init(nibName: "NCCreateFormUploadConflictCell", bundle: nil), forCellReuseIdentifier: "Cell")
-        
+
+        tableView.register(UINib(nibName: "NCCreateFormUploadConflictCell", bundle: nil), forCellReuseIdentifier: "Cell")
+
         if metadatasUploadInConflict.count == 1 {
             labelTitle.text = String(metadatasUploadInConflict.count) + " " + NSLocalizedString("_file_conflict_num_", comment: "")
             labelSubTitle.text = NSLocalizedString("_file_conflict_desc_", comment: "")
@@ -94,14 +94,14 @@ extension NCCreateFormUploadConflictDelegate {
             labelNewFiles.text = NSLocalizedString("_file_conflict_new_", comment: "")
             labelAlreadyExistingFiles.text = NSLocalizedString("_file_conflict_exists_", comment: "")
         }
-        
+
         switchNewFiles.isOn = false
         switchAlreadyExistingFiles.isOn = false
-        
+
         buttonCancel.layer.cornerRadius = 20
         buttonCancel.layer.masksToBounds = true
         buttonCancel.setTitle(NSLocalizedString("_cancel_", comment: ""), for: .normal)
-        
+
         buttonContinue.layer.cornerRadius = 20
         buttonContinue.layer.masksToBounds = true
         buttonContinue.setTitle(NSLocalizedString("_continue_", comment: ""), for: .normal)
@@ -113,34 +113,34 @@ extension NCCreateFormUploadConflictDelegate {
         blurView.frame = view.bounds
         blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
         view.addSubview(blurView)
-        
+
         changeTheming()
 
         DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
             self.conflictDialog(fileCount: self.metadatasUploadInConflict.count)
         }
     }
-    
+
     override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
         super.traitCollectionDidChange(previousTraitCollection)
-        
+
         changeTheming()
     }
-    
+
     // MARK: - Theming
-    
-    func changeTheming(){
-        
+
+    func changeTheming() {
+
         view.backgroundColor = NCBrandColor.shared.systemGroupedBackground
         tableView.backgroundColor = NCBrandColor.shared.systemGroupedBackground
         viewSwitch.backgroundColor = NCBrandColor.shared.systemGroupedBackground
         viewButton.backgroundColor = NCBrandColor.shared.systemGroupedBackground
     }
-    
+
     // MARK: - ConflictDialog
-    
+
     func conflictDialog(fileCount: Int) {
-        
+
         var tile = ""
         var titleReplace = ""
         var titleKeep = ""
@@ -154,41 +154,41 @@ extension NCCreateFormUploadConflictDelegate {
             titleReplace = NSLocalizedString("_replace_all_action_title_", comment: "")
             titleKeep = NSLocalizedString("_keep_both_for_all_action_title_", comment: "")
         }
-        
+
         let conflictAlert = UIAlertController(title: tile, message: "", preferredStyle: .alert)
 
         // REPLACE
         conflictAlert.addAction(UIAlertAction(title: titleReplace, style: .default, handler: { action in
-                        
+
             for metadata in self.metadatasUploadInConflict {
                 self.metadatasNOConflict.append(metadata)
             }
-            
+
             self.buttonContinueTouch(action)
         }))
-        
+
         // KEEP BOTH
         conflictAlert.addAction(UIAlertAction(title: titleKeep, style: .default, handler: { action in
-            
+
             for metadata in self.metadatasUploadInConflict {
                 self.metadatasConflictNewFiles.append(metadata.ocId)
                 self.metadatasConflictAlreadyExistingFiles.append(metadata.ocId)
             }
-            
+
             self.buttonContinueTouch(action)
         }))
-        
-        conflictAlert.addAction(UIAlertAction(title: NSLocalizedString("_cancel_keep_existing_action_title_", comment: ""), style: .cancel, handler: { (_) in
+
+        conflictAlert.addAction(UIAlertAction(title: NSLocalizedString("_cancel_keep_existing_action_title_", comment: ""), style: .cancel, handler: { _ in
             self.dismiss(animated: true, completion: nil)
         }))
-        
-        conflictAlert.addAction(UIAlertAction(title: NSLocalizedString("_more_action_title_", comment: ""), style: .default, handler: { (_) in
+
+        conflictAlert.addAction(UIAlertAction(title: NSLocalizedString("_more_action_title_", comment: ""), style: .default, handler: { _ in
             self.blurView.removeFromSuperview()
         }))
-        
+
         self.present(conflictAlert, animated: true, completion: nil)
     }
-    
+
     // MARK: - Action
 
     @IBAction func valueChangedSwitchNewFiles(_ sender: Any) {
@@ -199,56 +199,56 @@ extension NCCreateFormUploadConflictDelegate {
                 metadatasConflictNewFiles.append(metadata.ocId)
             }
         }
-        
+
        verifySwith()
     }
-    
+
     @IBAction func valueChangedSwitchAlreadyExistingFiles(_ sender: Any) {
         metadatasConflictAlreadyExistingFiles.removeAll()
-        
+
         if switchAlreadyExistingFiles.isOn {
             for metadata in metadatasUploadInConflict {
                 metadatasConflictAlreadyExistingFiles.append(metadata.ocId)
             }
         }
-        
+
         verifySwith()
     }
-    
+
     func verifySwith() {
-        
+
         if alwaysNewFileNameNumber && switchNewFiles.isOn {
             metadatasConflictNewFiles.removeAll()
             metadatasConflictAlreadyExistingFiles.removeAll()
-            
+
             for metadata in metadatasUploadInConflict {
                 metadatasConflictNewFiles.append(metadata.ocId)
             }
             for metadata in metadatasUploadInConflict {
                 metadatasConflictAlreadyExistingFiles.append(metadata.ocId)
             }
-            
+
             switchAlreadyExistingFiles.isOn = true
             NCContentPresenter.shared.messageNotification("_info_", description: "_file_not_rewite_doc_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorInternalError)
         }
-        
+
         tableView.reloadData()
         canContinue()
     }
-        
+
     @IBAction func buttonCancelTouch(_ sender: Any) {
-        
+
         delegate?.dismissCreateFormUploadConflict(metadatas: nil)
         dismiss(animated: true)
     }
-    
+
     @IBAction func buttonContinueTouch(_ sender: Any) {
-        
+
         for metadata in metadatasUploadInConflict {
-            
+
             // keep both
             if metadatasConflictNewFiles.contains(metadata.ocId) && metadatasConflictAlreadyExistingFiles.contains(metadata.ocId) {
-            
+
                 let fileNameMOV = (metadata.fileNameView as NSString).deletingPathExtension + ".mov"
                 var fileName = metadata.fileNameView
                 let fileNameExtension = (fileName as NSString).pathExtension.lowercased()
@@ -258,44 +258,44 @@ extension NCCreateFormUploadConflictDelegate {
                 }
                 let oldPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
                 let newFileName = NCUtilityFileSystem.shared.createFileName(fileName, serverUrl: metadata.serverUrl, account: metadata.account)
-                
+
                 metadata.ocId = UUID().uuidString
                 metadata.fileName = newFileName
                 metadata.fileNameView = newFileName
-                
+
                 // This is not an asset - [file]
                 if metadata.assetLocalIdentifier == "" {
                     let newPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: newFileName)
                     CCUtility.moveFile(atPath: oldPath, toPath: newPath)
                 }
-                
+
                 metadatasNOConflict.append(metadata)
-                
+
                 // MOV (Live Photo)
                 if let metadataMOV = self.metadatasMOV.first(where: { $0.fileName == fileNameMOV }) {
-                    
+
                     let oldPath = CCUtility.getDirectoryProviderStorageOcId(metadataMOV.ocId, fileNameView: metadataMOV.fileNameView)
                     let newFileNameMOV = (newFileName as NSString).deletingPathExtension + ".mov"
-                    
+
                     metadataMOV.ocId = UUID().uuidString
                     metadataMOV.fileName = newFileNameMOV
                     metadataMOV.fileNameView = newFileNameMOV
-                    
+
                     let newPath = CCUtility.getDirectoryProviderStorageOcId(metadataMOV.ocId, fileNameView: newFileNameMOV)
                     CCUtility.moveFile(atPath: oldPath, toPath: newPath)
                 }
-                
+
             // overwrite
             } else if metadatasConflictNewFiles.contains(metadata.ocId) {
-                
+
                 metadatasNOConflict.append(metadata)
-            
+
             // remove (MOV)
             } else if metadatasConflictAlreadyExistingFiles.contains(metadata.ocId) {
-                
+
                 let fileNameMOV = (metadata.fileNameView as NSString).deletingPathExtension + ".mov"
                 var index = 0
-                
+
                 for metadataMOV in metadatasMOV {
                     if metadataMOV.fileNameView == fileNameMOV {
                         metadatasMOV.remove(at: index)
@@ -303,20 +303,20 @@ extension NCCreateFormUploadConflictDelegate {
                     }
                     index += 1
                 }
-                
+
             } else {
                 print("error")
             }
         }
-        
+
         metadatasNOConflict.append(contentsOf: metadatasMOV)
-        
+
         if delegate != nil {
             delegate?.dismissCreateFormUploadConflict(metadatas: metadatasNOConflict)
         } else {
             appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: metadatasNOConflict)
         }
-                
+
         dismiss(animated: true)
     }
 }
@@ -324,7 +324,7 @@ extension NCCreateFormUploadConflictDelegate {
 // MARK: - UITableViewDelegate
 
 extension NCCreateFormUploadConflict: UITableViewDelegate {
-    
+
     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
         if metadatasUploadInConflict.count == 1 {
             return 250
@@ -337,21 +337,21 @@ extension NCCreateFormUploadConflict: UITableViewDelegate {
 // MARK: - UITableViewDataSource
 
 extension NCCreateFormUploadConflict: UITableViewDataSource {
-    
+
     func numberOfSections(in tableView: UITableView) -> Int {
         return 1
     }
-    
+
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         return metadatasUploadInConflict.count
     }
-    
+
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
-        
+
         if let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? NCCreateFormUploadConflictCell {
-            
+
             cell.backgroundColor = tableView.backgroundColor
-            
+
             let metadataNewFile = metadatasUploadInConflict[indexPath.row]
 
             cell.ocId = metadataNewFile.ocId
@@ -361,50 +361,50 @@ extension NCCreateFormUploadConflict: UITableViewDataSource {
             cell.labelDetailNewFile.text = ""
 
             // -----> Already Existing File
-            
+
             guard let metadataAlreadyExists = NCManageDatabase.shared.getMetadataConflict(account: metadataNewFile.account, serverUrl: metadataNewFile.serverUrl, fileName: metadataNewFile.fileNameView) else { return UITableViewCell() }
             if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadataAlreadyExists.ocId, etag: metadataAlreadyExists.etag)) {
                 cell.imageAlreadyExistingFile.image =  UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadataAlreadyExists.ocId, etag: metadataAlreadyExists.etag))
             } else if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageOcId(metadataAlreadyExists.ocId, fileNameView: metadataAlreadyExists.fileNameView)) && metadataAlreadyExists.contentType == "application/pdf" {
-            
+
                 let url = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataAlreadyExists.ocId, fileNameView: metadataAlreadyExists.fileNameView))
                 if let image = NCUtility.shared.pdfThumbnail(url: url) {
                     cell.imageAlreadyExistingFile.image = image
                 } else {
-                    cell.imageAlreadyExistingFile.image = UIImage.init(named: metadataAlreadyExists.iconName)
+                    cell.imageAlreadyExistingFile.image = UIImage(named: metadataAlreadyExists.iconName)
                 }
-            
+
             } else {
                 if metadataAlreadyExists.iconName.count > 0 {
-                    cell.imageAlreadyExistingFile.image = UIImage.init(named: metadataAlreadyExists.iconName)
+                    cell.imageAlreadyExistingFile.image = UIImage(named: metadataAlreadyExists.iconName)
                 } else {
-                    cell.imageAlreadyExistingFile.image = UIImage.init(named: "file")
+                    cell.imageAlreadyExistingFile.image = UIImage(named: "file")
                 }
             }
             cell.labelDetailAlreadyExistingFile.text = CCUtility.dateDiff(metadataAlreadyExists.date as Date) + "\n" + CCUtility.transformedSize(metadataAlreadyExists.size)
-                
+
             if metadatasConflictAlreadyExistingFiles.contains(metadataNewFile.ocId) {
                 cell.switchAlreadyExistingFile.isOn = true
             } else {
                 cell.switchAlreadyExistingFile.isOn = false
             }
-            
+
             // -----> New File
-            
+
             if metadataNewFile.iconName.count > 0 {
-                cell.imageNewFile.image = UIImage.init(named: metadataNewFile.iconName)
+                cell.imageNewFile.image = UIImage(named: metadataNewFile.iconName)
             } else {
-                cell.imageNewFile.image = UIImage.init(named: "file")
+                cell.imageNewFile.image = UIImage(named: "file")
             }
             let filePathNewFile = CCUtility.getDirectoryProviderStorageOcId(metadataNewFile.ocId, fileNameView: metadataNewFile.fileNameView)!
             if metadataNewFile.assetLocalIdentifier.count > 0 {
-                
+
                 let result = PHAsset.fetchAssets(withLocalIdentifiers: [metadataNewFile.assetLocalIdentifier], options: nil)
                 let date = result.firstObject!.modificationDate
                 let mediaType = result.firstObject!.mediaType
-                
+
                 if let fileNamePath = self.fileNamesPath[metadataNewFile.fileNameView] {
-                    
+
                     do {
                         if mediaType == PHAssetMediaType.image {
                             let data = try Data(contentsOf: URL(fileURLWithPath: fileNamePath))
@@ -416,26 +416,26 @@ extension NCCreateFormUploadConflict: UITableViewDataSource {
                                 cell.imageNewFile.image = image
                             }
                         }
-                        
+
                         let fileDictionary = try FileManager.default.attributesOfItem(atPath: fileNamePath)
                         let fileSize = fileDictionary[FileAttributeKey.size] as! Int64
-                        
+
                         cell.labelDetailNewFile.text = CCUtility.dateDiff(date) + "\n" + CCUtility.transformedSize(fileSize)
-                        
+
                     } catch { print("Error: \(error)") }
-                    
+
                 } else {
-                    
-                    CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadataNewFile, notification: false) { (metadataNew, fileNamePath) in
-                       
+
+                    CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadataNewFile, notification: false) { metadataNew, fileNamePath in
+
                         if metadataNew != nil {
                             self.fileNamesPath[metadataNewFile.fileNameView] = fileNamePath!
-                            
+
                             do {
-                                
+
                                 let fileDictionary = try FileManager.default.attributesOfItem(atPath: fileNamePath!)
                                 let fileSize = fileDictionary[FileAttributeKey.size] as! Int64
-                                
+
                                 if mediaType == PHAssetMediaType.image {
                                     let data = try Data(contentsOf: URL(fileURLWithPath: fileNamePath!))
                                     if let image = UIImage(data: data) {
@@ -446,16 +446,16 @@ extension NCCreateFormUploadConflict: UITableViewDataSource {
                                         cell.imageNewFile.image = image
                                     }
                                 }
-                                
+
                                 cell.labelDetailNewFile.text = CCUtility.dateDiff(date) + "\n" + CCUtility.transformedSize(fileSize)
-                               
+
                             } catch { print("Error: \(error)") }
                         }
                     }
                 }
-                      
+
             } else if FileManager().fileExists(atPath: filePathNewFile) {
-                
+
                 do {
                     if metadataNewFile.classFile ==  NCCommunicationCommon.typeClassFile.image.rawValue {
                         let data = try Data(contentsOf: URL(fileURLWithPath: filePathNewFile))
@@ -463,39 +463,39 @@ extension NCCreateFormUploadConflict: UITableViewDataSource {
                             cell.imageNewFile.image = image
                         }
                     }
-                    
+
                     let fileDictionary = try FileManager.default.attributesOfItem(atPath: filePathNewFile)
                     let fileSize = fileDictionary[FileAttributeKey.size] as! Int64
-                    
+
                     cell.labelDetailNewFile.text = CCUtility.dateDiff(metadataNewFile.date as Date) + "\n" + CCUtility.transformedSize(fileSize)
-                    
+
                 } catch { print("Error: \(error)") }
-                
+
             } else {
-                
+
                 CCUtility.dateDiff(metadataNewFile.date as Date)
             }
-            
+
             if metadatasConflictNewFiles.contains(metadataNewFile.ocId) {
                 cell.switchNewFile.isOn = true
             } else {
                 cell.switchNewFile.isOn = false
             }
-        
+
             // Hide switch if only one
             if metadatasUploadInConflict.count == 1 {
                 cell.switchAlreadyExistingFile.isHidden = true
                 cell.switchNewFile.isHidden = true
             }
-            
+
             // text label new file
             if textLabelDetailNewFile != nil {
                 cell.labelDetailNewFile.text = textLabelDetailNewFile! + "\n"
             }
-            
+
             return cell
         }
-        
+
         return UITableViewCell()
     }
 }
@@ -503,7 +503,7 @@ extension NCCreateFormUploadConflict: UITableViewDataSource {
 // MARK: - NCCreateFormUploadConflictCellDelegate
 
 extension NCCreateFormUploadConflict: NCCreateFormUploadConflictCellDelegate {
-    
+
     func valueChangedSwitchNewFile(with ocId: String, isOn: Bool) {
         if let index = metadatasConflictNewFiles.firstIndex(of: ocId) {
             metadatasConflictNewFiles.remove(at: index)
@@ -516,10 +516,10 @@ extension NCCreateFormUploadConflict: NCCreateFormUploadConflictCellDelegate {
         } else {
             switchNewFiles.isOn = false
         }
-        
+
         canContinue()
     }
-    
+
     func valueChangedSwitchAlreadyExistingFile(with ocId: String, isOn: Bool) {
         if let index = metadatasConflictAlreadyExistingFiles.firstIndex(of: ocId) {
             metadatasConflictAlreadyExistingFiles.remove(at: index)
@@ -532,19 +532,19 @@ extension NCCreateFormUploadConflict: NCCreateFormUploadConflictCellDelegate {
         } else {
             switchAlreadyExistingFiles.isOn = false
         }
-        
+
         canContinue()
     }
-    
+
     func canContinue() {
         var result = true
-        
+
         for metadata in metadatasUploadInConflict {
             if !metadatasConflictNewFiles.contains(metadata.ocId) && !metadatasConflictAlreadyExistingFiles.contains(metadata.ocId) {
                 result = false
             }
         }
-        
+
         if result {
             buttonContinue.isEnabled = true
             buttonContinue.setTitleColor(NCBrandColor.shared.label, for: .normal)
@@ -554,4 +554,3 @@ extension NCCreateFormUploadConflict: NCCreateFormUploadConflictCellDelegate {
         }
     }
 }
-

+ 6 - 6
iOSClient/Main/Create cloud/NCCreateFormUploadConflictCell.swift

@@ -24,7 +24,7 @@
 import UIKit
 
 class NCCreateFormUploadConflictCell: UITableViewCell {
-    
+
     @IBOutlet weak var labelFileName: UILabel!
 
     @IBOutlet weak var imageAlreadyExistingFile: UIImageView!
@@ -35,21 +35,21 @@ class NCCreateFormUploadConflictCell: UITableViewCell {
 
     @IBOutlet weak var switchAlreadyExistingFile: UISwitch!
     @IBOutlet weak var switchNewFile: UISwitch!
-    
-    var delegate: NCCreateFormUploadConflictCellDelegate?
+
+    weak var delegate: NCCreateFormUploadConflictCellDelegate?
     var ocId: String = ""
 
     @IBAction func valueChangedSwitchNewFile(_ sender: Any) {
         delegate?.valueChangedSwitchNewFile(with: ocId, isOn: switchNewFile.isOn)
     }
-    
+
     @IBAction func valueChangedSwitchAlreadyExistingFile(_ sender: Any) {
         delegate?.valueChangedSwitchAlreadyExistingFile(with: ocId, isOn: switchAlreadyExistingFile.isOn)
     }
 }
 
-protocol NCCreateFormUploadConflictCellDelegate {
-    
+protocol NCCreateFormUploadConflictCellDelegate: AnyObject {
+
     func valueChangedSwitchNewFile(with ocId: String, isOn: Bool)
     func valueChangedSwitchAlreadyExistingFile(with ocId: String, isOn: Bool)
 

+ 148 - 148
iOSClient/Main/Create cloud/NCCreateFormUploadDocuments.swift

@@ -23,6 +23,7 @@
 
 import UIKit
 import NCCommunication
+import XLForm
 
 // MARK: -
 
@@ -31,7 +32,7 @@ import NCCommunication
     @IBOutlet weak var indicator: UIActivityIndicatorView!
     @IBOutlet weak var collectionView: UICollectionView!
     @IBOutlet weak var collectionViewHeigth: NSLayoutConstraint!
-    
+
     let appDelegate = UIApplication.shared.delegate as! AppDelegate
 
     var editorId = ""
@@ -45,108 +46,108 @@ import NCCommunication
     var titleForm = ""
     var listOfTemplate: [NCCommunicationEditorTemplates] = []
     var selectTemplate: NCCommunicationEditorTemplates?
-    
+
     // Layout
     let numItems = 2
     let sectionInsets: CGFloat = 10
     let highLabelName: CGFloat = 20
-    
+
     // MARK: - View Life Cycle
-    
+
     override func viewDidLoad() {
         super.viewDidLoad()
-                
+
         if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account) {
             fileNameFolder = "/"
         } else {
             fileNameFolder = (serverUrl as NSString).lastPathComponent
         }
-        
+
         self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
 
-        let cancelButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(cancel))
-        let saveButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
-        
+        let cancelButton: UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(cancel))
+        let saveButton: UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
+
         self.navigationItem.leftBarButtonItem = cancelButton
         self.navigationItem.rightBarButtonItem = saveButton
         self.navigationItem.rightBarButtonItem?.isEnabled = false
-        
+
         // title 
         self.title = titleForm
-      
+
         changeTheming()
-        
+
         initializeForm()
-        
+
         // load the templates available
         getTemplate()
     }
-    
+
     override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
         super.traitCollectionDidChange(previousTraitCollection)
-        
+
         changeTheming()
     }
-    
+
     // MARK: - Theming
-    
+
     func changeTheming() {
-        
+
         view.backgroundColor = NCBrandColor.shared.systemGroupedBackground
         collectionView.backgroundColor = NCBrandColor.shared.systemGroupedBackground
         tableView.backgroundColor = NCBrandColor.shared.secondarySystemGroupedBackground
-        
+
         tableView.reloadData()
         collectionView.reloadData()
     }
-    
+
     // MARK: - Tableview (XLForm)
 
     func initializeForm() {
-        
-        let form : XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor
+
+        let form: XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor
         form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
-        
-        var section : XLFormSectionDescriptor
-        var row : XLFormRowDescriptor
-        
+
+        var section: XLFormSectionDescriptor
+        var row: XLFormRowDescriptor
+
         // Section: Destination Folder
-        
+
         section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: "").uppercased())
         form.addFormSection(section)
-        
+
         row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: fileNameFolder)
         row.action.formSelector = #selector(changeDestinationFolder(_:))
         row.value = fileNameFolder
         row.cellConfig["backgroundColor"] = tableView.backgroundColor
 
         row.cellConfig["imageView.image"] =  UIImage(named: "folder")!.image(color: NCBrandColor.shared.brandElement, size: 25)
-        
+
         row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
         row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
 
         section.addFormRow(row)
-        
+
         // Section: File Name
-        
+
         section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_filename_", comment: "").uppercased())
         form.addFormSection(section)
-        
+
         row = XLFormRowDescriptor(tag: "fileName", rowType: XLFormRowDescriptorTypeText, title: NSLocalizedString("_filename_", comment: ""))
         row.value = fileName
         row.cellConfig["backgroundColor"] = tableView.backgroundColor
-        
+
         row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
         row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textField.textColor"] = NCBrandColor.shared.label
-        
+
         row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
         row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
-        
+
         section.addFormRow(row)
-        
+
         self.form = form
     }
 
@@ -158,27 +159,27 @@ import NCCommunication
     }
 
     // MARK: - CollectionView
-    
+
     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
         return listOfTemplate.count
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
 
         let itemWidth: CGFloat = (collectionView.frame.width - (sectionInsets * 4) - CGFloat(numItems)) / CGFloat(numItems)
         let itemHeight: CGFloat = itemWidth + highLabelName
-        
+
         collectionViewHeigth.constant = itemHeight + sectionInsets
-        
+
         return CGSize(width: itemWidth, height: itemHeight)
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
-        
+
         let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
-        
+
         let template = listOfTemplate[indexPath.row]
-        
+
         // image
         let imagePreview = cell.viewWithTag(100) as! UIImageView
         if template.preview != "" {
@@ -192,12 +193,12 @@ import NCCommunication
                 getImageFromTemplate(name: template.name, preview: template.preview, indexPath: indexPath)
             }
         }
-        
+
         // name
         let name = cell.viewWithTag(200) as! UILabel
         name.text = template.name
         name.textColor = NCBrandColor.shared.secondarySystemGroupedBackground
-        
+
         // select
         let imageSelect = cell.viewWithTag(300) as! UIImageView
         if selectTemplate != nil && selectTemplate?.name == template.name {
@@ -208,165 +209,164 @@ import NCCommunication
             cell.backgroundColor = NCBrandColor.shared.secondarySystemGroupedBackground
             imageSelect.isHidden = true
         }
-        
+
         return cell
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
-        
+
         let template = listOfTemplate[indexPath.row]
-        
+
         selectTemplate = template
         fileNameExtension = template.ext
-        
+
         collectionView.reloadData()
     }
-    
+
     // MARK: - Action
-    
+
     func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
-        
+
         guard let serverUrl = serverUrl else {
             return
         }
-        
+
         self.serverUrl = serverUrl
         if serverUrl == NCUtilityFileSystem.shared.getHomeServer( account: appDelegate.account) {
             fileNameFolder = "/"
         } else {
             fileNameFolder = (serverUrl as NSString).lastPathComponent
         }
-        
-        let buttonDestinationFolder : XLFormRowDescriptor  = self.form.formRow(withTag: "ButtonDestinationFolder")!
+
+        let buttonDestinationFolder: XLFormRowDescriptor  = self.form.formRow(withTag: "ButtonDestinationFolder")!
         buttonDestinationFolder.title = fileNameFolder
-        
+
         self.tableView.reloadData()
     }
-    
+
     @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
-        
+
         self.deselectFormRow(sender)
-        
+
         let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
         let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
         let viewController = navigationController.topViewController as! NCSelect
-        
+
         viewController.delegate = self
         viewController.typeOfCommandView = .selectCreateFolder
 
         self.present(navigationController, animated: true, completion: nil)
     }
-    
+
     @objc func save() {
-        
+
         guard let selectTemplate = self.selectTemplate else {
             return
         }
         templateIdentifier = selectTemplate.identifier
 
-        let rowFileName : XLFormRowDescriptor  = self.form.formRow(withTag: "fileName")!
+        let rowFileName: XLFormRowDescriptor  = self.form.formRow(withTag: "fileName")!
         guard var fileNameForm = rowFileName.value else {
             return
         }
-        
+
         if fileNameForm as! String == "" {
             return
         } else {
-            
+
             let result = NCCommunicationCommon.shared.getInternalType(fileName: fileNameForm as! String, mimeType: "", directory: false)
             if NCUtility.shared.isDirectEditing(account: appDelegate.account, contentType: result.mimeType).count == 0 {
                 fileNameForm = (fileNameForm as! NSString).deletingPathExtension + "." + fileNameExtension
             }
-            
+
             if NCManageDatabase.shared.getMetadataConflict(account: appDelegate.account, serverUrl: serverUrl, fileName: String(describing: fileNameForm)) != nil {
-                
+
                 let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate.account, user: appDelegate.user, userId: appDelegate.userId, fileName: String(describing: fileNameForm), fileNameView: String(describing: fileNameForm), ocId: "", serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: "", livePhoto: false)
-                
+
                 guard let conflictViewController = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict else { return }
                 conflictViewController.textLabelDetailNewFile = NSLocalizedString("_now_", comment: "")
                 conflictViewController.alwaysNewFileNameNumber = true
                 conflictViewController.serverUrl = serverUrl
                 conflictViewController.metadatasUploadInConflict = [metadataForUpload]
                 conflictViewController.delegate = self
-                
+
                 self.present(conflictViewController, animated: true, completion: nil)
-                
+
             } else {
-                                
+
                 let fileNamePath = CCUtility.returnFileNamePath(fromFileName: String(describing: fileNameForm), serverUrl: serverUrl, urlBase: appDelegate.urlBase, account: appDelegate.account)!
                 createDocument(fileNamePath: fileNamePath, fileName: String(describing: fileNameForm))
             }
         }
     }
-    
+
     func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
-        
+
         if metadatas == nil || metadatas?.count == 0 {
-            
+
             DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                 self.cancel()
             }
-            
+
         } else {
-            
+
             let fileName = metadatas![0].fileName
             let fileNamePath = CCUtility.returnFileNamePath(fromFileName: fileName, serverUrl: serverUrl, urlBase: appDelegate.urlBase, account: appDelegate.account)!
-            
+
             createDocument(fileNamePath: fileNamePath, fileName: fileName)
         }
     }
-    
+
     func createDocument(fileNamePath: String, fileName: String) {
-        
+
         if self.editorId == NCGlobal.shared.editorText || self.editorId == NCGlobal.shared.editorOnlyoffice {
-             
+
             var customUserAgent: String?
-            
+
             if self.editorId == NCGlobal.shared.editorOnlyoffice {
                 customUserAgent = NCUtility.shared.getCustomUserAgentOnlyOffice()
             }
-            
-            NCCommunication.shared.NCTextCreateFile(fileNamePath: fileNamePath, editorId: editorId, creatorId: creatorId, templateId: templateIdentifier, customUserAgent: customUserAgent) { (account, url, errorCode, errorMessage) in
-                
+
+            NCCommunication.shared.NCTextCreateFile(fileNamePath: fileNamePath, editorId: editorId, creatorId: creatorId, templateId: templateIdentifier, customUserAgent: customUserAgent) { account, url, errorCode, errorMessage in
+
                 if errorCode == 0 && account == self.appDelegate.account {
-                    
+
                     if url != nil && url!.count > 0 {
                         let results = NCCommunicationCommon.shared.getInternalType(fileName: fileName, mimeType: "", directory: false)
-                        
+
                         self.dismiss(animated: true, completion: {
                             let metadata = NCManageDatabase.shared.createMetadata(account: self.appDelegate.account, user: self.appDelegate.user, userId: self.appDelegate.userId, fileName: fileName, fileNameView: fileName, ocId: CCUtility.createRandomString(12), serverUrl: self.serverUrl, urlBase: self.appDelegate.urlBase, url: url ?? "", contentType: results.mimeType, livePhoto: false)
-                            
+
                             if let viewController = self.appDelegate.activeViewController {
                                 NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil)
                             }
                         })
                     }
-                    
+
                 } else if errorCode != 0 {
-                    NCContentPresenter.shared.messageNotification("_error_", description: errorMessage, delay: NCGlobal.shared.dismissAfterSecond, type:NCContentPresenter.messageType.error, errorCode: errorCode)
+                    NCContentPresenter.shared.messageNotification("_error_", description: errorMessage, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
                 } else {
                    print("[LOG] It has been changed user during networking process, error.")
                 }
             }
         }
-        
+
         if self.editorId == NCGlobal.shared.editorCollabora {
-            
-            NCCommunication.shared.createRichdocuments(path: fileNamePath, templateId: templateIdentifier) { (account, url, errorCode, errorDescription) in
-                
+
+            NCCommunication.shared.createRichdocuments(path: fileNamePath, templateId: templateIdentifier) { account, url, errorCode, errorDescription in
+
                 if errorCode == 0 && account == self.appDelegate.account && url != nil {
-                   
+
                     self.dismiss(animated: true, completion: {
-                    
+
                         let createFileName = (fileName as NSString).deletingPathExtension + "." + self.fileNameExtension
                         let metadata = NCManageDatabase.shared.createMetadata(account: self.appDelegate.account, user: self.appDelegate.user, userId: self.appDelegate.userId, fileName: createFileName, fileNameView: createFileName, ocId: CCUtility.createRandomString(12), serverUrl: self.serverUrl, urlBase: self.appDelegate.urlBase, url: url!, contentType: "", livePhoto: false)
-                    
+
                         if let viewController = self.appDelegate.activeViewController {
                             NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil)
                         }
                    })
-                   
-                    
+
                 } else if errorCode != 0 {
                     NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
                 } else {
@@ -375,42 +375,42 @@ import NCCommunication
             }
         }
     }
-    
+
     @objc func cancel() {
-        
+
         self.dismiss(animated: true, completion: nil)
     }
-    
+
     // MARK: NC API
-    
+
     func getTemplate() {
-     
+
         indicator.color = NCBrandColor.shared.brandElement
         indicator.startAnimating()
-        
+
         if self.editorId == NCGlobal.shared.editorText || self.editorId == NCGlobal.shared.editorOnlyoffice {
-                        
+
             var customUserAgent: String?
             if self.editorId == NCGlobal.shared.editorOnlyoffice {
                 customUserAgent = NCUtility.shared.getCustomUserAgentOnlyOffice()
             }
-            NCCommunication.shared.NCTextGetListOfTemplates(customUserAgent: customUserAgent) { (account, templates, errorCode, errorMessage) in
-                
+            NCCommunication.shared.NCTextGetListOfTemplates(customUserAgent: customUserAgent) { account, templates, errorCode, _ in
+
                 self.indicator.stopAnimating()
-                
+
                 if errorCode == 0 && account == self.appDelegate.account {
-                    
+
                     for template in templates {
-                        
+
                         let temp = NCCommunicationEditorTemplates()
-                                               
+
                         temp.identifier = template.identifier
                         temp.ext = template.ext
                         temp.name = template.name
                         temp.preview = template.preview
-                                               
+
                         self.listOfTemplate.append(temp)
-                                               
+
                         // default: template empty
                         if temp.preview == "" {
                             self.selectTemplate = temp
@@ -419,11 +419,11 @@ import NCCommunication
                         }
                     }
                 }
-                    
+
                 if self.listOfTemplate.count == 0 {
-                    
+
                     let temp = NCCommunicationEditorTemplates()
-                    
+
                     temp.identifier = ""
                     if self.editorId == NCGlobal.shared.editorText {
                         temp.ext = "md"
@@ -436,40 +436,40 @@ import NCCommunication
                     }
                     temp.name = "Empty"
                     temp.preview = ""
-                                                                  
+
                     self.listOfTemplate.append(temp)
-                    
+
                     self.selectTemplate = temp
                     self.fileNameExtension = temp.ext
                     self.navigationItem.rightBarButtonItem?.isEnabled = true
                 }
-                
+
                 self.collectionView.reloadData()
             }
-            
+
         }
-        
-        if self.editorId == NCGlobal.shared.editorCollabora  {
-                        
-            NCCommunication.shared.getTemplatesRichdocuments(typeTemplate: typeTemplate) { (account, templates, errorCode, errorDescription) in
-                
+
+        if self.editorId == NCGlobal.shared.editorCollabora {
+
+            NCCommunication.shared.getTemplatesRichdocuments(typeTemplate: typeTemplate) { account, templates, errorCode, _ in
+
                 self.indicator.stopAnimating()
 
                 if errorCode == 0 && account == self.appDelegate.account {
-                    
+
                     for template in templates! {
-                        
+
                         let temp = NCCommunicationEditorTemplates()
-                        
+
                         temp.identifier = "\(template.templateId)"
                         temp.delete = template.delete
                         temp.ext = template.ext
                         temp.name = template.name
                         temp.preview = template.preview
                         temp.type = template.type
-                        
+
                         self.listOfTemplate.append(temp)
-                        
+
                         // default: template empty
                         if temp.preview == "" {
                             self.selectTemplate = temp
@@ -478,11 +478,11 @@ import NCCommunication
                         }
                     }
                 }
-                
+
                 if self.listOfTemplate.count == 0 {
-                    
+
                     let temp = NCCommunicationEditorTemplates()
-                    
+
                     temp.identifier = ""
                     if self.typeTemplate == NCGlobal.shared.templateDocument {
                         temp.ext = "docx"
@@ -493,31 +493,31 @@ import NCCommunication
                     }
                     temp.name = "Empty"
                     temp.preview = ""
-                                                                  
+
                     self.listOfTemplate.append(temp)
-                    
+
                     self.selectTemplate = temp
                     self.fileNameExtension = temp.ext
                     self.navigationItem.rightBarButtonItem?.isEnabled = true
                 }
-                
+
                 self.collectionView.reloadData()
             }
         }
     }
-    
+
     func getImageFromTemplate(name: String, preview: String, indexPath: IndexPath) {
-        
+
         let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + name + ".png"
 
-        NCCommunication.shared.download(serverUrlFileName: preview, fileNameLocalPath: fileNameLocalPath, requestHandler: { (_) in
-            
-        }, taskHandler: { (_) in
-            
-        }, progressHandler: { (_) in
-            
-        }) { (account, etag, date, lenght, allHeaderFields, error, errorCode, errorDescription) in
-            
+        NCCommunication.shared.download(serverUrlFileName: preview, fileNameLocalPath: fileNameLocalPath, requestHandler: { _ in
+
+        }, taskHandler: { _ in
+
+        }, progressHandler: { _ in
+
+        }) { account, _, _, _, _, _, errorCode, _ in
+
             if errorCode == 0 && account == self.appDelegate.account {
                 self.collectionView.reloadItems(at: [indexPath])
             } else if errorCode != 0 {

+ 210 - 213
iOSClient/Main/Create cloud/NCCreateFormUploadScanDocument.swift

@@ -25,10 +25,12 @@ import UIKit
 import NCCommunication
 import Vision
 import VisionKit
+import Photos
+import XLForm
 
 @available(iOS 13.0, *)
 class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NCCreateFormUploadConflictDelegate {
-    
+
     let appDelegate = UIApplication.shared.delegate as! AppDelegate
 
     enum typeQuality {
@@ -37,167 +39,167 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
         case high
     }
     var quality: typeQuality = .medium
-    
+
     var serverUrl = ""
     var titleServerUrl = ""
     var arrayImages: [UIImage] = []
     var fileName = CCUtility.createFileNameDate("scan", extension: "pdf")
     var password: String = ""
     var fileType = "PDF"
-    
+
     var cellBackgoundColor = NCBrandColor.shared.secondarySystemGroupedBackground
-    
+
     // MARK: - View Life Cycle
 
     convenience init(serverUrl: String, arrayImages: [UIImage]) {
-        
+
         self.init()
-        
+
         if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account) {
             titleServerUrl = "/"
         } else {
             titleServerUrl = (serverUrl as NSString).lastPathComponent
         }
-        
+
         self.serverUrl = serverUrl
         self.arrayImages = arrayImages
     }
-        
+
     override func viewDidLoad() {
-        
+
         super.viewDidLoad()
-        
+
         self.title = NSLocalizedString("_save_settings_", comment: "")
-        
-        let saveButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
+
+        let saveButton: UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
         self.navigationItem.rightBarButtonItem = saveButton
-        
+
         NCUtility.shared.colorNavigationController(navigationController, backgroundColor: NCBrandColor.shared.systemBackground, titleColor: NCBrandColor.shared.label, tintColor: nil, withoutShadow: false)
-        
+
         tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
 
         //        self.tableView.sectionHeaderHeight = 10
         //        self.tableView.sectionFooterHeight = 10        
-        
+
         //        let row : XLFormRowDescriptor  = self.form.formRow(withTag: "fileName")!
         //        let rowCell = row.cell(forForm: self)
         //        rowCell.becomeFirstResponder()
-        
+
         changeTheming()
-        
+
         initializeForm()
-        
+
         let value = CCUtility.getTextRecognitionStatus()
-        SetTextRecognition(newValue: value)
+        setTextRecognition(newValue: value)
     }
-    
+
     override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
         super.traitCollectionDidChange(previousTraitCollection)
-        
+
         changeTheming()
     }
-    
+
     // MARK: - Theming
-    
+
     @objc func changeTheming() {
-        
+
         view.backgroundColor = NCBrandColor.shared.systemGroupedBackground
         tableView.backgroundColor = NCBrandColor.shared.systemGroupedBackground
         cellBackgoundColor = NCBrandColor.shared.secondarySystemGroupedBackground
-        
+
         tableView.reloadData()
     }
-    
-    //MARK: XLForm
-    
+
+    // MARK: XLForm
+
     func initializeForm() {
-        
-        let form : XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor
+
+        let form: XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor
         form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
-        
-        var section : XLFormSectionDescriptor
-        var row : XLFormRowDescriptor
-        
+
+        var section: XLFormSectionDescriptor
+        var row: XLFormRowDescriptor
+
         // Section: Destination Folder
-        
+
         section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: ""))
         form.addFormSection(section)
-        
+
         row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: self.titleServerUrl)
         row.action.formSelector = #selector(changeDestinationFolder(_:))
         row.cellConfig["backgroundColor"] = cellBackgoundColor
 
         row.cellConfig["imageView.image"] =  UIImage(named: "folder")!.image(color: NCBrandColor.shared.brandElement, size: 25)
-        
+
         row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
         row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
 
         section.addFormRow(row)
-        
+
         // Section: Quality
-        
+
         section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_quality_image_title_", comment: ""))
         form.addFormSection(section)
-        
+
         row = XLFormRowDescriptor(tag: "compressionQuality", rowType: XLFormRowDescriptorTypeSlider)
         row.value = 0.5
         row.title = NSLocalizedString("_quality_medium_", comment: "")
         row.cellConfig["backgroundColor"] = cellBackgoundColor
 
         row.cellConfig["slider.minimumTrackTintColor"] = NCBrandColor.shared.brandElement
-        
+
         row.cellConfig["slider.maximumValue"] = 1
         row.cellConfig["slider.minimumValue"] = 0
         row.cellConfig["steps"] = 2
-        
+
         row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.center.rawValue
         row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
-        
+
         section.addFormRow(row)
-        
+
         // Section: Password
-        
+
         section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_pdf_password_", comment: ""))
         form.addFormSection(section)
-        
+
         row = XLFormRowDescriptor(tag: "password", rowType: XLFormRowDescriptorTypePassword, title: NSLocalizedString("_password_", comment: ""))
         row.cellConfig["backgroundColor"] = cellBackgoundColor
 
         row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
-        
+
         row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
         row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textField.textColor"] = NCBrandColor.shared.label
-        
+
         section.addFormRow(row)
-        
+
         // Section: Text recognition
-        
+
         section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_text_recognition_", comment: ""))
         form.addFormSection(section)
-            
+
         row = XLFormRowDescriptor(tag: "textRecognition", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_text_recognition_", comment: ""))
         row.value = 0
         row.cellConfig["backgroundColor"] = cellBackgoundColor
 
-        row.cellConfig["imageView.image"] = UIImage(named: "textRecognition")!.image(color: NCBrandColor.shared.brandElement, size: 25) 
-        
+        row.cellConfig["imageView.image"] = UIImage(named: "textRecognition")!.image(color: NCBrandColor.shared.brandElement, size: 25)
+
         row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
 
         section.addFormRow(row)
-        
+
         // Section: File
-        
+
         section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_file_creation_", comment: ""))
         form.addFormSection(section)
-        
+
         row = XLFormRowDescriptor(tag: "filetype", rowType: XLFormRowDescriptorTypeSelectorSegmentedControl, title: NSLocalizedString("_file_type_", comment: ""))
         if arrayImages.count == 1 {
-            row.selectorOptions = ["PDF","JPG"]
+            row.selectorOptions = ["PDF", "JPG"]
         } else {
             row.selectorOptions = ["PDF"]
         }
@@ -207,10 +209,9 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
         row.cellConfig["tintColor"] = NCBrandColor.shared.brandElement
         row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
-        
+
         section.addFormRow(row)
-        
-        
+
         row = XLFormRowDescriptor(tag: "fileName", rowType: XLFormRowDescriptorTypeText, title: NSLocalizedString("_filename_", comment: ""))
         row.value = self.fileName
         row.cellConfig["backgroundColor"] = cellBackgoundColor
@@ -223,47 +224,47 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
         row.cellConfig["textField.textColor"] = NCBrandColor.shared.label
 
         section.addFormRow(row)
-        
+
         self.form = form
     }
-    
+
     override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
-        
+
         super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
-        
+
         if formRow.tag == "textRecognition" {
-            
-            self.SetTextRecognition(newValue: newValue as! Int)
+
+            self.setTextRecognition(newValue: newValue as! Int)
         }
-        
+
         if formRow.tag == "fileName" {
-            
+
             self.form.delegate = nil
-            
+
             let fileNameNew = newValue as? String
-            
+
             if fileNameNew != nil {
                 self.fileName = CCUtility.removeForbiddenCharactersServer(fileNameNew)
             } else {
                 self.fileName = ""
             }
-            
+
             formRow.value = self.fileName
-            
+
             self.updateFormRow(formRow)
-            
+
             self.form.delegate = self
         }
-        
+
         if formRow.tag == "compressionQuality" {
-            
+
             self.form.delegate = nil
-            
-            //let row : XLFormRowDescriptor  = self.form.formRow(withTag: "descriptionQuality")!
+
+            // let row : XLFormRowDescriptor  = self.form.formRow(withTag: "descriptionQuality")!
             let newQuality = newValue as? NSNumber
             let compressionQuality = (newQuality?.doubleValue)!
-            
-            if compressionQuality >= 0.0 && compressionQuality <= 0.3  {
+
+            if compressionQuality >= 0.0 && compressionQuality <= 0.3 {
                 formRow.title = NSLocalizedString("_quality_low_", comment: "")
                 quality = typeQuality.low
             } else if compressionQuality > 0.3 && compressionQuality <= 0.6 {
@@ -273,12 +274,12 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
                 formRow.title = NSLocalizedString("_quality_high_", comment: "")
                 quality = typeQuality.high
             }
-            
+
             self.updateFormRow(formRow)
-            
+
             self.form.delegate = self
         }
-        
+
         if formRow.tag == "password" {
             let stringPassword = newValue as? String
             if stringPassword != nil {
@@ -287,17 +288,17 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
                 password = ""
             }
         }
-        
+
         if formRow.tag == "filetype" {
             fileType = newValue as! String
-            
-            let rowFileName : XLFormRowDescriptor  = self.form.formRow(withTag: "fileName")!
-            let rowPassword : XLFormRowDescriptor  = self.form.formRow(withTag: "password")!
+
+            let rowFileName: XLFormRowDescriptor  = self.form.formRow(withTag: "fileName")!
+            let rowPassword: XLFormRowDescriptor  = self.form.formRow(withTag: "password")!
 
             rowFileName.value = createFileName(rowFileName.value as? String)
-            
+
             self.updateFormRow(rowFileName)
-            
+
             // rowPassword
             if fileType == "JPG" || fileType == "TXT" {
                 rowPassword.value = ""
@@ -306,13 +307,13 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
             } else {
                 rowPassword.disabled = false
             }
-        
+
             self.updateFormRow(rowPassword)
         }
     }
-    
-    func SetTextRecognition(newValue: Int) {
-        
+
+    func setTextRecognition(newValue: Int) {
+
         let rowCompressionQuality: XLFormRowDescriptor = self.form.formRow(withTag: "compressionQuality")!
         let rowFileTape: XLFormRowDescriptor = self.form.formRow(withTag: "filetype")!
         let rowFileName: XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
@@ -320,16 +321,16 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
         let rowTextRecognition: XLFormRowDescriptor = self.form.formRow(withTag: "textRecognition")!
 
         self.form.delegate = nil
-         
+
         if newValue == 1 {
-            rowFileTape.selectorOptions = ["PDF","TXT"]
+            rowFileTape.selectorOptions = ["PDF", "TXT"]
             rowFileTape.value = "PDF"
             fileType = "PDF"
             rowPassword.disabled = true
             rowCompressionQuality.disabled = false
         } else {
             if arrayImages.count == 1 {
-                rowFileTape.selectorOptions = ["PDF","JPG"]
+                rowFileTape.selectorOptions = ["PDF", "JPG"]
             } else {
                 rowFileTape.selectorOptions = ["PDF"]
             }
@@ -338,136 +339,136 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
             rowPassword.disabled = false
             rowCompressionQuality.disabled = false
         }
-         
+
         rowFileName.value = createFileName(rowFileName.value as? String)
         self.updateFormRow(rowFileName)
         self.tableView.reloadData()
-        
+
         CCUtility.setTextRecognitionStatus(newValue)
         rowTextRecognition.value = newValue
-        
+
         self.form.delegate = self
     }
-    
+
     func createFileName(_ fileName: String?) -> String {
-        
+
         var name: String = ""
         var newFileName: String = ""
-        
+
         if fileName == nil || fileName == "" {
             name = CCUtility.createFileNameDate("scan", extension: "pdf") ?? "scan.pdf"
         } else {
             name = fileName!
         }
-        
+
         let ext = (name as NSString).pathExtension.uppercased()
-        
-        if (ext == "") {
+
+        if ext == "" {
             newFileName = name + "." + fileType.lowercased()
         } else {
             newFileName = (name as NSString).deletingPathExtension + "." + fileType.lowercased()
         }
-        
+
         return newFileName
     }
-    
+
     // MARK: - Action
-    
+
     func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
-        
+
         if serverUrl != nil {
-            
+
             CCUtility.setDirectoryScanDocuments(serverUrl!)
             self.serverUrl = serverUrl!
-            
+
             if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account) {
                 self.titleServerUrl = "/"
             } else {
                 self.titleServerUrl = (serverUrl! as NSString).lastPathComponent
             }
-            
+
             // Update
-            let row : XLFormRowDescriptor  = self.form.formRow(withTag: "ButtonDestinationFolder")!
+            let row: XLFormRowDescriptor  = self.form.formRow(withTag: "ButtonDestinationFolder")!
             row.title = self.titleServerUrl
             self.updateFormRow(row)
         }
     }
-    
+
     @objc func save() {
-        
-        let rowFileName : XLFormRowDescriptor  = self.form.formRow(withTag: "fileName")!
+
+        let rowFileName: XLFormRowDescriptor  = self.form.formRow(withTag: "fileName")!
         guard let name = rowFileName.value else {
             return
         }
         if name as! String == "" {
             return
         }
-        
+
         let ext = (name as! NSString).pathExtension.uppercased()
         var fileNameSave = ""
-        
-        if (ext == "") {
+
+        if ext == "" {
             fileNameSave = name as! String + "." + fileType.lowercased()
         } else {
             fileNameSave = (name as! NSString).deletingPathExtension + "." + fileType.lowercased()
         }
-        
-        //Create metadata for upload
+
+        // Create metadata for upload
         let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate.account, user: appDelegate.user, userId: appDelegate.userId, fileName: fileNameSave, fileNameView: fileNameSave, ocId: UUID().uuidString, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: "", livePhoto: false)
-        
+
         metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
         metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile
         metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
-                
+
         if NCManageDatabase.shared.getMetadataConflict(account: appDelegate.account, serverUrl: serverUrl, fileName: fileNameSave) != nil {
-                        
+
             guard let conflictViewController = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict else { return }
             conflictViewController.textLabelDetailNewFile = NSLocalizedString("_now_", comment: "")
             conflictViewController.serverUrl = serverUrl
             conflictViewController.metadatasUploadInConflict = [metadataForUpload]
             conflictViewController.delegate = self
-            
+
             self.present(conflictViewController, animated: true, completion: nil)
-            
+
         } else {
-                     
+
             NCUtility.shared.startActivityIndicator(backgroundView: self.view, blurEffect: true)
-            
+
             DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                 self.dismissAndUpload(metadataForUpload)
             }
         }
     }
-    
+
     func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
-        
+
         if metadatas != nil && metadatas!.count > 0 {
-                 
+
             NCUtility.shared.startActivityIndicator(backgroundView: self.view, blurEffect: true)
-            
+
             DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                 self.dismissAndUpload(metadatas![0])
             }
         }
     }
-    
+
     func dismissAndUpload(_ metadata: tableMetadata) {
-        
+
         guard let fileNameGenerateExport = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else {
             NCUtility.shared.stopActivityIndicator()
             NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorCreationFile)
             return
         }
-        
+
         // Text Recognition TXT
         if fileType == "TXT" && self.form.formRow(withTag: "textRecognition")!.value as! Int == 1 {
-            
+
             var textFile = ""
             for image in self.arrayImages {
-                
+
                 let requestHandler = VNImageRequestHandler(cgImage: image.cgImage!, options: [:])
-                
-                let request = VNRecognizeTextRequest { (request, error) in
+
+                let request = VNRecognizeTextRequest { request, _ in
                     guard let observations = request.results as? [VNRecognizedTextObservation] else {
                         NCUtility.shared.stopActivityIndicator()
                         return
@@ -476,32 +477,32 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
                         guard let textLine = observation.topCandidates(1).first else {
                             continue
                         }
-                           
+
                         textFile += textLine.string
                         textFile += "\n"
                     }
                 }
-                
+
                 request.recognitionLevel = .accurate
                 request.usesLanguageCorrection = true
                 try? requestHandler.perform([request])
             }
-            
+
             do {
-                try textFile.write(to: NSURL(fileURLWithPath: fileNameGenerateExport) as URL  , atomically: true, encoding: .utf8)
+                try textFile.write(to: NSURL(fileURLWithPath: fileNameGenerateExport) as URL, atomically: true, encoding: .utf8)
             } catch {
                 NCUtility.shared.stopActivityIndicator()
                 NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorCreationFile)
                 return
             }
         }
-        
+
         if fileType == "PDF" {
-            
+
             let pdfData = NSMutableData()
-            
+
             if password.count > 0 {
-                let info: [AnyHashable: Any] = [kCGPDFContextUserPassword as String : password, kCGPDFContextOwnerPassword as String : password]
+                let info: [AnyHashable: Any] = [kCGPDFContextUserPassword as String: password, kCGPDFContextOwnerPassword as String: password]
                 UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, info)
             } else {
                 UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
@@ -510,21 +511,21 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
 #if targetEnvironment(simulator)
             fontColor = UIColor.red
 #endif
-            
+
             for var image in self.arrayImages {
-                
+
                 image = changeCompressionImage(image)
-                
+
                 let bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
-                
+
                 if self.form.formRow(withTag: "textRecognition")!.value as! Int == 1 {
-                    
+
                     UIGraphicsBeginPDFPageWithInfo(bounds, nil)
                     image.draw(in: bounds)
 
                     let requestHandler = VNImageRequestHandler(cgImage: image.cgImage!, options: [:])
-                    
-                    let request = VNRecognizeTextRequest { (request, error) in
+
+                    let request = VNRecognizeTextRequest { request, _ in
                         guard let observations = request.results as? [VNRecognizedTextObservation] else {
                             NCUtility.shared.stopActivityIndicator()
                             return
@@ -533,7 +534,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
                             guard let textLine = observation.topCandidates(1).first else {
                                 continue
                             }
-                            
+
                             var t: CGAffineTransform = CGAffineTransform.identity
                             t = t.scaledBy(x: image.size.width, y: -image.size.height)
                             t = t.translatedBy(x: 0, y: -1)
@@ -542,41 +543,41 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
 
                             let font = UIFont.systemFont(ofSize: rect.size.height, weight: .regular)
                             let attributes = self.bestFittingFont(for: text, in: rect, fontDescriptor: font.fontDescriptor, fontColor: fontColor)
-                        
+
                             text.draw(with: rect, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
                         }
                     }
-                    
+
                     request.recognitionLevel = .accurate
                     request.usesLanguageCorrection = true
                     try? requestHandler.perform([request])
-                    
+
                 } else {
-                    
+
                     UIGraphicsBeginPDFPageWithInfo(bounds, nil)
                     image.draw(in: bounds)
                 }
             }
-            
-            UIGraphicsEndPDFContext();
-            
+
+            UIGraphicsEndPDFContext()
+
             do {
                 try pdfData.write(toFile: fileNameGenerateExport, options: .atomic)
             } catch {
                 print("error catched")
             }
         }
-        
+
         if fileType == "JPG" {
-            
+
             let image = changeCompressionImage(self.arrayImages[0])
-            
+
             guard let data = image.jpegData(compressionQuality: CGFloat(0.5)) else {
                 NCUtility.shared.stopActivityIndicator()
                 NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorCreationFile)
                 return
             }
-            
+
             do {
                 try data.write(to: NSURL.fileURL(withPath: fileNameGenerateExport), options: .atomic)
             } catch {
@@ -585,18 +586,18 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
                 return
             }
         }
-        
+
         NCUtility.shared.stopActivityIndicator()
 
         appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: [metadata])
 
         // Request delete all image scanned
         let alertController = UIAlertController(title: "", message: NSLocalizedString("_delete_all_scanned_images_", comment: ""), preferredStyle: .alert)
-        
-        let actionYes = UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (action:UIAlertAction) in
-            
+
+        let actionYes = UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (_: UIAlertAction) in
+
             let path = CCUtility.getDirectoryScan()!
-            
+
             do {
                 let filePaths = try FileManager.default.contentsOfDirectory(atPath: path)
                 for filePath in filePaths {
@@ -605,41 +606,41 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
             } catch let error as NSError {
                 print("Error: \(error.debugDescription)")
             }
-            
+
             self.dismiss(animated: true, completion: nil)
         }
-        
-        let actionNo = UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (action:UIAlertAction) in
+
+        let actionNo = UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (_: UIAlertAction) in
             self.dismiss(animated: true, completion: nil)
         }
-        
+
         alertController.addAction(actionYes)
         alertController.addAction(actionNo)
-        self.present(alertController, animated: true, completion:nil)
+        self.present(alertController, animated: true, completion: nil)
     }
-    
+
     func cancel() {
-        
+
         self.dismiss(animated: true, completion: nil)
     }
-    
+
     @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
-        
+
         self.deselectFormRow(sender)
-        
+
         let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
         let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
         let viewController = navigationController.topViewController as! NCSelect
-        
+
         viewController.delegate = self
         viewController.typeOfCommandView = .selectCreateFolder
         viewController.includeDirectoryE2EEncryption = true
-                
+
         self.present(navigationController, animated: true, completion: nil)
     }
-    
+
     func changeCompressionImage(_ image: UIImage) -> UIImage {
-        
+
         var compressionQuality: CGFloat = 0.5
         var baseHeight: Float = 595.2    // A4
         var baseWidth: Float = 841.8     // A4
@@ -658,7 +659,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
             baseWidth *= 4
             compressionQuality = 0.9
         }
-        
+
         var newHeight = Float(image.size.height)
         var newWidth = Float(image.size.width)
         var imgRatio: Float = newWidth / newHeight
@@ -669,18 +670,16 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
                 imgRatio = baseHeight / newHeight
                 newWidth = imgRatio * newWidth
                 newHeight = baseHeight
-            }
-            else if imgRatio > baseRatio {
+            } else if imgRatio > baseRatio {
                 imgRatio = baseWidth / newWidth
                 newHeight = imgRatio * newHeight
                 newWidth = baseWidth
-            }
-            else {
+            } else {
                 newHeight = baseHeight
                 newWidth = baseWidth
             }
         }
-        
+
         let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(newWidth), height: CGFloat(newHeight))
         UIGraphicsBeginImageContext(rect.size)
         image.draw(in: rect)
@@ -689,34 +688,34 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
         UIGraphicsEndImageContext()
         return UIImage(data: imageData!) ?? image
     }
-    
+
     func bestFittingFont(for text: String, in bounds: CGRect, fontDescriptor: UIFontDescriptor, fontColor: UIColor) -> [NSAttributedString.Key: Any] {
-        
+
         let constrainingDimension = min(bounds.width, bounds.height)
         let properBounds = CGRect(origin: .zero, size: bounds.size)
         var attributes: [NSAttributedString.Key: Any] = [:]
-        
+
         let infiniteBounds = CGSize(width: CGFloat.infinity, height: CGFloat.infinity)
         var bestFontSize: CGFloat = constrainingDimension
-        
+
         // Search font (H)
         for fontSize in stride(from: bestFontSize, through: 0, by: -1) {
             let newFont = UIFont(descriptor: fontDescriptor, size: fontSize)
             attributes[.font] = newFont
-            
+
             let currentFrame = text.boundingRect(with: infiniteBounds, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil)
-            
+
             if properBounds.contains(currentFrame) {
                 bestFontSize = fontSize
                 break
             }
         }
-        
+
         // Search kern (W)
         let font = UIFont(descriptor: fontDescriptor, size: bestFontSize)
-        attributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: fontColor, NSAttributedString.Key.kern: 0] as [NSAttributedString.Key : Any]
+        attributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: fontColor, NSAttributedString.Key.kern: 0] as [NSAttributedString.Key: Any]
         for kern in stride(from: 0, through: 100, by: 0.1) {
-            let attributesTmp = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: fontColor, NSAttributedString.Key.kern: kern] as [NSAttributedString.Key : Any]
+            let attributesTmp = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: fontColor, NSAttributedString.Key.kern: kern] as [NSAttributedString.Key: Any]
             let size = text.size(withAttributes: attributesTmp).width
             if size <= bounds.width {
                 attributes = attributesTmp
@@ -724,36 +723,35 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC
                 break
             }
         }
-        
+
         return attributes
     }
 
 }
 
 @available(iOS 13.0, *)
-class NCCreateScanDocument : NSObject, VNDocumentCameraViewControllerDelegate {
+class NCCreateScanDocument: NSObject, VNDocumentCameraViewControllerDelegate {
     @objc static let shared: NCCreateScanDocument = {
         let instance = NCCreateScanDocument()
         return instance
     }()
-    
-    let appDelegate = UIApplication.shared.delegate as! AppDelegate
+
     var viewController: UIViewController?
-    
+
     func openScannerDocument(viewController: UIViewController) {
-        
+
         self.viewController = viewController
-        
+
         guard VNDocumentCameraViewController.isSupported else { return }
-            
+
         let controller = VNDocumentCameraViewController()
         controller.delegate = self
 
         self.viewController?.present(controller, animated: true)
     }
-    
+
     func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFinishWith scan: VNDocumentCameraScan) {
-                
+
         for pageNumber in 0..<scan.pageCount {
             let fileName = CCUtility.createFileName("scan.png", fileDate: Date(), fileType: PHAssetMediaType.image, keyFileName: NCGlobal.shared.keyFileNameMask, keyFileNameType: NCGlobal.shared.keyFileNameType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal, forcedNewFileName: true)!
             let fileNamePath = CCUtility.getDirectoryScan() + "/" + fileName
@@ -762,22 +760,21 @@ class NCCreateScanDocument : NSObject, VNDocumentCameraViewControllerDelegate {
                 try image.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath))
             } catch { }
         }
-        
+
         controller.dismiss(animated: true) {
             if self.viewController is DragDropViewController {
                 (self.viewController as! DragDropViewController).loadImage()
             } else {
                 let storyboard = UIStoryboard(name: "Scan", bundle: nil)
                 let controller = storyboard.instantiateInitialViewController()!
-                
+
                 controller.modalPresentationStyle = UIModalPresentationStyle.pageSheet
                 self.viewController?.present(controller, animated: true, completion: nil)
             }
         }
     }
-        
+
     func documentCameraViewControllerDidCancel(_ controller: VNDocumentCameraViewController) {
         controller.dismiss(animated: true, completion: nil)
     }
 }
-

+ 101 - 102
iOSClient/Main/Create cloud/NCCreateFormUploadVoiceNote.swift

@@ -25,7 +25,7 @@ import UIKit
 import NCCommunication
 
 class NCCreateFormUploadVoiceNote: XLFormViewController, NCSelectDelegate, AVAudioPlayerDelegate, NCCreateFormUploadConflictDelegate {
-    
+
     @IBOutlet weak var buttonPlayStop: UIButton!
     @IBOutlet weak var labelTimer: UILabel!
     @IBOutlet weak var labelDuration: UILabel!
@@ -39,7 +39,7 @@ class NCCreateFormUploadVoiceNote: XLFormViewController, NCSelectDelegate, AVAud
     private var fileNamePath = ""
     private var durationPlayer: TimeInterval = 0
     private var counterSecondPlayer: TimeInterval = 0
-    
+
     private var audioPlayer: AVAudioPlayer!
     private var timer = Timer()
 
@@ -49,74 +49,74 @@ class NCCreateFormUploadVoiceNote: XLFormViewController, NCSelectDelegate, AVAud
 
     override func viewDidLoad() {
         super.viewDidLoad()
-                
+
         self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(cancel))
         self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
-        
+
         self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
 
         // title
         self.title = NSLocalizedString("_voice_memo_title_", comment: "")
-        
+
         // Button Play Stop
         buttonPlayStop.setImage(UIImage(named: "audioPlay")!.image(color: NCBrandColor.shared.gray, size: 100), for: .normal)
-        
+
         // Progress view
         progressView.progress = 0
         progressView.progressTintColor = .green
         progressView.trackTintColor = UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 247.0/255.0, alpha: 1.0)
-        
+
         labelTimer.textColor = NCBrandColor.shared.label
         labelDuration.textColor = NCBrandColor.shared.label
-        
+
         changeTheming()
-        
+
         initializeForm()
     }
-    
+
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
-        
+
         updateTimerUI()
     }
-    
+
     override func viewDidDisappear(_ animated: Bool) {
         super.viewDidDisappear(animated)
-        
+
         if audioPlayer.isPlaying {
             stop()
         }
     }
-    
+
     override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
         super.traitCollectionDidChange(previousTraitCollection)
-        
+
         changeTheming()
     }
-    
+
     // MARK: - Theming
-    
+
     @objc func changeTheming() {
-        
+
         view.backgroundColor = NCBrandColor.shared.systemGroupedBackground
         tableView.backgroundColor = NCBrandColor.shared.systemGroupedBackground
         cellBackgoundColor = NCBrandColor.shared.secondarySystemGroupedBackground
-        
+
         tableView.reloadData()
     }
-    
+
     public func setup(serverUrl: String, fileNamePath: String, fileName: String) {
-    
+
         if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account) {
             titleServerUrl = "/"
         } else {
             titleServerUrl = (serverUrl as NSString).lastPathComponent
         }
-    
+
         self.fileName = fileName
         self.serverUrl = serverUrl
         self.fileNamePath = fileNamePath
-        
+
         // player
         do {
             try audioPlayer = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileNamePath))
@@ -127,39 +127,39 @@ class NCCreateFormUploadVoiceNote: XLFormViewController, NCSelectDelegate, AVAud
             buttonPlayStop.isEnabled = false
         }
     }
-    
-    //MARK: XLForm
+
+    // MARK: XLForm
 
     func initializeForm() {
-        
-        let form : XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor
+
+        let form: XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor
         form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
-        
-        var section : XLFormSectionDescriptor
-        var row : XLFormRowDescriptor
-        
+
+        var section: XLFormSectionDescriptor
+        var row: XLFormRowDescriptor
+
         // Section: Destination Folder
-        
+
         section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: "").uppercased())
         form.addFormSection(section)
-        
+
         row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: self.titleServerUrl)
         row.action.formSelector = #selector(changeDestinationFolder(_:))
         row.cellConfig["backgroundColor"] = cellBackgoundColor
 
         row.cellConfig["imageView.image"] =  UIImage(named: "folder")!.image(color: NCBrandColor.shared.brandElement, size: 25)
-        
+
         row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
         row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
-        
+
         section.addFormRow(row)
-        
+
         // Section: File Name
-        
+
         section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_filename_", comment: "").uppercased())
         form.addFormSection(section)
-        
+
         row = XLFormRowDescriptor(tag: "fileName", rowType: XLFormRowDescriptorTypeText, title: NSLocalizedString("_filename_", comment: ""))
         row.value = self.fileName
         row.cellConfig["backgroundColor"] = cellBackgoundColor
@@ -170,32 +170,32 @@ class NCCreateFormUploadVoiceNote: XLFormViewController, NCSelectDelegate, AVAud
         row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
         row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
         row.cellConfig["textField.textColor"] = NCBrandColor.shared.label
-        
+
         section.addFormRow(row)
 
         self.form = form
     }
-        
+
     override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
-        
+
         super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
-        
+
         if formRow.tag == "fileName" {
-            
+
             self.form.delegate = nil
-            
+
             if let fileNameNew = formRow.value {
                 self.fileName = CCUtility.removeForbiddenCharactersServer(fileNameNew as? String)
             }
-            
+
             formRow.value = self.fileName
             self.updateFormRow(formRow)
-            
+
             self.form.delegate = self
         }
     }
-    
-    //MARK: TableViewDelegate
+
+    // MARK: TableViewDelegate
 
     override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
         let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
@@ -203,161 +203,160 @@ class NCCreateFormUploadVoiceNote: XLFormViewController, NCSelectDelegate, AVAud
         header.textLabel?.textColor = .gray
         header.tintColor = cellBackgoundColor
     }
-    
+
     // MARK: - Action
-    
+
     func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
-        
+
         if serverUrl != nil {
-            
+
             self.serverUrl = serverUrl!
-            
+
             if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account) {
                 self.titleServerUrl = "/"
             } else {
                 self.titleServerUrl = (serverUrl! as NSString).lastPathComponent
             }
-            
+
             // Update
-            let row : XLFormRowDescriptor  = self.form.formRow(withTag: "ButtonDestinationFolder")!
+            let row: XLFormRowDescriptor  = self.form.formRow(withTag: "ButtonDestinationFolder")!
             row.title = self.titleServerUrl
             self.updateFormRow(row)
         }
     }
-    
+
     @objc func save() {
-        
-        let rowFileName : XLFormRowDescriptor  = self.form.formRow(withTag: "fileName")!
+
+        let rowFileName: XLFormRowDescriptor  = self.form.formRow(withTag: "fileName")!
         guard let name = rowFileName.value else {
             return
         }
         let ext = (name as! NSString).pathExtension.uppercased()
         var fileNameSave = ""
-                   
-        if (ext == "") {
+
+        if ext == "" {
             fileNameSave = name as! String + ".m4a"
         } else {
             fileNameSave = (name as! NSString).deletingPathExtension + ".m4a"
         }
-        
-        let metadataForUpload = NCManageDatabase.shared.createMetadata(account: self.appDelegate.account, user: self.appDelegate.user, userId: self.appDelegate.userId, fileName: fileNameSave, fileNameView: fileNameSave, ocId: UUID().uuidString, serverUrl: self.serverUrl, urlBase: self.appDelegate.urlBase ,url: "", contentType: "", livePhoto: false)
-        
+
+        let metadataForUpload = NCManageDatabase.shared.createMetadata(account: self.appDelegate.account, user: self.appDelegate.user, userId: self.appDelegate.userId, fileName: fileNameSave, fileNameView: fileNameSave, ocId: UUID().uuidString, serverUrl: self.serverUrl, urlBase: self.appDelegate.urlBase, url: "", contentType: "", livePhoto: false)
+
         metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
         metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile
         metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
-        
+
         if NCManageDatabase.shared.getMetadataConflict(account: appDelegate.account, serverUrl: serverUrl, fileName: fileNameSave) != nil {
-                        
+
             guard let conflictViewController = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict else { return }
             conflictViewController.textLabelDetailNewFile = NSLocalizedString("_now_", comment: "")
             conflictViewController.serverUrl = serverUrl
             conflictViewController.metadatasUploadInConflict = [metadataForUpload]
             conflictViewController.delegate = self
-            
+
             self.present(conflictViewController, animated: true, completion: nil)
-            
+
         } else {
-                            
+
             dismissAndUpload(metadataForUpload)
         }
     }
-    
+
     func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
-        
+
         if metadatas != nil && metadatas!.count > 0 {
-                                
+
             DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                 self.dismissAndUpload(metadatas![0])
             }
         }
     }
-    
+
     func dismissAndUpload(_ metadata: tableMetadata) {
-        
+
         CCUtility.copyFile(atPath: self.fileNamePath, toPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
-                   
+
         appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: [metadata])
 
         self.dismiss(animated: true, completion: nil)
     }
-    
+
     @objc func cancel() {
-        
+
         try? FileManager.default.removeItem(atPath: fileNamePath)
         self.dismiss(animated: true, completion: nil)
     }
-    
+
     @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
-        
+
         self.deselectFormRow(sender)
-        
+
         let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
         let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
         let viewController = navigationController.topViewController as! NCSelect
-        
+
         viewController.delegate = self
         viewController.typeOfCommandView = .selectCreateFolder
         viewController.includeDirectoryE2EEncryption = true
-        
+
         self.present(navigationController, animated: true, completion: nil)
     }
-    
-    //MARK: Player - Timer
+
+    // MARK: Player - Timer
 
     func updateTimerUI() {
-        labelTimer.text =  String.init().formatSecondsToString(counterSecondPlayer)
-        labelDuration.text = String.init().formatSecondsToString(durationPlayer)
+        labelTimer.text =  String().formatSecondsToString(counterSecondPlayer)
+        labelDuration.text = String().formatSecondsToString(durationPlayer)
         progressView.progress = Float(counterSecondPlayer / durationPlayer)
     }
-    
+
     @objc func updateTimer() {
         counterSecondPlayer += 1
         updateTimerUI()
     }
-    
+
     @IBAction func playStop(_ sender: Any) {
 
         if audioPlayer.isPlaying {
-            
+
             stop()
-            
+
         } else {
-            
+
             start()
         }
     }
-    
+
     func start() {
-        
+
         audioPlayer.prepareToPlay()
         audioPlayer.play()
-        
+
         timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
-        
+
         buttonPlayStop.setImage(UIImage(named: "stop")!.image(color: NCBrandColor.shared.gray, size: 100), for: .normal)
     }
-    
+
     func stop() {
-        
+
         audioPlayer.currentTime = 0.0
         audioPlayer.stop()
-        
+
         timer.invalidate()
         counterSecondPlayer = 0
         progressView.progress = 0
         updateTimerUI()
-        
+
         buttonPlayStop.setImage(UIImage(named: "audioPlay")!.image(color: NCBrandColor.shared.gray, size: 100), for: .normal)
     }
-    
+
     func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
-        
+
         timer.invalidate()
         counterSecondPlayer = 0
         progressView.progress = 0
         updateTimerUI()
-        
+
         buttonPlayStop.setImage(UIImage(named: "audioPlay")!.image(color: NCBrandColor.shared.gray, size: 100), for: .normal)
     }
 }
-

+ 39 - 39
iOSClient/Main/Create cloud/NCCreateMenuAdd.swift

@@ -25,64 +25,64 @@ import Foundation
 import Sheeeeeeeeet
 
 class NCCreateMenuAdd: NSObject {
-    
-    let appDelegate = UIApplication.shared.delegate as! AppDelegate
+
+    weak var appDelegate = UIApplication.shared.delegate as! AppDelegate
     var isNextcloudTextAvailable = false
-    
-    @objc init(viewController: UIViewController, view : UIView) {
+
+    @objc init(viewController: UIViewController, view: UIView) {
         super.init()
 
         if self.appDelegate.reachability.isReachable() && NCBrandBeta.shared.directEditing && NCManageDatabase.sharedInstance.getDirectEditingCreators(account: self.appDelegate.activeAccount) != nil {
             isNextcloudTextAvailable = true
         }
-        
+
         var items = [MenuItem]()
 
         ActionSheetTableView.appearance().backgroundColor = NCBrandColor.sharedInstance.backgroundForm
         ActionSheetTableView.appearance().separatorColor = NCBrandColor.sharedInstance.separator
         ActionSheetItemCell.appearance().backgroundColor = NCBrandColor.sharedInstance.backgroundForm
         ActionSheetItemCell.appearance().titleColor = NCBrandColor.sharedInstance.textView
-        
-        items.append(MenuItem(title: NSLocalizedString("_upload_photos_videos_", comment: ""), value: 10, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "file_photo"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
-        
-        items.append(MenuItem(title: NSLocalizedString("_upload_file_", comment: ""), value: 20, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "file"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
-        
+
+        items.append(MenuItem(title: NSLocalizedString("_upload_photos_videos_", comment: ""), value: 10, image: CCGraphics.changeThemingColorImage(UIImage(named: "file_photo"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
+
+        items.append(MenuItem(title: NSLocalizedString("_upload_file_", comment: ""), value: 20, image: CCGraphics.changeThemingColorImage(UIImage(named: "file"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
+
         if NCBrandOptions.sharedInstance.use_imi_viewer {
-            items.append(MenuItem(title: NSLocalizedString("_im_create_new_file", tableName: "IMLocalizable", bundle: Bundle.main, value: "", comment: ""), value: 21, image: CCGraphics.scale(UIImage.init(named: "imagemeter"), to: CGSize(width: 25, height: 25), isAspectRation: true)))
+            items.append(MenuItem(title: NSLocalizedString("_im_create_new_file", tableName: "IMLocalizable", bundle: Bundle.main, value: "", comment: ""), value: 21, image: CCGraphics.scale(UIImage(named: "imagemeter"), to: CGSize(width: 25, height: 25), isAspectRation: true)))
         }
-        
+
         if isNextcloudTextAvailable {
-            items.append(MenuItem(title: NSLocalizedString("_create_nextcloudtext_document_", comment: ""), value: 31, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "file_txt"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
+            items.append(MenuItem(title: NSLocalizedString("_create_nextcloudtext_document_", comment: ""), value: 31, image: CCGraphics.changeThemingColorImage(UIImage(named: "file_txt"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
         } else {
-            items.append(MenuItem(title: NSLocalizedString("_upload_file_text_", comment: ""), value: 30, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "file_txt"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
+            items.append(MenuItem(title: NSLocalizedString("_upload_file_text_", comment: ""), value: 30, image: CCGraphics.changeThemingColorImage(UIImage(named: "file_txt"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
         }
-        
+
 #if !targetEnvironment(simulator)
         if #available(iOS 11.0, *) {
-            items.append(MenuItem(title: NSLocalizedString("_scans_document_", comment: ""), value: 40, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "scan"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
+            items.append(MenuItem(title: NSLocalizedString("_scans_document_", comment: ""), value: 40, image: CCGraphics.changeThemingColorImage(UIImage(named: "scan"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
         }
 #endif
-        
-        items.append(MenuItem(title: NSLocalizedString("_create_voice_memo_", comment: ""), value: 50, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "microphone"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
 
-        items.append(MenuItem(title: NSLocalizedString("_create_folder_", comment: ""), value: 60, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), width: 50, height: 50, color: NCBrandColor.sharedInstance.brandElement)))
-        
+        items.append(MenuItem(title: NSLocalizedString("_create_voice_memo_", comment: ""), value: 50, image: CCGraphics.changeThemingColorImage(UIImage(named: "microphone"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
+
+        items.append(MenuItem(title: NSLocalizedString("_create_folder_", comment: ""), value: 60, image: CCGraphics.changeThemingColorImage(UIImage(named: "folder"), width: 50, height: 50, color: NCBrandColor.sharedInstance.brandElement)))
+
         if let richdocumentsMimetypes = NCManageDatabase.sharedInstance.getRichdocumentsMimetypes(account: appDelegate.activeAccount) {
             if richdocumentsMimetypes.count > 0 {
-                items.append(MenuItem(title: NSLocalizedString("_create_new_document_", comment: ""), value: 70, image: UIImage.init(named: "create_file_document")))
+                items.append(MenuItem(title: NSLocalizedString("_create_new_document_", comment: ""), value: 70, image: UIImage(named: "create_file_document")))
                 items.append(MenuItem(title: NSLocalizedString("_create_new_spreadsheet_", comment: ""), value: 80, image: UIImage(named: "create_file_xls")))
                 items.append(MenuItem(title: NSLocalizedString("_create_new_presentation_", comment: ""), value: 90, image: UIImage(named: "create_file_ppt")))
             }
         }
-        
+
         items.append(CancelButton(title: NSLocalizedString("_cancel_", comment: "")))
-        
-        let actionSheet = ActionSheet(menu: Menu(items: items), action: { (shhet, item) in
+
+        let actionSheet = ActionSheet(menu: Menu(items: items), action: { _, item in
 
             if item.value as? Int == 10 { self.appDelegate.activeMain.openAssetsPickerController() }
             if item.value as? Int == 20 { self.appDelegate.activeMain.openImportDocumentPicker() }
             if item.value as? Int == 21 {
-                _ = IMCreate.init(serverUrl: self.appDelegate.activeMain.serverUrl)
+                _ = IMCreate(serverUrl: self.appDelegate.activeMain.serverUrl)
             }
             if item.value as? Int == 30 {
                 let storyboard = UIStoryboard(name: "NCText", bundle: nil)
@@ -95,12 +95,12 @@ class NCCreateMenuAdd: NSObject {
                     return
                 }
                 navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
-                
+
                 let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadDocuments
                 viewController.typeTemplate = k_template_document
                 viewController.serverUrl = self.appDelegate.activeMain.serverUrl
                 viewController.titleForm = NSLocalizedString("_create_nextcloudtext_document_", comment: "")
-                
+
                 self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
             }
             if item.value as? Int == 40 {
@@ -108,22 +108,22 @@ class NCCreateMenuAdd: NSObject {
                     NCCreateScanDocument.sharedInstance.openScannerDocument(viewController: self.appDelegate.activeMain)
                 }
             }
-            
+
             if item.value as? Int == 50 { NCMainCommon.sharedInstance.startAudioRecorder() }
-            
+
             if item.value as? Int == 60 { self.appDelegate.activeMain.createFolder() }
-            
+
             if item.value as? Int == 70 {
                 guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController() else {
                     return
                 }
                 navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
-                
+
                 let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadDocuments
                 viewController.typeTemplate = k_template_document
                 viewController.serverUrl = self.appDelegate.activeMain.serverUrl
                 viewController.titleForm = NSLocalizedString("_create_new_document_", comment: "")
-                
+
                 self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
             }
             if item.value as? Int == 80 {
@@ -131,12 +131,12 @@ class NCCreateMenuAdd: NSObject {
                     return
                 }
                 navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
-                
+
                 let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadDocuments
                 viewController.typeTemplate = k_template_spreadsheet
                 viewController.serverUrl = self.appDelegate.activeMain.serverUrl
                 viewController.titleForm = NSLocalizedString("_create_new_spreadsheet_", comment: "")
-                
+
                 self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
             }
             if item.value as? Int == 90 {
@@ -144,19 +144,19 @@ class NCCreateMenuAdd: NSObject {
                     return
                 }
                 navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
-                
+
                 let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadDocuments
                 viewController.typeTemplate = k_template_presentation
                 viewController.serverUrl = self.appDelegate.activeMain.serverUrl
                 viewController.titleForm = NSLocalizedString("_create_new_presentation_", comment: "")
-                
+
                 self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
             }
-            
+
             if item is CancelButton { print("Cancel buttons has the value `true`") }
         })
-                
+
         actionSheet.present(in: viewController, from: view)
-        
+
     }
 }

+ 0 - 1
iOSClient/Main/NCCellProtocol.swift

@@ -29,4 +29,3 @@ protocol NCCellProtocol {
     var filePreviewImageView: UIImageView? { get }
     var fileUser: String? { get }
 }
-

+ 233 - 234
iOSClient/Main/NCFunctionCenter.swift

@@ -29,31 +29,31 @@ import IHProgressHUD
 @objc class NCFunctionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelectDelegate {
     @objc public static let shared: NCFunctionCenter = {
         let instance = NCFunctionCenter()
-        
+
         NotificationCenter.default.addObserver(instance, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
         NotificationCenter.default.addObserver(instance, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
-        
+
         return instance
     }()
-    
+
     let appDelegate = UIApplication.shared.delegate as! AppDelegate
     var viewerQuickLook: NCViewerQuickLook?
     var documentController: UIDocumentInteractionController?
-    
-    //MARK: - Download
+
+    // MARK: - Download
 
     @objc func downloadedFile(_ notification: NSNotification) {
-            
+
         if let userInfo = notification.userInfo as NSDictionary? {
             if let ocId = userInfo["ocId"] as? String, let selector = userInfo["selector"] as? String, let errorCode = userInfo["errorCode"] as? Int, let errorDescription = userInfo["errorDescription"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
-                
+
                 if metadata.account != appDelegate.account { return }
-                
+
                 if errorCode == 0 {
-                    
+
                     switch selector {
                     case NCGlobal.shared.selectorLoadFileQuickLook:
-                        
+
                         let fileNamePath = NSTemporaryDirectory() + metadata.fileNameView
                         CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: fileNamePath)
 
@@ -61,120 +61,120 @@ import IHProgressHUD
                         if #available(iOS 13.0, *) {
                             editingMode = true
                         }
-                        
+
                         let viewerQuickLook = NCViewerQuickLook(with: URL(fileURLWithPath: fileNamePath), editingMode: editingMode, metadata: metadata)
                         let navigationController = UINavigationController(rootViewController: viewerQuickLook)
                         navigationController.modalPresentationStyle = .overFullScreen
-                        
+
                         self.appDelegate.window?.rootViewController?.present(navigationController, animated: true)
-                        
+
                     case NCGlobal.shared.selectorLoadFileView:
-                        
+
                         if UIApplication.shared.applicationState == UIApplication.State.active {
-                                                        
+
                             if metadata.contentType.contains("opendocument") && !NCUtility.shared.isRichDocument(metadata) {
-                                
+
                                 self.openDocumentController(metadata: metadata)
-                                
+
                             } else if metadata.classFile == NCCommunicationCommon.typeClassFile.compress.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.unknow.rawValue {
 
                                 self.openDocumentController(metadata: metadata)
-                                
+
                             } else {
-                                
+
                                 if let viewController = self.appDelegate.activeViewController {
                                     let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
                                     NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon)
                                 }
                             }
                         }
-                        
+
                     case NCGlobal.shared.selectorOpenIn:
-                        
+
                         if UIApplication.shared.applicationState == UIApplication.State.active {
-                            
+
                             self.openDocumentController(metadata: metadata)
                         }
-                        
+
                     case NCGlobal.shared.selectorLoadCopy:
-                        
+
                         copyPasteboard()
-                        
+
                     case NCGlobal.shared.selectorLoadOffline:
-                        
+
                         NCManageDatabase.shared.setLocalFile(ocId: metadata.ocId, offline: true)
-                       
+
                     case NCGlobal.shared.selectorPrint:
-                        
+
                         printDocument(metadata: metadata)
-                        
+
                     case NCGlobal.shared.selectorSaveAlbum:
-                        
+
                         saveAlbum(metadata: metadata)
-                       
+
                     case NCGlobal.shared.selectorSaveBackground:
-                        
+
                         saveBackground(metadata: metadata)
-                        
+
                     case NCGlobal.shared.selectorSaveAlbumLivePhotoIMG, NCGlobal.shared.selectorSaveAlbumLivePhotoMOV:
-                        
+
                         var metadata = metadata
                         var metadataMOV = metadata
                         guard let metadataTMP = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) else { break }
-                        
+
                         if selector == NCGlobal.shared.selectorSaveAlbumLivePhotoIMG {
                             metadataMOV = metadataTMP
                         }
-                        
+
                         if selector == NCGlobal.shared.selectorSaveAlbumLivePhotoMOV {
                             metadata = metadataTMP
                         }
-                            
+
                         if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) && CCUtility.fileProviderStorageExists(metadataMOV.ocId, fileNameView: metadataMOV.fileNameView) {
                             saveLivePhotoToDisk(metadata: metadata, metadataMov: metadataMOV)
                         }
-                    
+
                     case NCGlobal.shared.selectorSaveAsScan:
-                        
+
                         saveAsScan(metadata: metadata)
-                        
+
                     case NCGlobal.shared.selectorOpenDetail:
-                        
-                        NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterOpenMediaDetail, userInfo: ["ocId":metadata.ocId])
-                        
+
+                        NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterOpenMediaDetail, userInfo: ["ocId": metadata.ocId])
+
                     default:
-                        
+
                         break
                     }
-                            
+
                 } else {
-                    
+
                     // File do not exists on server, remove in local
-                    if (errorCode == NCGlobal.shared.errorResourceNotFound || errorCode == NCGlobal.shared.errorBadServerResponse) {
-                        
+                    if errorCode == NCGlobal.shared.errorResourceNotFound || errorCode == NCGlobal.shared.errorBadServerResponse {
+
                         do {
                             try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
                         } catch { }
-                        
+
                         NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
                         NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
-                        
+
                     } else {
-                        
+
                         NCContentPresenter.shared.messageNotification("_download_file_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode, priority: .max)
                     }
                 }
             }
         }
     }
-    
-    //MARK: - Upload
+
+    // MARK: - Upload
 
     @objc func uploadedFile(_ notification: NSNotification) {
-    
+
         if let userInfo = notification.userInfo as NSDictionary? {
             if let ocId = userInfo["ocId"] as? String, let errorCode = userInfo["errorCode"] as? Int, let errorDescription = userInfo["errorDescription"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
-                
+
                 if metadata.account == appDelegate.account {
                     if errorCode != 0 {
                         if errorCode != -999 && errorDescription != "" {
@@ -185,50 +185,50 @@ import IHProgressHUD
             }
         }
     }
-    
+
     // MARK: -
 
-    func openShare(ViewController: UIViewController, metadata: tableMetadata, indexPage: NCGlobal.NCSharePagingIndex) {
-        
+    func openShare(viewController: UIViewController, metadata: tableMetadata, indexPage: NCGlobal.NCSharePagingIndex) {
+
         let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as! UINavigationController
         let shareViewController = shareNavigationController.topViewController as! NCSharePaging
-        
+
         shareViewController.metadata = metadata
         shareViewController.indexPage = indexPage
-        
+
         shareNavigationController.modalPresentationStyle = .formSheet
-        ViewController.present(shareNavigationController, animated: true, completion: nil)
+        viewController.present(shareNavigationController, animated: true, completion: nil)
     }
-     
+
     // MARK: -
-    
+
     func openDownload(metadata: tableMetadata, selector: String) {
-        
+
         if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
-            
+
             NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "selector": selector, "errorCode": 0, "errorDescription": "" ])
-                                    
+
         } else {
-            
-            NCNetworking.shared.download(metadata: metadata, selector: selector) { (_) in }
+
+            NCNetworking.shared.download(metadata: metadata, selector: selector) { _ in }
         }
     }
-    
+
     // MARK: - Open in ...
-    
+
     func openDocumentController(metadata: tableMetadata) {
-        
+
         guard let mainTabBar = self.appDelegate.mainTabBar else { return }
         let fileURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
-        
+
         documentController = UIDocumentInteractionController(url: fileURL)
         documentController?.presentOptionsMenu(from: mainTabBar.menuRect, in: mainTabBar, animated: true)
     }
-    
+
     func openActivityViewController(selectOcId: [String]) {
-        
+
         NCUtility.shared.startActivityIndicator(backgroundView: nil, blurEffect: true)
-        
+
         var error: Int = 0
         var items: [Any] = []
 
@@ -253,47 +253,47 @@ import IHProgressHUD
             }
         }
         if error == 0 && items.count > 0 {
-              
+
             guard let mainTabBar = self.appDelegate.mainTabBar else { return }
-                    
-            let activityViewController = UIActivityViewController.init(activityItems: items, applicationActivities: nil)
+
+            let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
 
             activityViewController.popoverPresentationController?.permittedArrowDirections = .any
             activityViewController.popoverPresentationController?.sourceView = mainTabBar
             activityViewController.popoverPresentationController?.sourceRect = mainTabBar.menuRect
-            
+
             self.appDelegate.window?.rootViewController?.present(activityViewController, animated: true)
-            
+
         }
         NCUtility.shared.stopActivityIndicator()
     }
-        
+
     // MARK: - Save as scan
-    
+
     func saveAsScan(metadata: tableMetadata) {
 
         let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
         let fileNameDestination = CCUtility.createFileName("scan.png", fileDate: Date(), fileType: PHAssetMediaType.image, keyFileName: NCGlobal.shared.keyFileNameMask, keyFileNameType: NCGlobal.shared.keyFileNameType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal, forcedNewFileName: true)!
         let fileNamePathDestination = CCUtility.getDirectoryScan() + "/" + fileNameDestination
-        
+
         NCUtilityFileSystem.shared.copyFile(atPath: fileNamePath, toPath: fileNamePathDestination)
-        
+
         let storyboard = UIStoryboard(name: "Scan", bundle: nil)
         let navigationController = storyboard.instantiateInitialViewController()!
-        
+
         navigationController.modalPresentationStyle = UIModalPresentationStyle.pageSheet
-        
+
         appDelegate.window?.rootViewController?.present(navigationController, animated: true, completion: nil)
     }
-    
+
     // MARK: - Print
-    
+
     func printDocument(metadata: tableMetadata) {
-    
+
         let fileNameURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
-        
+
         if UIPrintInteractionController.canPrint(fileNameURL) {
-            
+
             let printInfo = UIPrintInfo(dictionary: nil)
             printInfo.jobName = fileNameURL.lastPathComponent
             printInfo.outputType = .photo
@@ -305,74 +305,74 @@ import IHProgressHUD
             printController.present(animated: true, completionHandler: nil)
         }
     }
-    
+
     // MARK: - Save photo
-    
+
     func saveAlbum(metadata: tableMetadata) {
-        
+
         let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
         let status = PHPhotoLibrary.authorizationStatus()
 
         if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue && status == PHAuthorizationStatus.authorized {
-            
-            if let image = UIImage.init(contentsOfFile: fileNamePath) {
-                UIImageWriteToSavedPhotosAlbum(image, self, #selector(SaveAlbum(_:didFinishSavingWithError:contextInfo:)), nil)
+
+            if let image = UIImage(contentsOfFile: fileNamePath) {
+                UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveAlbum(_:didFinishSavingWithError:contextInfo:)), nil)
             } else {
                 NCContentPresenter.shared.messageNotification("_save_selected_files_", description: "_file_not_saved_cameraroll_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorFileNotSaved)
             }
-            
+
         } else if metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue && status == PHAuthorizationStatus.authorized {
-            
+
             if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath) {
-                UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, #selector(SaveAlbum(_:didFinishSavingWithError:contextInfo:)), nil)
+                UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, #selector(saveAlbum(_:didFinishSavingWithError:contextInfo:)), nil)
             } else {
                 NCContentPresenter.shared.messageNotification("_save_selected_files_", description: "_file_not_saved_cameraroll_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorFileNotSaved)
             }
-            
+
         } else if status != PHAuthorizationStatus.authorized {
-            
+
             NCContentPresenter.shared.messageNotification("_access_photo_not_enabled_", description: "_access_photo_not_enabled_msg_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorFileNotSaved)
         }
     }
-    
-    @objc private func SaveAlbum(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
-        
+
+    @objc private func saveAlbum(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
+
         if error != nil {
             NCContentPresenter.shared.messageNotification("_save_selected_files_", description: "_file_not_saved_cameraroll_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorFileNotSaved)
         }
     }
-    
+
     func saveLivePhoto(metadata: tableMetadata, metadataMOV: tableMetadata) {
-        
+
         if !CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
             NCOperationQueue.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorSaveAlbumLivePhotoIMG)
         }
-        
+
         if !CCUtility.fileProviderStorageExists(metadataMOV.ocId, fileNameView: metadataMOV.fileNameView) {
             NCOperationQueue.shared.download(metadata: metadataMOV, selector: NCGlobal.shared.selectorSaveAlbumLivePhotoMOV)
         }
-        
+
         if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) && CCUtility.fileProviderStorageExists(metadataMOV.ocId, fileNameView: metadataMOV.fileNameView) {
             saveLivePhotoToDisk(metadata: metadata, metadataMov: metadataMOV)
         }
     }
-    
+
     func saveLivePhotoToDisk(metadata: tableMetadata, metadataMov: tableMetadata) {
-        
+
         let fileNameImage = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
         let fileNameMov = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataMov.ocId, fileNameView: metadataMov.fileNameView)!)
-        
+
         IHProgressHUD.set(defaultMaskType: .clear)
         IHProgressHUD.set(minimumDismiss: 2)
-        
+
         NCLivePhoto.generate(from: fileNameImage, videoURL: fileNameMov, progress: { progress in
-                
+
             IHProgressHUD.show(progress: CGFloat(progress))
-            
-        }, completion: { livePhoto, resources in
-    
+
+        }, completion: { _, resources in
+
             if resources != nil {
-                NCLivePhoto.saveToLibrary(resources!) { (result) in
+                NCLivePhoto.saveToLibrary(resources!) { result in
                     if !result {
                         IHProgressHUD.showError(withStatus: NSLocalizedString("_livephoto_save_error_", comment: ""))
                     } else {
@@ -384,14 +384,14 @@ import IHProgressHUD
             }
         })
     }
-    
+
     func saveBackground(metadata: tableMetadata) {
-        
+
         let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
         let destination = CCUtility.getDirectoryGroup().appendingPathComponent(NCGlobal.shared.appBackground).path + "/" + metadata.fileNameView
-        
+
         if NCUtilityFileSystem.shared.copyFile(atPath: fileNamePath, toPath: destination) {
-            
+
             if appDelegate.activeViewController is NCCollectionViewCommon {
                 let viewController: NCCollectionViewCommon = appDelegate.activeViewController as! NCCollectionViewCommon
                 let layoutKey = viewController.layoutKey
@@ -403,70 +403,70 @@ import IHProgressHUD
             }
         }
     }
-    
+
     // MARK: - Copy & Paste
-    
+
     func copyPasteboard() {
-        
+
         var metadatas: [tableMetadata] = []
-        var items = [[String : Any]]()
-        
+        var items = [[String: Any]]()
+
         for ocId in appDelegate.pasteboardOcIds {
             if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
                 metadatas.append(metadata)
             }
         }
-        
+
         for metadata in metadatas {
-            
+
             if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
                 do {
                     // Get Data
-                    let data = try Data.init(contentsOf: URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)))
+                    let data = try Data(contentsOf: URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)))
                     // Pasteboard item
                     if let unmanagedFileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (metadata.fileNameView as NSString).pathExtension as CFString, nil) {
                         let fileUTI = unmanagedFileUTI.takeRetainedValue() as String
-                        items.append([fileUTI:data])
+                        items.append([fileUTI: data])
                     }
                 } catch {
                     print("error")
                 }
             } else {
-                NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadCopy) { (_) in }
+                NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadCopy) { _ in }
             }
         }
-        
+
         UIPasteboard.general.setItems(items, options: [:])
     }
 
     func pastePasteboard(serverUrl: String) {
-    
+
         var pasteboardTypes: [String] = []
-        
-        func upload(pasteboardType : String?, data: Data?) -> Bool {
-            
+
+        func upload(pasteboardType: String?, data: Data?) -> Bool {
+
             guard let data = data else { return false}
             guard let pasteboardType = pasteboardType else { return false }
-            
+
             let results = NCCommunicationCommon.shared.getFileProperties(inUTI: pasteboardType as CFString)
             if results.ext == "" { return false }
-                
+
             do {
                 let fileName = results.name + "_" + CCUtility.getIncrementalNumber() + "." + results.ext
                 let serverUrlFileName = serverUrl + "/" + fileName
                 let ocIdUpload = UUID().uuidString
                 let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocIdUpload, fileNameView: fileName)!
                 try data.write(to: URL(fileURLWithPath: fileNameLocalPath))
-               
+
                 IHProgressHUD.set(defaultMaskType: .clear)
                 IHProgressHUD.set(minimumDismiss: 2)
 
-                NCCommunication.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath) { task in
+                NCCommunication.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath) { _ in
                 } progressHandler: { progress in
-                    
+
                     IHProgressHUD.show(progress: CGFloat(progress.fractionCompleted), status: fileName)
-                    
-                } completionHandler: { account, ocId, etag, date, size, allHeaderFields, errorCode, errorDescription in
+
+                } completionHandler: { account, ocId, etag, _, _, _, errorCode, errorDescription in
                     if errorCode == 0 && etag != nil && ocId != nil {
                         let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId!, fileNameView: fileName)!
                         NCUtilityFileSystem.shared.moveFile(atPath: fileNameLocalPath, toPath: toPath)
@@ -482,11 +482,11 @@ import IHProgressHUD
             }
             return true
         }
-                
+
         for (index, items) in UIPasteboard.general.items.enumerated() {
 
             for item in items { pasteboardTypes.append(item.key) }
-            
+
             for typeIdentifier in pasteboardTypes {
                 let data = UIPasteboard.general.data(forPasteboardType: typeIdentifier, inItemSet: IndexSet([index]))?.first
                 if upload(pasteboardType: typeIdentifier, data: data) {
@@ -495,21 +495,21 @@ import IHProgressHUD
             }
         }
     }
-    
+
     // MARK: -
-    
+
     func openFileViewInFolder(serverUrl: String, fileName: String) {
-        
+
         let viewController = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as! NCFileViewInFolder
-        let navigationController = UINavigationController.init(rootViewController: viewController)
+        let navigationController = UINavigationController(rootViewController: viewController)
 
         let topViewController = viewController
         var listViewController = [NCFileViewInFolder]()
         var serverUrl = serverUrl
         let homeUrl = NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account)
-        
+
         while true {
-            
+
             var viewController: NCFileViewInFolder?
             if serverUrl != homeUrl {
                 viewController = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as? NCFileViewInFolder
@@ -521,30 +521,30 @@ import IHProgressHUD
                 viewController = topViewController
             }
             guard let vc = viewController else { return }
-            
+
             vc.serverUrl = serverUrl
             vc.fileName = fileName
-            
+
             vc.navigationItem.backButtonTitle = vc.titleCurrentFolder
             listViewController.insert(vc, at: 0)
-            
+
             if serverUrl != homeUrl {
                 serverUrl = NCUtilityFileSystem.shared.deletingLastPathComponent(account: appDelegate.account, serverUrl: serverUrl)
             } else {
                 break
             }
         }
-        
+
         navigationController.setViewControllers(listViewController, animated: false)
         navigationController.modalPresentationStyle = .formSheet
-        
+
         appDelegate.window?.rootViewController?.present(navigationController, animated: true, completion: nil)
     }
-    
+
     // MARK: - NCSelect + Delegate
-    
+
     func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
-        if (serverUrl != nil && items.count > 0) {
+        if serverUrl != nil && items.count > 0 {
             if copy {
                 for metadata in items as! [tableMetadata] {
                     NCOperationQueue.shared.copyMove(metadata: metadata, serverUrl: serverUrl!, overwrite: overwrite, move: false)
@@ -558,19 +558,19 @@ import IHProgressHUD
     }
 
     func openSelectView(items: [Any], viewController: UIViewController) {
-        
-        let navigationController = UIStoryboard.init(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
+
+        let navigationController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
         let topViewController = navigationController.topViewController as! NCSelect
         var listViewController = [NCSelect]()
-        
+
         var copyItems: [Any] = []
         for item in items {
             copyItems.append(item)
         }
-        
+
         let homeUrl = NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account)
         var serverUrl = (copyItems[0] as! Nextcloud.tableMetadata).serverUrl
-        
+
         // Setup view controllers such that the current view is of the same directory the items to be copied are in
         while true {
             // If not in the topmost directory, create a new view controller and set correct title.
@@ -591,28 +591,28 @@ import IHProgressHUD
             vc.typeOfCommandView = .copyMove
             vc.items = copyItems
             vc.serverUrl = serverUrl
-            
+
             vc.navigationItem.backButtonTitle = vc.titleCurrentFolder
             listViewController.insert(vc, at: 0)
-            
+
             if serverUrl != homeUrl {
                 serverUrl = NCUtilityFileSystem.shared.deletingLastPathComponent(account: appDelegate.account, serverUrl: serverUrl)
             } else {
                 break
             }
         }
-        
+
         navigationController.setViewControllers(listViewController, animated: false)
         navigationController.modalPresentationStyle = .formSheet
-        
+
         viewController.present(navigationController, animated: true, completion: nil)
     }
-    
+
     // MARK: - Context Menu Configuration
-    
+
     @available(iOS 13.0, *)
     func contextMenuConfiguration(ocId: String, viewController: UIViewController, enableDeleteLocal: Bool, enableViewInFolder: Bool, image: UIImage?) -> UIMenu {
-        
+
         guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else {
             return UIMenu()
         }
@@ -625,7 +625,7 @@ import IHProgressHUD
             titleSave = NSLocalizedString("_livephoto_save_", comment: "")
         }
         let titleFavorite = metadata.favorite ? NSLocalizedString("_remove_favorites_", comment: "") : NSLocalizedString("_add_favorites_", comment: "")
-        
+
         let serverUrl = metadata.serverUrl + "/" + metadata.fileName
         var isOffline = false
         if metadata.directory {
@@ -638,23 +638,23 @@ import IHProgressHUD
             }
         }
         let titleOffline = isOffline ? NSLocalizedString("_remove_available_offline_", comment: "") :  NSLocalizedString("_set_available_offline_", comment: "")
-        
-        let copy = UIAction(title: NSLocalizedString("_copy_file_", comment: ""), image: UIImage(systemName: "doc.on.doc")) { action in
+
+        let copy = UIAction(title: NSLocalizedString("_copy_file_", comment: ""), image: UIImage(systemName: "doc.on.doc")) { _ in
             self.appDelegate.pasteboardOcIds = [metadata.ocId]
             self.copyPasteboard()
         }
-        
-        let copyPath = UIAction(title: NSLocalizedString("_copy_path_", comment: ""), image: UIImage(systemName: "doc.on.clipboard")) { action in
+
+        let copyPath = UIAction(title: NSLocalizedString("_copy_path_", comment: ""), image: UIImage(systemName: "doc.on.clipboard")) { _ in
             let board = UIPasteboard.general
             board.string = NCUtilityFileSystem.shared.getPath(metadata: metadata)
             NCContentPresenter.shared.messageNotification("", description: "_copied_path_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorNoError)
         }
-        
-        let detail = UIAction(title: NSLocalizedString("_details_", comment: ""), image: UIImage(systemName: "info")) { action in
-            self.openShare(ViewController: viewController, metadata: metadata, indexPage: .activity)
+
+        let detail = UIAction(title: NSLocalizedString("_details_", comment: ""), image: UIImage(systemName: "info")) { _ in
+            self.openShare(viewController: viewController, metadata: metadata, indexPage: .activity)
         }
-        
-        let offline = UIAction(title: titleOffline, image: UIImage(systemName: "tray.and.arrow.down")) { action in
+
+        let offline = UIAction(title: titleOffline, image: UIImage(systemName: "tray.and.arrow.down")) { _ in
             if isOffline {
                 if metadata.directory {
                     NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, offline: false, account: self.appDelegate.account)
@@ -666,19 +666,19 @@ import IHProgressHUD
                     NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, offline: true, account: self.appDelegate.account)
                     NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorDownloadAllFile)
                 } else {
-                    NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadOffline) { (_) in }
+                    NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadOffline) { _ in }
                     if let metadataLivePhoto = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
-                        NCNetworking.shared.download(metadata: metadataLivePhoto, selector: NCGlobal.shared.selectorLoadOffline) { (_) in }
+                        NCNetworking.shared.download(metadata: metadataLivePhoto, selector: NCGlobal.shared.selectorLoadOffline) { _ in }
                     }
                 }
             }
-            
+
             if viewController is NCCollectionViewCommon {
                 (viewController as! NCCollectionViewCommon).reloadDataSource()
             }
         }
-        
-        let save = UIAction(title: titleSave, image: UIImage(systemName: "square.and.arrow.down")) { action in
+
+        let save = UIAction(title: titleSave, image: UIImage(systemName: "square.and.arrow.down")) { _ in
             if metadataMOV != nil {
                 self.saveLivePhoto(metadata: metadata, metadataMOV: metadataMOV!)
             } else {
@@ -689,120 +689,120 @@ import IHProgressHUD
                 }
             }
         }
-        
-        let saveBackground = UIAction(title: NSLocalizedString("_use_as_background_", comment: ""), image: UIImage(systemName: "text.below.photo")) { action in
+
+        let saveBackground = UIAction(title: NSLocalizedString("_use_as_background_", comment: ""), image: UIImage(systemName: "text.below.photo")) { _ in
             if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
                 self.saveBackground(metadata: metadata)
             } else {
                 NCOperationQueue.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorSaveBackground)
             }
         }
-        
-        let viewInFolder = UIAction(title: NSLocalizedString("_view_in_folder_", comment: ""), image: UIImage(systemName: "arrow.forward.square")) { action in
+
+        let viewInFolder = UIAction(title: NSLocalizedString("_view_in_folder_", comment: ""), image: UIImage(systemName: "arrow.forward.square")) { _ in
             self.openFileViewInFolder(serverUrl: metadata.serverUrl, fileName: metadata.fileName)
         }
-        
-        let openIn = UIAction(title: NSLocalizedString("_open_in_", comment: ""), image: UIImage(systemName: "square.and.arrow.up") ) { action in
+
+        let openIn = UIAction(title: NSLocalizedString("_open_in_", comment: ""), image: UIImage(systemName: "square.and.arrow.up") ) { _ in
             self.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorOpenIn)
         }
-        
-        let print = UIAction(title: NSLocalizedString("_print_", comment: ""), image: UIImage(systemName: "printer") ) { action in
+
+        let print = UIAction(title: NSLocalizedString("_print_", comment: ""), image: UIImage(systemName: "printer") ) { _ in
             self.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorPrint)
         }
-        
-        let modify = UIAction(title: NSLocalizedString("_modify_", comment: ""), image: UIImage(systemName: "pencil.tip.crop.circle")) { action in
+
+        let modify = UIAction(title: NSLocalizedString("_modify_", comment: ""), image: UIImage(systemName: "pencil.tip.crop.circle")) { _ in
             self.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorLoadFileQuickLook)
         }
-        
-        let saveAsScan = UIAction(title: NSLocalizedString("_save_as_scan_", comment: ""), image: UIImage(systemName: "viewfinder.circle")) { action in
+
+        let saveAsScan = UIAction(title: NSLocalizedString("_save_as_scan_", comment: ""), image: UIImage(systemName: "viewfinder.circle")) { _ in
             self.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorSaveAsScan)
         }
-        
-        //let open = UIMenu(title: NSLocalizedString("_open_", comment: ""), image: UIImage(systemName: "square.and.arrow.up"), children: [openIn, openQuickLook])
-        
-        let moveCopy = UIAction(title: NSLocalizedString("_move_or_copy_", comment: ""), image: UIImage(systemName: "arrow.up.right.square")) { action in
+
+        // let open = UIMenu(title: NSLocalizedString("_open_", comment: ""), image: UIImage(systemName: "square.and.arrow.up"), children: [openIn, openQuickLook])
+
+        let moveCopy = UIAction(title: NSLocalizedString("_move_or_copy_", comment: ""), image: UIImage(systemName: "arrow.up.right.square")) { _ in
             self.openSelectView(items: [metadata], viewController: viewController)
         }
-        
-        let rename = UIAction(title: NSLocalizedString("_rename_", comment: ""), image: UIImage(systemName: "pencil")) { action in
-            
+
+        let rename = UIAction(title: NSLocalizedString("_rename_", comment: ""), image: UIImage(systemName: "pencil")) { _ in
+
             if let vcRename = UIStoryboard(name: "NCRenameFile", bundle: nil).instantiateInitialViewController() as? NCRenameFile {
-                
+
                 vcRename.metadata = metadata
                 vcRename.imagePreview = image
 
                 let popup = NCPopupViewController(contentController: vcRename, popupWidth: vcRename.width, popupHeight: vcRename.height)
-                                            
+
                 viewController.present(popup, animated: true)
             }
         }
-        
-        let favorite = UIAction(title: titleFavorite, image: NCUtility.shared.loadImage(named: "star.fill", color: NCBrandColor.shared.yellowFavorite)) { action in
-            
-            NCNetworking.shared.favoriteMetadata(metadata) { (errorCode, errorDescription) in
+
+        let favorite = UIAction(title: titleFavorite, image: NCUtility.shared.loadImage(named: "star.fill", color: NCBrandColor.shared.yellowFavorite)) { _ in
+
+            NCNetworking.shared.favoriteMetadata(metadata) { errorCode, errorDescription in
                 if errorCode != 0 {
                     NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
                 }
             }
         }
-        
-        let deleteConfirmFile = UIAction(title: titleDeleteConfirmFile, image: UIImage(systemName: "trash"), attributes: .destructive) { action in
-            NCNetworking.shared.deleteMetadata(metadata, onlyLocalCache: false) { (errorCode, errorDescription) in
+
+        let deleteConfirmFile = UIAction(title: titleDeleteConfirmFile, image: UIImage(systemName: "trash"), attributes: .destructive) { _ in
+            NCNetworking.shared.deleteMetadata(metadata, onlyLocalCache: false) { errorCode, errorDescription in
                 if errorCode != 0 {
                     NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
                 }
             }
         }
-        
-        let deleteConfirmLocal = UIAction(title: NSLocalizedString("_remove_local_file_", comment: ""), image: UIImage(systemName: "trash"), attributes: .destructive) { action in
-            NCNetworking.shared.deleteMetadata(metadata, onlyLocalCache: true) { (errorCode, errorDescription) in
+
+        let deleteConfirmLocal = UIAction(title: NSLocalizedString("_remove_local_file_", comment: ""), image: UIImage(systemName: "trash"), attributes: .destructive) { _ in
+            NCNetworking.shared.deleteMetadata(metadata, onlyLocalCache: true) { _, _ in
             }
         }
-        
+
         var delete = UIMenu(title: NSLocalizedString("_delete_file_", comment: ""), image: UIImage(systemName: "trash"), options: .destructive, children: [deleteConfirmLocal, deleteConfirmFile])
-        
+
         if !enableDeleteLocal {
             delete = UIMenu(title: NSLocalizedString("_delete_file_", comment: ""), image: UIImage(systemName: "trash"), options: .destructive, children: [deleteConfirmFile])
         }
-        
+
         if metadata.directory {
             delete = UIMenu(title: NSLocalizedString("_delete_folder_", comment: ""), image: UIImage(systemName: "trash"), options: .destructive, children: [deleteConfirmFile])
         }
-        
+
         // ------ MENU -----
-        
+
         // DIR
-        
+
         if metadata.directory {
-            
+
             let submenu = UIMenu(title: "", options: .displayInline, children: [favorite, offline, rename, moveCopy, copyPath, delete])
             return UIMenu(title: "", children: [detail, submenu])
         }
-        
+
         // FILE
-        
+
         var children: [UIMenuElement] = [favorite, offline, openIn, rename, moveCopy, copy, copyPath, delete]
 
         if (metadata.contentType != "image/svg+xml") && (metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue) {
             children.insert(save, at: 2)
         }
-        
+
         if (metadata.contentType != "image/svg+xml") && (metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue) {
             children.insert(saveAsScan, at: 2)
         }
-        
+
         if (metadata.contentType != "image/svg+xml") && (metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue || metadata.contentType == "application/pdf" || metadata.contentType == "com.adobe.pdf") {
             children.insert(print, at: 2)
         }
-        
+
         if enableViewInFolder {
             children.insert(viewInFolder, at: children.count-1)
         }
-        
+
         if (!isFolderEncrypted && metadata.contentType != "image/gif" && metadata.contentType != "image/svg+xml") && (metadata.contentType == "com.adobe.pdf" || metadata.contentType == "application/pdf" || metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue) {
             children.insert(modify, at: children.count-1)
         }
-        
+
         if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue && viewController is NCCollectionViewCommon && !NCBrandOptions.shared.disable_background_image {
             let viewController: NCCollectionViewCommon = viewController as! NCCollectionViewCommon
             let layoutKey = viewController.layoutKey
@@ -810,9 +810,8 @@ import IHProgressHUD
                 children.insert(saveBackground, at: children.count-1)
             }
         }
-        
+
         let submenu = UIMenu(title: "", options: .displayInline, children: children)
         return UIMenu(title: "", children: [detail, submenu])
     }
 }
-

+ 17 - 19
iOSClient/Main/NCMainNavigationController.swift

@@ -24,55 +24,53 @@
 import UIKit
 
 class NCMainNavigationController: UINavigationController {
-    
-    private let appDelegate = UIApplication.shared.delegate as! AppDelegate
 
     // MARK: - View Life Cycle
 
     required init?(coder: NSCoder) {
         super.init(coder: coder)
-        
+
         NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
-        
+
         changeTheming()
     }
-    
+
     override func viewDidLayoutSubviews() {
         super.viewDidLayoutSubviews()
     }
-    
+
     override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
         super.traitCollectionDidChange(previousTraitCollection)
-        
+
         changeTheming()
     }
-    
+
     // MARK: - Theming
-    
+
     @objc func changeTheming() {
-        
+
         if #available(iOS 13.0, *) {
-            
+
             let appearance = UINavigationBarAppearance()
-            
+
             appearance.configureWithOpaqueBackground()
-            appearance.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor : NCBrandColor.shared.label]
+            appearance.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: NCBrandColor.shared.label]
             appearance.backgroundColor = NCBrandColor.shared.systemBackground
             appearance.configureWithOpaqueBackground()
-            appearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor : NCBrandColor.shared.label]
+            appearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor: NCBrandColor.shared.label]
             appearance.backgroundColor = NCBrandColor.shared.systemBackground
 
             navigationBar.scrollEdgeAppearance = appearance
             navigationBar.standardAppearance = appearance
-            
+
         } else {
-            
+
             navigationBar.barStyle = .default
             navigationBar.barTintColor = NCBrandColor.shared.systemBackground
-            navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:NCBrandColor.shared.label]
-            navigationBar.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor:NCBrandColor.shared.label]
+            navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: NCBrandColor.shared.label]
+            navigationBar.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: NCBrandColor.shared.label]
         }
-        
+
         navigationBar.tintColor = .systemBlue
         navigationBar.setNeedsLayout()
     }

+ 34 - 35
iOSClient/Main/NCMainTabBar.swift

@@ -29,40 +29,40 @@ class NCMainTabBar: UITabBar {
     private var shapeLayer: CALayer?
     private let appDelegate = UIApplication.shared.delegate as! AppDelegate
     private var timer: Timer?
-    
+
     public var menuRect: CGRect {
         get {
             let tabBarItemWidth = Int(self.frame.size.width) / (self.items?.count ?? 0)
             let rect = CGRect(x: 0, y: -5, width: tabBarItemWidth, height: Int(self.frame.size.height))
-            
+
             return rect
         }
     }
-    
+
     // MARK: - Life Cycle
 
     required init?(coder: NSCoder) {
         super.init(coder: coder)
-        
+
         appDelegate.mainTabBar = self
         timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: (#selector(updateBadgeNumber)), userInfo: nil, repeats: true)
-            
+
         NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
         NotificationCenter.default.addObserver(self, selector: #selector(updateBadgeNumber), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUpdateBadgeNumber), object: nil)
 
         barTintColor = NCBrandColor.shared.secondarySystemBackground
         backgroundColor = NCBrandColor.shared.secondarySystemBackground
-        
+
         changeTheming()
     }
-    
+
     @objc func changeTheming() {
         tintColor = NCBrandColor.shared.brandElement
         if let centerButton = self.viewWithTag(99) {
             centerButton.backgroundColor = NCBrandColor.shared.brandElement
-        }        
+        }
     }
-    
+
     override var backgroundColor: UIColor? {
         get {
             return self.fillColor
@@ -72,7 +72,7 @@ class NCMainTabBar: UITabBar {
             self.setNeedsDisplay()
         }
     }
-        
+
     override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
         let button = self.viewWithTag(99)
         if self.bounds.contains(point) || (button != nil && button!.frame.contains(point)) {
@@ -84,7 +84,7 @@ class NCMainTabBar: UITabBar {
 
     override func layoutSubviews() {
         super.layoutSubviews()
-        
+
         layer.shadowPath = createPath()
         layer.shadowRadius = 5
         layer.shadowOffset = .zero
@@ -97,7 +97,7 @@ class NCMainTabBar: UITabBar {
     }
 
     private func addShape() {
-        
+
         let shapeLayer = CAShapeLayer()
         shapeLayer.path = createPath()
         shapeLayer.fillColor = backgroundColor?.cgColor
@@ -111,9 +111,9 @@ class NCMainTabBar: UITabBar {
 
         self.shapeLayer = shapeLayer
     }
-    
+
     private func createPath() -> CGPath {
-        
+
         let height: CGFloat = 28
         let margin: CGFloat = 6
         let path = UIBezierPath()
@@ -131,54 +131,54 @@ class NCMainTabBar: UITabBar {
 
         return path.cgPath
     }
-    
+
     private func createButtons() {
-       
+
         // File
         if let item = items?[0] {
             item.title = NSLocalizedString("_home_", comment: "")
             item.image = UIImage(named: "tabBarFiles")?.image(color: NCBrandColor.shared.brandElement, size: 25)
             item.selectedImage = item.image
         }
-        
+
         // Favorite
         if let item = items?[1] {
             item.title = NSLocalizedString("_favorites_", comment: "")
             item.image = UIImage(named: "tabBarFavorites")?.image(color: NCBrandColor.shared.brandElement, size: 25)
             item.selectedImage = item.image
         }
-        
+
         // +
         if let item = items?[2] {
             item.title = ""
             item.image = nil
             item.isEnabled = false
         }
-        
+
         // Media
         if let item = items?[3] {
             item.title = NSLocalizedString("_media_", comment: "")
             item.image = UIImage(named: "tabBarMedia")?.image(color: NCBrandColor.shared.brandElement, size: 25)
             item.selectedImage = item.image
         }
-        
+
         // More
         if let item = items?[4] {
             item.title = NSLocalizedString("_more_", comment: "")
             item.image = UIImage(named: "tabBarMore")?.image(color: NCBrandColor.shared.brandElement, size: 25)
             item.selectedImage = item.image
         }
-        
+
         // Center button
-        
+
         if let centerButton = self.viewWithTag(99) {
             centerButton.removeFromSuperview()
         }
         let centerButtonHeight: CGFloat = 57
         let centerButtonY: CGFloat = -28
-        
+
         let centerButton = UIButton(frame: CGRect(x: (self.bounds.width / 2)-(centerButtonHeight/2), y: centerButtonY, width: centerButtonHeight, height: centerButtonHeight))
-        
+
         centerButton.setTitle("", for: .normal)
         centerButton.setImage(UIImage(named: "tabBarPlus")?.image(color: .white, size: 100), for: .normal)
         centerButton.backgroundColor = NCBrandColor.shared.brandElement
@@ -191,33 +191,33 @@ class NCMainTabBar: UITabBar {
         centerButton.layer.shadowRadius = 3.0
         centerButton.layer.shadowOpacity = 0.5
         centerButton.action(for: .touchUpInside) { _ in
-            
+
             if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.appDelegate.activeServerUrl)) {
-                
+
                 if !directory.permissions.contains("CK") {
                     NCContentPresenter.shared.messageNotification("_warning_", description: "_no_permission_add_file_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorInternalError)
                     return
                 }
             }
-            
+
             if let viewController = self.window?.rootViewController {
                 self.appDelegate.toggleMenu(viewController: viewController)
             }
         }
-        
+
         self.addSubview(centerButton)
     }
-    
+
     @objc func updateBadgeNumber() {
-        
+
         if appDelegate.account == "" { return }
-        
+
         let counterDownload = NCOperationQueue.shared.downloadCount()
         let counterUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status == %d OR status == %d OR status == %d", NCGlobal.shared.metadataStatusWaitUpload, NCGlobal.shared.metadataStatusInUpload, NCGlobal.shared.metadataStatusUploading)).count
         let total = counterDownload + counterUpload
-        
+
         UIApplication.shared.applicationIconBadgeNumber = total
-        
+
         if let item = items?[0] {
             if total > 0 {
                 item.badgeValue = String(total)
@@ -226,7 +226,7 @@ class NCMainTabBar: UITabBar {
             }
         }
     }
-    
+
     func getCenterButton() -> UIView? {
         if let centerButton = self.viewWithTag(99) {
             return centerButton
@@ -235,4 +235,3 @@ class NCMainTabBar: UITabBar {
         }
     }
 }
-

+ 46 - 48
iOSClient/Main/NCPickerViewController.swift

@@ -25,7 +25,7 @@ import UIKit
 import TLPhotoPicker
 import MobileCoreServices
 
-//MARK: - Photo Picker
+// MARK: - Photo Picker
 
 class NCPhotosPickerViewController: NSObject {
 
@@ -38,65 +38,65 @@ class NCPhotosPickerViewController: NSObject {
     init(viewController: UIViewController, maxSelectedAssets: Int, singleSelectedMode: Bool) {
         sourceViewController = viewController
         super.init()
-        
+
         self.maxSelectedAssets = maxSelectedAssets
         self.singleSelectedMode = singleSelectedMode
-        
-        self.openPhotosPickerViewController { (assets) in
+
+        self.openPhotosPickerViewController { assets in
             guard let assets = assets else { return }
             if assets.count > 0 {
-                
-                let form = NCCreateFormUploadAssets.init(serverUrl: self.appDelegate.activeServerUrl, assets: assets, cryptated: false, session: NCNetworking.shared.sessionIdentifierBackground, delegate: nil)
-                let navigationController = UINavigationController.init(rootViewController: form)
-                
+
+                let form = NCCreateFormUploadAssets(serverUrl: self.appDelegate.activeServerUrl, assets: assets, cryptated: false, session: NCNetworking.shared.sessionIdentifierBackground, delegate: nil)
+                let navigationController = UINavigationController(rootViewController: form)
+
                 DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
                     viewController.present(navigationController, animated: true, completion: nil)
                 }
             }
         }
     }
-    
-    private func openPhotosPickerViewController(completition: @escaping ([PHAsset]?) -> ()) {
-        
+
+    private func openPhotosPickerViewController(completition: @escaping ([PHAsset]?) -> Void) {
+
         var selectedAssets: [PHAsset] = []
         var configure = TLPhotosPickerConfigure()
-        
+
         configure.cancelTitle = NSLocalizedString("_cancel_", comment: "")
         configure.doneTitle = NSLocalizedString("_done_", comment: "")
         configure.emptyMessage = NSLocalizedString("_no_albums_", comment: "")
         configure.tapHereToChange = NSLocalizedString("_tap_here_to_change_", comment: "")
-        
+
         if maxSelectedAssets > 0 {
             configure.maxSelectedAssets = maxSelectedAssets
         }
         configure.selectedColor = NCBrandColor.shared.brandElement
         configure.singleSelectedMode = singleSelectedMode
         configure.allowedAlbumCloudShared = true
-        
-        let viewController = customPhotoPickerViewController(withTLPHAssets: { (assets) in
-            
+
+        let viewController = customPhotoPickerViewController(withTLPHAssets: { assets in
+
             for asset: TLPHAsset in assets {
                 if asset.phAsset != nil {
                     selectedAssets.append(asset.phAsset!)
                 }
             }
-            
+
             completition(selectedAssets)
-            
+
         }, didCancel: nil)
-        
-        viewController.didExceedMaximumNumberOfSelection = { (picker) in
+
+        viewController.didExceedMaximumNumberOfSelection = { _ in
             NCContentPresenter.shared.messageNotification("_info_", description: "_limited_dimension_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError)
         }
-        
-        viewController.handleNoAlbumPermissions = { (picker) in
+
+        viewController.handleNoAlbumPermissions = { _ in
             NCContentPresenter.shared.messageNotification("_info_", description: "_denied_album_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError)
         }
-        
-        viewController.handleNoCameraPermissions = { (picker) in
+
+        viewController.handleNoCameraPermissions = { _ in
             NCContentPresenter.shared.messageNotification("_info_", description: "_denied_camera_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError)
         }
-        
+
         viewController.configure = configure
 
         sourceViewController.present(viewController, animated: true, completion: nil)
@@ -104,78 +104,76 @@ class NCPhotosPickerViewController: NSObject {
 }
 
 class customPhotoPickerViewController: TLPhotosPickerViewController {
-    
+
     override var preferredStatusBarStyle: UIStatusBarStyle {
         return .lightContent
     }
-    
+
     override func makeUI() {
         super.makeUI()
-        
+
         self.customNavItem.leftBarButtonItem?.tintColor = .systemBlue
         self.customNavItem.rightBarButtonItem?.tintColor = .systemBlue
     }
 }
 
-//MARK: - Document Picker
+// MARK: - Document Picker
 
 class NCDocumentPickerViewController: NSObject, UIDocumentPickerDelegate {
 
     let appDelegate = UIApplication.shared.delegate as! AppDelegate
-    
+
     @discardableResult
     init (tabBarController: UITabBarController) {
         super.init()
-          
+
         let documentProviderMenu = UIDocumentPickerViewController(documentTypes: ["public.data"], in: .import)
-        
+
         documentProviderMenu.modalPresentationStyle = .formSheet
         documentProviderMenu.allowsMultipleSelection = true
         documentProviderMenu.popoverPresentationController?.sourceView = tabBarController.tabBar
         documentProviderMenu.popoverPresentationController?.sourceRect = tabBarController.tabBar.bounds
         documentProviderMenu.delegate = self
-        
+
         appDelegate.window?.rootViewController?.present(documentProviderMenu, animated: true, completion: nil)
     }
-    
+
     func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
-    
+
         for url in urls {
-            
+
             let fileName = url.lastPathComponent
             let serverUrl = appDelegate.activeServerUrl
             let ocId = NSUUID().uuidString
             let atPath = url.path
             let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
-            
+
             if NCUtilityFileSystem.shared.copyFile(atPath: atPath, toPath: toPath) {
-                
+
                 let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate.account, user: appDelegate.user, userId: appDelegate.userId, fileName: fileName, fileNameView: fileName, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: "", livePhoto: false)
-                
+
                 metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
                 metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile
                 metadataForUpload.size = NCUtilityFileSystem.shared.getFileSize(filePath: toPath)
                 metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
-                
+
                 if NCManageDatabase.shared.getMetadataConflict(account: appDelegate.account, serverUrl: serverUrl, fileName: fileName) != nil {
-                    
-                    if let conflict = UIStoryboard.init(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict {
-                        
+
+                    if let conflict = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict {
+
                         conflict.serverUrl = serverUrl
                         conflict.metadatasUploadInConflict = [metadataForUpload]
-                    
+
                         appDelegate.window?.rootViewController?.present(conflict, animated: true, completion: nil)
                     }
-                
+
                 } else {
                     appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: [metadataForUpload])
                 }
-                
+
             } else {
                 NCContentPresenter.shared.messageNotification("_error_", description: "_read_file_error_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError)
             }
         }
     }
 }
-
-

+ 38 - 38
iOSClient/Main/Section Header Footer/NCSectionHeaderFooter.swift

@@ -25,7 +25,7 @@ import UIKit
 import MarkdownKit
 
 class NCSectionHeaderMenu: UICollectionReusableView, UIGestureRecognizerDelegate {
-    
+
     @IBOutlet weak var buttonMore: UIButton!
     @IBOutlet weak var buttonSwitch: UIButton!
     @IBOutlet weak var buttonOrder: UIButton!
@@ -35,35 +35,35 @@ class NCSectionHeaderMenu: UICollectionReusableView, UIGestureRecognizerDelegate
     @IBOutlet weak var textViewRichWorkspace: UITextView!
     @IBOutlet weak var separator: UIView!
     @IBOutlet weak var separatorHeightConstraint: NSLayoutConstraint!
-    
-    var delegate: NCSectionHeaderMenuDelegate?
+
+    weak var delegate: NCSectionHeaderMenuDelegate?
 
     private var markdownParser = MarkdownParser()
     private var richWorkspaceText: String?
     private var textViewColor: UIColor?
-    private let gradient : CAGradientLayer = CAGradientLayer()
-    
+    private let gradient: CAGradientLayer = CAGradientLayer()
+
     override func awakeFromNib() {
         super.awakeFromNib()
-        
+
         backgroundColor = .clear
-        
-        buttonSwitch.setImage(UIImage.init(named: "switchList")!.image(color: NCBrandColor.shared.gray, size: 25), for: .normal)
-        
+
+        buttonSwitch.setImage(UIImage(named: "switchList")!.image(color: NCBrandColor.shared.gray, size: 25), for: .normal)
+
         buttonOrder.setTitle("", for: .normal)
         buttonOrder.setTitleColor(.systemBlue, for: .normal)
-        buttonMore.setImage(UIImage.init(named: "more")!.image(color:  NCBrandColor.shared.gray, size: 25), for: .normal)
-                
+        buttonMore.setImage(UIImage(named: "more")!.image(color: NCBrandColor.shared.gray, size: 25), for: .normal)
+
         // Gradient
         gradient.startPoint = CGPoint(x: 0, y: 0.50)
         gradient.endPoint = CGPoint(x: 0, y: 1)
         viewRichWorkspace.layer.addSublayer(gradient)
         setGradientColor()
-        
+
         let tap = UITapGestureRecognizer(target: self, action: #selector(touchUpInsideViewRichWorkspace(_:)))
         tap.delegate = self
         viewRichWorkspace?.addGestureRecognizer(tap)
-        
+
         separator.backgroundColor = NCBrandColor.shared.separator
         separatorHeightConstraint.constant = 0.5
 
@@ -74,36 +74,36 @@ class NCSectionHeaderMenu: UICollectionReusableView, UIGestureRecognizerDelegate
         }
         textViewColor = NCBrandColor.shared.label
     }
-    
+
     override func layoutSublayers(of layer: CALayer) {
         super.layoutSublayers(of: layer)
         gradient.frame = viewRichWorkspace.bounds
     }
-    
+
     override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
         super.traitCollectionDidChange(previousTraitCollection)
         setGradientColor()
     }
-    
+
     func setGradientColor() {
         if traitCollection.userInterfaceStyle == .dark {
-            gradient.colors = [UIColor.init(white: 0, alpha: 0).cgColor, UIColor.black.cgColor]
+            gradient.colors = [UIColor(white: 0, alpha: 0).cgColor, UIColor.black.cgColor]
         } else {
-            gradient.colors = [UIColor.init(white: 1, alpha: 0).cgColor, UIColor.white.cgColor]
+            gradient.colors = [UIColor(white: 1, alpha: 0).cgColor, UIColor.white.cgColor]
         }
     }
-    
+
     func setTitleSorted(datasourceTitleButton: String) {
-        
+
         let title = NSLocalizedString(datasourceTitleButton, comment: "")
-        let size = title.size(withAttributes:[.font: buttonOrder.titleLabel?.font as Any])
-        
+        let size = title.size(withAttributes: [.font: buttonOrder.titleLabel?.font as Any])
+
         buttonOrder.setTitle(title, for: .normal)
         buttonOrderWidthConstraint.constant = size.width + 5
     }
-    
+
     func setStatusButton(count: Int) {
-        
+
         if count == 0 {
             buttonSwitch.isEnabled = false
             buttonOrder.isEnabled = false
@@ -114,7 +114,7 @@ class NCSectionHeaderMenu: UICollectionReusableView, UIGestureRecognizerDelegate
             buttonMore.isEnabled = true
         }
     }
-    
+
     func setRichWorkspaceText(richWorkspaceText: String?) {
         guard let richWorkspaceText = richWorkspaceText else { return }
         if richWorkspaceText != self.richWorkspaceText {
@@ -122,25 +122,25 @@ class NCSectionHeaderMenu: UICollectionReusableView, UIGestureRecognizerDelegate
             self.richWorkspaceText = richWorkspaceText
         }
     }
-    
+
     @IBAction func touchUpInsideMore(_ sender: Any) {
         delegate?.tapMoreHeader(sender: sender)
     }
-    
+
     @IBAction func touchUpInsideSwitch(_ sender: Any) {
         delegate?.tapSwitchHeader(sender: sender)
     }
-    
+
     @IBAction func touchUpInsideOrder(_ sender: Any) {
         delegate?.tapOrderHeader(sender: sender)
     }
-    
+
     @objc func touchUpInsideViewRichWorkspace(_ sender: Any) {
         delegate?.tapRichWorkspace(sender: sender)
     }
 }
 
-protocol NCSectionHeaderMenuDelegate {
+protocol NCSectionHeaderMenuDelegate: AnyObject {
     func tapSwitchHeader(sender: Any)
     func tapMoreHeader(sender: Any)
     func tapOrderHeader(sender: Any)
@@ -156,33 +156,33 @@ extension NCSectionHeaderMenuDelegate {
 }
 
 class NCSectionFooter: UICollectionReusableView {
-    
+
     @IBOutlet weak var labelSection: UILabel!
-    
+
     override func awakeFromNib() {
         super.awakeFromNib()
-        
+
         self.backgroundColor = UIColor.clear
         labelSection.textColor = NCBrandColor.shared.gray
     }
-    
+
     func setTitleLabel(directories: Int, files: Int, size: Int64) {
-        
+
         var foldersText = ""
         var filesText = ""
-        
+
         if directories > 1 {
             foldersText = "\(directories) " + NSLocalizedString("_folders_", comment: "")
         } else if directories == 1 {
             foldersText = "1 " + NSLocalizedString("_folder_", comment: "")
         }
-        
+
         if files > 1 {
             filesText = "\(files) " + NSLocalizedString("_files_", comment: "") + " " + CCUtility.transformedSize(size)
         } else if files == 1 {
             filesText = "1 " + NSLocalizedString("_file_", comment: "") + " " + CCUtility.transformedSize(size)
         }
-        
+
         if foldersText == "" {
             labelSection.text = filesText
         } else if filesText == "" {

+ 6 - 7
iOSClient/Media/Cell/NCGridMediaCell.swift

@@ -29,10 +29,10 @@ class NCGridMediaCell: UICollectionViewCell, NCCellProtocol {
     @IBOutlet weak var imageVisualEffect: UIVisualEffectView!
     @IBOutlet weak var imageSelect: UIImageView!
     @IBOutlet weak var imageStatus: UIImageView!
-    
+
     private var objectId: String = ""
     private var user: String = ""
-    
+
     var date: Date?
 
     var filePreviewImageView: UIImageView? {
@@ -61,7 +61,7 @@ class NCGridMediaCell: UICollectionViewCell, NCCellProtocol {
             user = newValue ?? ""
         }
     }
-    
+
     override func awakeFromNib() {
         super.awakeFromNib()
         initCell()
@@ -71,7 +71,7 @@ class NCGridMediaCell: UICollectionViewCell, NCCellProtocol {
         super.prepareForReuse()
         initCell()
     }
-    
+
     func initCell() {
         imageItem.backgroundColor = UIColor.lightGray
         imageStatus.image = nil
@@ -81,7 +81,7 @@ class NCGridMediaCell: UICollectionViewCell, NCCellProtocol {
         imageVisualEffect.layer.cornerRadius = 6
         imageVisualEffect.clipsToBounds = true
     }
-    
+
     func selectMode(_ status: Bool) {
         if status {
             imageSelect.isHidden = false
@@ -90,7 +90,7 @@ class NCGridMediaCell: UICollectionViewCell, NCCellProtocol {
             imageVisualEffect.isHidden = true
         }
     }
-    
+
     func selected(_ status: Bool) {
         if status {
             imageSelect.image = NCBrandColor.cacheImages.checkedYes
@@ -102,4 +102,3 @@ class NCGridMediaCell: UICollectionViewCell, NCCellProtocol {
         }
     }
 }
-

+ 179 - 182
iOSClient/Media/NCMedia.swift

@@ -25,15 +25,15 @@ import UIKit
 import NCCommunication
 
 class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate {
-    
-    @IBOutlet weak var collectionView : UICollectionView!
-    
+
+    @IBOutlet weak var collectionView: UICollectionView!
+
     private var emptyDataSet: NCEmptyDataSet?
     private var mediaCommandView: NCMediaCommandView?
     private var gridLayout: NCGridMediaLayout!
 
     internal let appDelegate = UIApplication.shared.delegate as! AppDelegate
-    
+
     public var metadatas: [tableMetadata] = []
     private var account: String = ""
 
@@ -42,57 +42,57 @@ class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate {
 
     internal var isEditMode = false
     internal var selectOcId: [String] = []
-    
+
     internal var filterClassTypeImage = false
     internal var filterClassTypeVideo = false
-            
+
     private let maxImageGrid: CGFloat = 7
     private var cellHeigth: CGFloat = 0
 
     private var oldInProgress = false
     private var newInProgress = false
-    
+
     private var lastContentOffsetY: CGFloat = 0
     private var mediaPath = ""
     private var livePhoto: Bool = false
-    
+
     private var timeIntervalSearchNewMedia: TimeInterval = 3.0
     private var timerSearchNewMedia: Timer?
-    
+
     private let insetsTop: CGFloat = 75
-        
+
     struct cacheImages {
         static var cellLivePhotoImage = UIImage()
         static var cellPlayImage = UIImage()
     }
-    
+
     // MARK: - View Life Cycle
 
     override func viewDidLoad() {
         super.viewDidLoad()
-        
+
         appDelegate.activeMedia = self
-        
+
         view.backgroundColor = NCBrandColor.shared.systemBackground
 
-        collectionView.register(UINib.init(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
-        
+        collectionView.register(UINib(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
+
         collectionView.alwaysBounceVertical = true
-        collectionView.contentInset = UIEdgeInsets(top: insetsTop, left: 0, bottom: 50, right: 0);
+        collectionView.contentInset = UIEdgeInsets(top: insetsTop, left: 0, bottom: 50, right: 0)
         collectionView.backgroundColor = NCBrandColor.shared.systemBackground
-                
+
         gridLayout = NCGridMediaLayout()
         gridLayout.itemForLine = CGFloat(min(CCUtility.getMediaWidthImage(), 5))
         gridLayout.sectionHeadersPinToVisibleBounds = true
 
         collectionView.collectionViewLayout = gridLayout
-        
+
         // Empty
-        emptyDataSet = NCEmptyDataSet.init(view: collectionView, offset: 0, delegate: self)
-      
+        emptyDataSet = NCEmptyDataSet(view: collectionView, offset: 0, delegate: self)
+
         // Notification
         NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
-            
+
         mediaCommandView = Bundle.main.loadNibNamed("NCMediaCommandView", owner: self, options: nil)?.first as? NCMediaCommandView
         self.view.addSubview(mediaCommandView!)
         mediaCommandView?.mediaView = self
@@ -105,60 +105,60 @@ class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate {
         mediaCommandView?.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
         mediaCommandView?.heightAnchor.constraint(equalToConstant: 150).isActive = true
         self.updateMediaControlVisibility()
-        
+
         collectionView.prefetchDataSource = self
-        
+
         cacheImages.cellLivePhotoImage = NCUtility.shared.loadImage(named: "livephoto", color: .white)
         cacheImages.cellPlayImage = NCUtility.shared.loadImage(named: "play.fill", color: .white)
     }
-    
+
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
-        
+
         appDelegate.activeViewController = self
-        
+
         //
         NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
         NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
         NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
         NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
-        
+
         // hide nagigation controller
         navigationController?.navigationBar.prefersLargeTitles = true
         navigationController?.setNavigationBarHidden(true, animated: false)
-        
-        self.reloadDataSourceWithCompletion { (_) in
+
+        self.reloadDataSourceWithCompletion { _ in
             self.timerSearchNewMedia?.invalidate()
             self.timerSearchNewMedia = Timer.scheduledTimer(timeInterval: self.timeIntervalSearchNewMedia, target: self, selector: #selector(self.searchNewMediaTimer), userInfo: nil, repeats: false)
         }
     }
-    
+
     override func viewWillDisappear(_ animated: Bool) {
         super.viewWillDisappear(animated)
-        
+
         NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
         NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
         NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
         NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
     }
-    
+
     override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
         super.viewWillTransition(to: size, with: coordinator)
-        
+
         coordinator.animate(alongsideTransition: nil) { _ in
             self.reloadDataThenPerform { }
         }
     }
-    
+
     override var preferredStatusBarStyle: UIStatusBarStyle {
         return .lightContent
     }
-    
-    //MARK: - NotificationCenter
+
+    // MARK: - NotificationCenter
 
     @objc func initialize() {
-        
-        self.reloadDataSourceWithCompletion { (_) in
+
+        self.reloadDataSourceWithCompletion { _ in
             self.timerSearchNewMedia?.invalidate()
             self.timerSearchNewMedia = Timer.scheduledTimer(timeInterval: self.timeIntervalSearchNewMedia, target: self, selector: #selector(self.searchNewMediaTimer), userInfo: nil, repeats: false)
             DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
@@ -166,82 +166,82 @@ class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate {
             }
         }
     }
-    
+
     @objc func deleteFile(_ notification: NSNotification) {
-        
+
         if let userInfo = notification.userInfo as NSDictionary? {
             if let ocId = userInfo["ocId"] as? String {
-          
+
                 let indexes = self.metadatas.indices.filter { self.metadatas[$0].ocId == ocId }
                 let metadatas = self.metadatas.filter { $0.ocId != ocId }
                 self.metadatas = metadatas
-                
+
                 if self.metadatas.count == 0 {
                     collectionView?.reloadData()
                 } else if let row = indexes.first {
                     let indexPath = IndexPath(row: row, section: 0)
                     collectionView?.deleteItems(at: [indexPath])
                 }
-                
+
                 self.updateMediaControlVisibility()
             }
         }
     }
-    
+
     @objc func moveFile(_ notification: NSNotification) {
-        
+
         if let userInfo = notification.userInfo as NSDictionary? {
             if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
-                
+
                 if metadata.account == appDelegate.account {
-                    
+
                     let indexes = self.metadatas.indices.filter { self.metadatas[$0].ocId == metadata.ocId }
                     let metadatas = self.metadatas.filter { $0.ocId != metadata.ocId }
                     self.metadatas = metadatas
-                    
+
                     if self.metadatas.count == 0 {
                         collectionView?.reloadData()
                     } else if let row = indexes.first {
                         let indexPath = IndexPath(row: row, section: 0)
                         collectionView?.deleteItems(at: [indexPath])
                     }
-                    
+
                     self.updateMediaControlVisibility()
                 }
             }
         }
     }
-    
+
     @objc func renameFile(_ notification: NSNotification) {
-        
+
         if let userInfo = notification.userInfo as NSDictionary? {
             if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
-                
+
                 if metadata.account == appDelegate.account {
-                    self.reloadDataSourceWithCompletion { (_) in }
+                    self.reloadDataSourceWithCompletion { _ in }
                 }
             }
         }
     }
-    
+
     @objc func uploadedFile(_ notification: NSNotification) {
-        
+
         if let userInfo = notification.userInfo as NSDictionary? {
             if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId), let errorCode = userInfo["errorCode"] as? Int {
                 if errorCode == 0 && metadata.account == appDelegate.account {
-                    self.reloadDataSourceWithCompletion { (_) in }
+                    self.reloadDataSourceWithCompletion { _ in }
                 }
             }
         }
     }
-    
-    //MARK: - Command
-    
+
+    // MARK: - Command
+
     func mediaCommandTitle() {
         mediaCommandView?.title.text = ""
-        
+
         if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
-        
+
             if let cell = visibleCells.first as? NCGridMediaCell {
                 if cell.date != nil {
                     mediaCommandView?.title.text = CCUtility.getTitleSectionDate(cell.date)
@@ -249,14 +249,14 @@ class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate {
             }
         }
     }
-    
+
     @objc func zoomOutGrid() {
         UIView.animate(withDuration: 0.0, animations: {
-            if(self.gridLayout.itemForLine + 1 < self.maxImageGrid) {
+            if self.gridLayout.itemForLine + 1 < self.maxImageGrid {
                 self.gridLayout.itemForLine += 1
                 self.mediaCommandView?.zoomInButton.isEnabled = true
             }
-            if(self.gridLayout.itemForLine == self.maxImageGrid - 1) {
+            if self.gridLayout.itemForLine == self.maxImageGrid - 1 {
                 self.mediaCommandView?.zoomOutButton.isEnabled = false
             }
 
@@ -267,11 +267,11 @@ class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate {
 
     @objc func zoomInGrid() {
         UIView.animate(withDuration: 0.0, animations: {
-            if(self.gridLayout.itemForLine - 1 > 0) {
+            if self.gridLayout.itemForLine - 1 > 0 {
                 self.gridLayout.itemForLine -= 1
                 self.mediaCommandView?.zoomOutButton.isEnabled = true
             }
-            if(self.gridLayout.itemForLine == 1) {
+            if self.gridLayout.itemForLine == 1 {
                 self.mediaCommandView?.zoomInButton.isEnabled = false
             }
 
@@ -279,28 +279,28 @@ class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate {
             CCUtility.setMediaWidthImage(Int(self.gridLayout.itemForLine))
         })
     }
-    
+
     @objc func openMenuButtonMore(_ sender: Any) {
         toggleMenu()
     }
-    
+
     // MARK: Select Path
-    
+
     func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
         if serverUrl != nil {
             let path = CCUtility.returnPathfromServerUrl(serverUrl, urlBase: appDelegate.urlBase, account: appDelegate.account) ?? ""
             NCManageDatabase.shared.setAccountMediaPath(path, account: appDelegate.account)
-            reloadDataSourceWithCompletion { (_) in
+            reloadDataSourceWithCompletion { _ in
                 self.searchNewMedia()
             }
         }
     }
-    
+
     // MARK: - Empty
-    
+
     func emptyDataSetView(_ view: NCEmptyView) {
-        
-        view.emptyImage.image = UIImage.init(named: "media")?.image(color: .gray, size: UIScreen.main.bounds.width)
+
+        view.emptyImage.image = UIImage(named: "media")?.image(color: .gray, size: UIScreen.main.bounds.width)
         if oldInProgress || newInProgress {
             view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
         } else {
@@ -313,11 +313,11 @@ class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate {
 // MARK: - Collection View
 
 extension NCMedia: UICollectionViewDelegate {
-    
+
     func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
-        
+
         let metadata = metadatas[indexPath.row]
-        
+
         if isEditMode {
             if let index = selectOcId.firstIndex(of: metadata.ocId) {
                 selectOcId.remove(at: index)
@@ -327,38 +327,38 @@ extension NCMedia: UICollectionViewDelegate {
             if indexPath.section <  collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
                 collectionView.reloadItems(at: [indexPath])
             }
-            
+
         } else {
-            
+
             // ACTIVE SERVERURL
             appDelegate.activeServerUrl = metadata.serverUrl
             let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as? NCGridMediaCell
             NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: metadatas, imageIcon: cell?.imageItem.image)
         }
     }
-    
+
     @available(iOS 13.0, *)
     func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
-        
+
         let metadata = metadatas[indexPath.row]
         let identifier = indexPath as NSCopying
         if let cell = collectionView.cellForItem(at: indexPath) as? NCGridMediaCell {
-        
+
             let image = cell.imageItem.image
 
             return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
-                
+
                 return NCViewerProviderContextMenu(metadata: metadata, image: image)
-                
-            }, actionProvider: { suggestedActions in
-                
+
+            }, actionProvider: { _ in
+
                 return NCFunctionCenter.shared.contextMenuConfiguration(ocId: metadata.ocId, viewController: self, enableDeleteLocal: false, enableViewInFolder: true, image: image)
             })
         } else {
             return nil
         }
     }
-    
+
     @available(iOS 13.0, *)
     func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
         animator.addCompletion {
@@ -372,19 +372,19 @@ extension NCMedia: UICollectionViewDelegate {
 
 extension NCMedia: UICollectionViewDataSourcePrefetching {
     func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
-        //print("[LOG] n. " + String(indexPaths.count))
+        // print("[LOG] n. " + String(indexPaths.count))
     }
 }
 
 extension NCMedia: UICollectionViewDataSource {
-    
+
     func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
         CATransaction.begin()
         CATransaction.setCompletionBlock(closure)
         collectionView?.reloadData()
         CATransaction.commit()
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
         emptyDataSet?.numberOfItemsInSection(metadatas.count, section: section)
         return metadatas.count
@@ -393,16 +393,16 @@ extension NCMedia: UICollectionViewDataSource {
     func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
         if indexPath.row < self.metadatas.count {
             let metadata = self.metadatas[indexPath.row]
-            
+
             if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
                 (cell as! NCGridMediaCell).imageItem.backgroundColor = nil
-                (cell as! NCGridMediaCell).imageItem.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
+                (cell as! NCGridMediaCell).imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
             } else {
                 NCOperationQueue.shared.downloadThumbnail(metadata: metadata, placeholder: false, cell: cell, view: collectionView)
             }
         }
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
         if !collectionView.indexPathsForVisibleItems.contains(indexPath) && indexPath.row < metadatas.count {
             let metadata = metadatas[indexPath.row]
@@ -411,12 +411,12 @@ extension NCMedia: UICollectionViewDataSource {
     }
 
     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
-        
+
         if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) && indexPath.row < metadatas.count {
-        
+
             let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
             let metadata = metadatas[indexPath.row]
-            
+
             self.cellHeigth = cell.frame.size.height
 
             cell.date = metadata.date as Date
@@ -428,7 +428,7 @@ extension NCMedia: UICollectionViewDataSource {
             } else if metadata.livePhoto && livePhoto {
                 cell.imageStatus.image = cacheImages.cellLivePhotoImage
             }
-            
+
             if isEditMode {
                 cell.selectMode(true)
                 if selectOcId.contains(metadata.ocId) {
@@ -439,22 +439,22 @@ extension NCMedia: UICollectionViewDataSource {
             } else {
                 cell.selectMode(false)
             }
-            
+
             return cell
-            
+
         } else {
-            
+
             return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
         }
     }
 }
 
 extension NCMedia: UICollectionViewDelegateFlowLayout {
-    
+
     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
         return CGSize(width: collectionView.frame.width, height: 0)
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
         return CGSize(width: collectionView.frame.width, height: 0)
     }
@@ -465,24 +465,24 @@ extension NCMedia {
     // MARK: - Datasource
 
     @objc func reloadDataSourceWithCompletion(_ completion: @escaping (_ metadatas: [tableMetadata]) -> Void) {
-        
+
         if appDelegate.account == "" { return }
-        
+
         if account != appDelegate.account {
             self.metadatas = []
             account = appDelegate.account
             collectionView?.reloadData()
         }
-        
+
         livePhoto = CCUtility.getLivePhoto()
-        
+
         if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
             self.mediaPath = activeAccount.mediaPath
         }
         let startServerUrl = NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account) + mediaPath
-        
+
         predicateDefault = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND (classFile == %@ OR classFile == %@) AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NCCommunicationCommon.typeClassFile.image.rawValue, NCCommunicationCommon.typeClassFile.video.rawValue)
-        
+
         if filterClassTypeImage {
             predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND classFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NCCommunicationCommon.typeClassFile.video.rawValue)
         } else if filterClassTypeVideo {
@@ -490,14 +490,14 @@ extension NCMedia {
         } else {
             predicate = predicateDefault
         }
-        
+
         guard var predicateForGetMetadatasMedia = predicate else { return }
-        
+
         if livePhoto {
             let predicateLivePhoto = NSPredicate(format: "!(ext == 'mov' AND livePhoto == true)")
-            predicateForGetMetadatasMedia = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicateForGetMetadatasMedia, predicateLivePhoto])
+            predicateForGetMetadatasMedia = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateForGetMetadatasMedia, predicateLivePhoto])
         }
-              
+
         DispatchQueue.global().async {
             self.metadatas = NCManageDatabase.shared.getMetadatasMedia(predicate: predicateForGetMetadatasMedia, sort: CCUtility.getMediaSortDate())
             DispatchQueue.main.sync {
@@ -509,7 +509,7 @@ extension NCMedia {
             }
         }
     }
-    
+
     func updateMediaControlVisibility() {
         if self.metadatas.count == 0 {
             if !self.filterClassTypeImage && !self.filterClassTypeVideo {
@@ -524,13 +524,12 @@ extension NCMedia {
             self.mediaCommandView?.isHidden = false
         }
     }
-    
+
     // MARK: - Search media
 
     private func searchOldMedia(value: Int = -30, limit: Int = 300) {
-        
-        if oldInProgress { return }
-        else { oldInProgress = true }
+
+        if oldInProgress { return } else { oldInProgress = true }
         collectionView.reloadData()
 
         var lessDate = Date()
@@ -539,34 +538,34 @@ extension NCMedia {
                 lessDate = metadata.date as Date
             }
         }
-        
+
         var greaterDate: Date
         if value == -999 {
             greaterDate = Date.distantPast
         } else {
-            greaterDate = Calendar.current.date(byAdding: .day, value:value, to: lessDate)!
+            greaterDate = Calendar.current.date(byAdding: .day, value: value, to: lessDate)!
         }
-        
+
         let height = self.tabBarController?.tabBar.frame.size.height ?? 0
         NCUtility.shared.startActivityIndicator(backgroundView: self.view, blurEffect: false, bottom: height + 50, style: .gray)
 
-        NCCommunication.shared.searchMedia(path: mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), timeout: 120) { (account, files, errorCode, errorDescription) in
-            
+        NCCommunication.shared.searchMedia(path: mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), timeout: 120) { account, files, errorCode, errorDescription in
+
             self.oldInProgress = false
             NCUtility.shared.stopActivityIndicator()
             self.collectionView.reloadData()
 
             if errorCode == 0 && account == self.appDelegate.account {
                 if files.count > 0 {
-                    NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: self.appDelegate.account) { (_, _, metadatas) in
+                    NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: self.appDelegate.account) { _, _, metadatas in
                         let predicateDate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
-                        let predicateResult = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicateDate, self.predicateDefault!])
+                        let predicateResult = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateDate, self.predicateDefault!])
                         let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: predicateResult)
                         let metadatasChanged = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
                         if metadatasChanged.metadatasUpdate.count == 0 {
                             self.researchOldMedia(value: value, limit: limit, withElseReloadDataSource: true)
                         } else {
-                            self.reloadDataSourceWithCompletion { (_) in }
+                            self.reloadDataSourceWithCompletion { _ in }
                         }
                     }
                 } else {
@@ -577,9 +576,9 @@ extension NCMedia {
             }
         }
     }
-    
-    private func researchOldMedia(value: Int , limit: Int, withElseReloadDataSource: Bool) {
-        
+
+    private func researchOldMedia(value: Int, limit: Int, withElseReloadDataSource: Bool) {
+
         if value == -30 {
             searchOldMedia(value: -90)
         } else if value == -90 {
@@ -590,23 +589,22 @@ extension NCMedia {
             searchOldMedia(value: -999, limit: 0)
         } else {
             if withElseReloadDataSource {
-                self.reloadDataSourceWithCompletion { (_) in }
+                self.reloadDataSourceWithCompletion { _ in }
             }
         }
     }
-    
+
     @objc func searchNewMediaTimer() {
         self.searchNewMedia()
     }
-    
+
     @objc func searchNewMedia() {
-        
-        if newInProgress { return }
-        else {
+
+        if newInProgress { return } else {
             newInProgress = true
             mediaCommandView?.activityIndicator.startAnimating()
         }
-        
+
         var limit: Int = 1000
         guard var lessDate = Calendar.current.date(byAdding: .second, value: 1, to: Date()) else { return }
         guard var greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return }
@@ -626,22 +624,22 @@ extension NCMedia {
                 }
             }
         }
-        
+
         reloadDataThenPerform {
 
-            NCCommunication.shared.searchMedia(path: self.mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), timeout: 120) { (account, files, errorCode, errorDescription) in
-                
+            NCCommunication.shared.searchMedia(path: self.mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), timeout: 120) { account, files, errorCode, errorDescription in
+
                 self.newInProgress = false
                 self.mediaCommandView?.activityIndicator.stopAnimating()
-                
+
                 if errorCode == 0 && account == self.appDelegate.account && files.count > 0 {
-                    NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { (_, _, metadatas) in
+                    NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { _, _, metadatas in
                         let predicate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
-                        let predicateResult = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicate, self.predicate!])
+                        let predicateResult = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, self.predicate!])
                         let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: predicateResult)
                         let updateMetadatas = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
                         if updateMetadatas.metadatasUpdate.count > 0 || updateMetadatas.metadatasDelete.count > 0 {
-                            self.reloadDataSourceWithCompletion { (_) in }
+                            self.reloadDataSourceWithCompletion { _ in }
                         }
                     }
                 } else if errorCode == 0 && files.count == 0 && self.metadatas.count == 0 {
@@ -657,41 +655,41 @@ extension NCMedia {
 // MARK: - ScrollView
 
 extension NCMedia: UIScrollViewDelegate {
-    
+
     func scrollViewDidScroll(_ scrollView: UIScrollView) {
-        
+
         if lastContentOffsetY == 0 || lastContentOffsetY + cellHeigth/2 <= scrollView.contentOffset.y  || lastContentOffsetY - cellHeigth/2 >= scrollView.contentOffset.y {
 
             mediaCommandTitle()
             lastContentOffsetY = scrollView.contentOffset.y
         }
     }
-    
+
     func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
         mediaCommandView?.collapseControlButtonView(true)
     }
-    
+
     func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
-        
+
         if !decelerate {
             timerSearchNewMedia?.invalidate()
             timerSearchNewMedia = Timer.scheduledTimer(timeInterval: timeIntervalSearchNewMedia, target: self, selector: #selector(searchNewMediaTimer), userInfo: nil, repeats: false)
-            
-            if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
+
+            if scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height) {
                 searchOldMedia()
             }
         }
     }
-    
+
     func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
         timerSearchNewMedia?.invalidate()
         timerSearchNewMedia = Timer.scheduledTimer(timeInterval: timeIntervalSearchNewMedia, target: self, selector: #selector(searchNewMediaTimer), userInfo: nil, repeats: false)
-        
-        if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
+
+        if scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height) {
             searchOldMedia()
         }
     }
-    
+
     func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
         let y = view.safeAreaInsets.top
         scrollView.contentOffset.y = -(insetsTop + y)
@@ -701,7 +699,7 @@ extension NCMedia: UIScrollViewDelegate {
 // MARK: - Media Command View
 
 class NCMediaCommandView: UIView {
-    
+
     @IBOutlet weak var moreView: UIVisualEffectView!
     @IBOutlet weak var gridSwitchButton: UIButton!
     @IBOutlet weak var separatorView: UIView!
@@ -710,12 +708,12 @@ class NCMediaCommandView: UIView {
     @IBOutlet weak var zoomOutButton: UIButton!
     @IBOutlet weak var moreButton: UIButton!
     @IBOutlet weak var controlButtonView: UIVisualEffectView!
-    @IBOutlet weak var title : UILabel!
-    @IBOutlet weak var activityIndicator : UIActivityIndicatorView!
+    @IBOutlet weak var title: UILabel!
+    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
 
-    var mediaView:NCMedia?
+    var mediaView: NCMedia?
     private let gradient: CAGradientLayer = CAGradientLayer()
-    
+
     override func awakeFromNib() {
         moreView.layer.cornerRadius = 20
         moreView.layer.masksToBounds = true
@@ -724,12 +722,12 @@ class NCMediaCommandView: UIView {
         gradient.frame = bounds
         gradient.startPoint = CGPoint(x: 0, y: 0.50)
         gradient.endPoint = CGPoint(x: 0, y: 0.9)
-        gradient.colors = [UIColor.black.withAlphaComponent(0.4).cgColor , UIColor.clear.cgColor]
+        gradient.colors = [UIColor.black.withAlphaComponent(0.4).cgColor, UIColor.clear.cgColor]
         layer.insertSublayer(gradient, at: 0)
-        moreButton.setImage(UIImage.init(named: "more")!.image(color: .white, size: 25), for: .normal)
+        moreButton.setImage(UIImage(named: "more")!.image(color: .white, size: 25), for: .normal)
         title.text = ""
     }
-    
+
     func toggleEmptyView(isEmpty: Bool) {
         if isEmpty {
             UIView.animate(withDuration: 0.3) {
@@ -745,25 +743,25 @@ class NCMediaCommandView: UIView {
             }
         }
     }
-    
+
     @IBAction func moreButtonPressed(_ sender: UIButton) {
         mediaView?.openMenuButtonMore(sender)
     }
-    
+
     @IBAction func zoomInPressed(_ sender: UIButton) {
         mediaView?.zoomInGrid()
     }
-    
+
     @IBAction func zoomOutPressed(_ sender: UIButton) {
         mediaView?.zoomOutGrid()
     }
-    
+
     @IBAction func gridSwitchButtonPressed(_ sender: Any) {
         self.collapseControlButtonView(false)
     }
-    
+
     func collapseControlButtonView(_ collapse: Bool) {
-        if (collapse) {
+        if collapse {
             self.buttonControlWidthConstraint.constant = 40
             UIView.animate(withDuration: 0.25) {
                 self.zoomOutButton.isHidden = true
@@ -783,11 +781,11 @@ class NCMediaCommandView: UIView {
             }
         }
     }
-    
+
     override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
         return moreView.frame.contains(point) || controlButtonView.frame.contains(point)
     }
-    
+
     override func layoutSublayers(of layer: CALayer) {
         super.layoutSublayers(of: layer)
         gradient.frame = bounds
@@ -797,36 +795,36 @@ class NCMediaCommandView: UIView {
 // MARK: - Media Grid Layout
 
 class NCGridMediaLayout: UICollectionViewFlowLayout {
-    
+
     var marginLeftRight: CGFloat = 6
     var itemForLine: CGFloat = 3
-    
+
     override init() {
         super.init()
-        
+
         sectionHeadersPinToVisibleBounds = false
-        
+
         minimumInteritemSpacing = 0
         minimumLineSpacing = marginLeftRight
-        
+
         self.scrollDirection = .vertical
-        self.sectionInset = UIEdgeInsets(top: 0, left: marginLeftRight, bottom: 0, right:  marginLeftRight)
+        self.sectionInset = UIEdgeInsets(top: 0, left: marginLeftRight, bottom: 0, right: marginLeftRight)
     }
-    
+
     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
-    
+
     override var itemSize: CGSize {
         get {
             if let collectionView = collectionView {
-                
+
                 let itemWidth: CGFloat = (collectionView.frame.width - marginLeftRight * 2 - marginLeftRight * (itemForLine - 1)) / itemForLine
                 let itemHeight: CGFloat = itemWidth
-                
+
                 return CGSize(width: itemWidth, height: itemHeight)
             }
-            
+
             // Default fallback
             return CGSize(width: 100, height: 100)
         }
@@ -834,9 +832,8 @@ class NCGridMediaLayout: UICollectionViewFlowLayout {
             super.itemSize = newValue
         }
     }
-    
+
     override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
         return proposedContentOffset
     }
 }
-

+ 41 - 41
iOSClient/Menu/AppDelegate+Menu.swift

@@ -28,21 +28,21 @@ import FloatingPanel
 import NCCommunication
 
 extension AppDelegate {
-    
+
     func toggleMenu(viewController: UIViewController) {
-        
+
         var actions: [NCMenuAction] = []
-        
+
         let appDelegate = UIApplication.shared.delegate as! AppDelegate
         let directEditingCreators = NCManageDatabase.shared.getDirectEditingCreators(account: appDelegate.account)
         let isEncrypted = CCUtility.isFolderEncrypted(appDelegate.activeServerUrl, e2eEncrypted: false, account: appDelegate.account, urlBase: appDelegate.urlBase)
         let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, appDelegate.activeServerUrl))
         let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
-        
+
         actions.append(
             NCMenuAction(
-                title: NSLocalizedString("_upload_photos_videos_", comment: ""), icon: UIImage(named: "file_photo")!.image(color: NCBrandColor.shared.gray, size: 50), action: { menuAction in
-                    NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { (hasPermission) in
+                title: NSLocalizedString("_upload_photos_videos_", comment: ""), icon: UIImage(named: "file_photo")!.image(color: NCBrandColor.shared.gray, size: 50), action: { _ in
+                    NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { hasPermission in
                         if hasPermission {
                             NCPhotosPickerViewController.init(viewController: viewController, maxSelectedAssets: 0, singleSelectedMode: false)
                         }
@@ -53,9 +53,9 @@ extension AppDelegate {
 
         actions.append(
             NCMenuAction(
-                title: NSLocalizedString("_upload_file_", comment: ""), icon: UIImage(named: "file")!.image(color: NCBrandColor.shared.gray, size: 50), action: { menuAction in
+                title: NSLocalizedString("_upload_file_", comment: ""), icon: UIImage(named: "file")!.image(color: NCBrandColor.shared.gray, size: 50), action: { _ in
                     if let tabBarController = self.window?.rootViewController as? UITabBarController {
-                        self.documentPickerViewController = NCDocumentPickerViewController.init(tabBarController: tabBarController)
+                        self.documentPickerViewController = NCDocumentPickerViewController(tabBarController: tabBarController)
                     }
                 }
             )
@@ -64,12 +64,12 @@ extension AppDelegate {
         if NCCommunication.shared.isNetworkReachable() && directEditingCreators != nil && directEditingCreators!.contains(where: { $0.editor == NCGlobal.shared.editorText}) && !isEncrypted {
             let directEditingCreator = directEditingCreators!.first(where: { $0.editor == NCGlobal.shared.editorText})!
             actions.append(
-                NCMenuAction(title: NSLocalizedString("_create_nextcloudtext_document_", comment: ""), icon: UIImage(named: "file_txt")!.image(color: NCBrandColor.shared.gray, size: 50), action: { menuAction in
+                NCMenuAction(title: NSLocalizedString("_create_nextcloudtext_document_", comment: ""), icon: UIImage(named: "file_txt")!.image(color: NCBrandColor.shared.gray, size: 50), action: { _ in
                     guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController() else {
                         return
                     }
                     navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
-                    
+
                     let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadDocuments
                     viewController.editorId = NCGlobal.shared.editorText
                     viewController.creatorId = directEditingCreator.identifier
@@ -80,12 +80,12 @@ extension AppDelegate {
                     appDelegate.window?.rootViewController?.present(navigationController, animated: true, completion: nil)
                 })
             )
-        } 
-        
+        }
+
         if #available(iOS 13.0, *) {
             actions.append(
                 NCMenuAction(
-                    title: NSLocalizedString("_scans_document_", comment: ""), icon: NCUtility.shared.loadImage(named: "doc.text.viewfinder"), action: { menuAction in
+                    title: NSLocalizedString("_scans_document_", comment: ""), icon: NCUtility.shared.loadImage(named: "doc.text.viewfinder"), action: { _ in
                         if let viewController = appDelegate.window?.rootViewController {
                             NCCreateScanDocument.shared.openScannerDocument(viewController: viewController)
                         }
@@ -93,21 +93,21 @@ extension AppDelegate {
                 )
             )
         }
-        
+
         actions.append(
             NCMenuAction(
-                title: NSLocalizedString("_create_voice_memo_", comment: ""), icon: UIImage(named: "microphone")!.image(color: NCBrandColor.shared.gray, size: 50), action: { menuAction in
-                    
-                    NCAskAuthorization.shared.askAuthorizationAudioRecord(viewController: viewController) { (hasPermission) in
+                title: NSLocalizedString("_create_voice_memo_", comment: ""), icon: UIImage(named: "microphone")!.image(color: NCBrandColor.shared.gray, size: 50), action: { _ in
+
+                    NCAskAuthorization.shared.askAuthorizationAudioRecord(viewController: viewController) { hasPermission in
                         if hasPermission {
                             let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
                             let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
-                        
+
                             viewController.delegate = self
                             viewController.createRecorder(fileName: fileName)
                             viewController.modalTransitionStyle = .crossDissolve
                             viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
-                        
+
                             appDelegate.window?.rootViewController?.present(viewController, animated: true, completion: nil)
                         }
                     }
@@ -117,27 +117,27 @@ extension AppDelegate {
 
         actions.append(
             NCMenuAction(title: NSLocalizedString("_create_folder_", comment: ""),
-                icon: UIImage(named: "folder")!.image(color: NCBrandColor.shared.brandElement, size: 50), action: { menuAction in
-                    
+                icon: UIImage(named: "folder")!.image(color: NCBrandColor.shared.brandElement, size: 50), action: { _ in
+
                     if appDelegate.activeServerUrl == "" { return }
-                    
+
                     let alertController = UIAlertController(title: NSLocalizedString("_create_folder_on_", comment: ""), message: nil, preferredStyle: .alert)
-                    
-                    alertController.addTextField { (textField) in
+
+                    alertController.addTextField { textField in
                         textField.autocapitalizationType = UITextAutocapitalizationType.sentences
                     }
-                    
+
                     let cancelAction = UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil)
-                    let okAction = UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in
+                    let okAction = UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
                         if let fileNameFolder = alertController.textFields?.first?.text {
-                            NCNetworking.shared.createFolder(fileName: fileNameFolder, serverUrl: appDelegate.activeServerUrl, account: appDelegate.account, urlBase: appDelegate.urlBase, overwrite: false) { (errorCode, errorDescription) in
+                            NCNetworking.shared.createFolder(fileName: fileNameFolder, serverUrl: appDelegate.activeServerUrl, account: appDelegate.account, urlBase: appDelegate.urlBase, overwrite: false) { errorCode, errorDescription in
                                 if errorCode != 0 {
                                 NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
                                 }
                             }
                         }
                     })
-                    
+
                     alertController.addAction(cancelAction)
                     alertController.addAction(okAction)
 
@@ -149,7 +149,7 @@ extension AppDelegate {
         if serverVersionMajor >= NCGlobal.shared.nextcloudVersion18 && directory?.richWorkspace == nil && !isEncrypted && NCCommunication.shared.isNetworkReachable() {
             actions.append(
                 NCMenuAction(
-                    title: NSLocalizedString("_add_folder_info_", comment: ""), icon: UIImage(named: "addFolderInfo")!.image(color: NCBrandColor.shared.gray, size: 50), action: { menuAction in
+                    title: NSLocalizedString("_add_folder_info_", comment: ""), icon: UIImage(named: "addFolderInfo")!.image(color: NCBrandColor.shared.gray, size: 50), action: { _ in
                         let richWorkspaceCommon = NCRichWorkspaceCommon()
                         if let viewController = self.activeViewController {
                             if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", appDelegate.account, appDelegate.activeServerUrl, NCGlobal.shared.fileNameRichWorkspace.lowercased())) == nil {
@@ -162,12 +162,12 @@ extension AppDelegate {
                 )
             )
         }
-               
+
         if NCCommunication.shared.isNetworkReachable() && directEditingCreators != nil && directEditingCreators!.contains(where: { $0.editor == NCGlobal.shared.editorOnlyoffice && $0.identifier == NCGlobal.shared.onlyofficeDocx}) && !isEncrypted {
             let directEditingCreator = directEditingCreators!.first(where: { $0.editor == NCGlobal.shared.editorOnlyoffice && $0.identifier == NCGlobal.shared.onlyofficeDocx})!
             actions.append(
                 NCMenuAction(
-                    title: NSLocalizedString("_create_new_document_", comment: ""), icon: UIImage(named: "create_file_document")!, action: { menuAction in
+                    title: NSLocalizedString("_create_new_document_", comment: ""), icon: UIImage(named: "create_file_document")!, action: { _ in
                         guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController() else {
                             return
                         }
@@ -185,12 +185,12 @@ extension AppDelegate {
                 )
             )
         }
-        
+
         if NCCommunication.shared.isNetworkReachable() && directEditingCreators != nil && directEditingCreators!.contains(where: { $0.editor == NCGlobal.shared.editorOnlyoffice && $0.identifier == NCGlobal.shared.onlyofficeXlsx}) && !isEncrypted {
             let directEditingCreator = directEditingCreators!.first(where: { $0.editor == NCGlobal.shared.editorOnlyoffice && $0.identifier == NCGlobal.shared.onlyofficeXlsx})!
             actions.append(
                 NCMenuAction(
-                    title: NSLocalizedString("_create_new_spreadsheet_", comment: ""), icon: UIImage(named: "create_file_xls")!, action: { menuAction in
+                    title: NSLocalizedString("_create_new_spreadsheet_", comment: ""), icon: UIImage(named: "create_file_xls")!, action: { _ in
                         guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController() else {
                             return
                         }
@@ -208,12 +208,12 @@ extension AppDelegate {
                 )
             )
         }
-        
+
         if NCCommunication.shared.isNetworkReachable() && directEditingCreators != nil && directEditingCreators!.contains(where: { $0.editor == NCGlobal.shared.editorOnlyoffice && $0.identifier == NCGlobal.shared.onlyofficePptx}) && !isEncrypted {
             let directEditingCreator = directEditingCreators!.first(where: { $0.editor == NCGlobal.shared.editorOnlyoffice && $0.identifier == NCGlobal.shared.onlyofficePptx})!
             actions.append(
                 NCMenuAction(
-                    title: NSLocalizedString("_create_new_presentation_", comment: ""), icon: UIImage(named: "create_file_ppt")!, action: { menuAction in
+                    title: NSLocalizedString("_create_new_presentation_", comment: ""), icon: UIImage(named: "create_file_ppt")!, action: { _ in
                         guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController() else {
                             return
                         }
@@ -231,12 +231,12 @@ extension AppDelegate {
                 )
             )
         }
-        
+
         if let richdocumentsMimetypes = NCManageDatabase.shared.getCapabilitiesServerArray(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesRichdocumentsMimetypes) {
             if richdocumentsMimetypes.count > 0 &&  NCCommunication.shared.isNetworkReachable() && !isEncrypted {
                 actions.append(
                     NCMenuAction(
-                        title: NSLocalizedString("_create_new_document_", comment: ""), icon: UIImage(named: "create_file_document")!, action: { menuAction in
+                        title: NSLocalizedString("_create_new_document_", comment: ""), icon: UIImage(named: "create_file_document")!, action: { _ in
                             guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController() else {
                                 return
                             }
@@ -255,7 +255,7 @@ extension AppDelegate {
 
                 actions.append(
                     NCMenuAction(
-                        title: NSLocalizedString("_create_new_spreadsheet_", comment: ""), icon: UIImage(named: "create_file_xls")!, action: { menuAction in
+                        title: NSLocalizedString("_create_new_spreadsheet_", comment: ""), icon: UIImage(named: "create_file_xls")!, action: { _ in
                             guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController() else {
                                 return
                             }
@@ -271,10 +271,10 @@ extension AppDelegate {
                         }
                     )
                 )
-                
+
                 actions.append(
                     NCMenuAction(
-                        title: NSLocalizedString("_create_new_presentation_", comment: ""), icon: UIImage(named: "create_file_ppt")!, action: { menuAction in
+                        title: NSLocalizedString("_create_new_presentation_", comment: ""), icon: UIImage(named: "create_file_ppt")!, action: { _ in
                             guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController() else {
                                 return
                             }
@@ -292,7 +292,7 @@ extension AppDelegate {
                 )
             }
         }
-        
+
         viewController.presentMenu(with: actions)
     }
 }

+ 74 - 76
iOSClient/Menu/NCCollectionViewCommon+Menu.swift

@@ -39,7 +39,7 @@ extension NCCollectionViewCommon {
         let isFolderEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase)
         let serverUrlHome = NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account)
         var isOffline = false
-        
+
         var titleDelete = NSLocalizedString("_delete_", comment: "")
         if NCManageDatabase.shared.isMetadataShareOrMounted(metadata: metadata, metadataFolder: metadataFolder) {
             titleDelete = NSLocalizedString("_leave_share_", comment: "")
@@ -48,7 +48,7 @@ extension NCCollectionViewCommon {
         } else {
             titleDelete = NSLocalizedString("_delete_file_", comment: "")
         }
-        
+
         if let metadataFolder = metadataFolder {
             let isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionShared)
             let isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionMounted)
@@ -56,7 +56,7 @@ extension NCCollectionViewCommon {
                 titleDelete = NSLocalizedString("_leave_share_", comment: "")
             }
         }
-               
+
         if metadata.directory {
             if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl)) {
                 isOffline = directory.offline
@@ -66,12 +66,12 @@ extension NCCollectionViewCommon {
                 isOffline = localFile.offline
             }
         }
-        
+
         let editors = NCUtility.shared.isDirectEditing(account: metadata.account, contentType: metadata.contentType)
         let isRichDocument = NCUtility.shared.isRichDocument(metadata)
 
         var iconHeader: UIImage!
-        
+
         if imageIcon != nil {
             iconHeader = imageIcon!
         } else {
@@ -81,7 +81,7 @@ extension NCCollectionViewCommon {
                 iconHeader = NCBrandColor.cacheImages.file
             }
         }
-        
+
         actions.append(
             NCMenuAction(
                 title: metadata.fileNameView,
@@ -97,8 +97,8 @@ extension NCCollectionViewCommon {
             NCMenuAction(
                 title: metadata.favorite ? NSLocalizedString("_remove_favorites_", comment: "") : NSLocalizedString("_add_favorites_", comment: ""),
                 icon: NCUtility.shared.loadImage(named: "star.fill", color: NCBrandColor.shared.yellowFavorite),
-                action: { menuAction in
-                    NCNetworking.shared.favoriteMetadata(metadata) { (errorCode, errorDescription) in
+                action: { _ in
+                    NCNetworking.shared.favoriteMetadata(metadata) { errorCode, errorDescription in
                         if errorCode != 0 {
                             NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
                         }
@@ -106,7 +106,7 @@ extension NCCollectionViewCommon {
                 }
             )
         )
-        
+
         //
         // DETAIL
         //
@@ -115,13 +115,13 @@ extension NCCollectionViewCommon {
                 NCMenuAction(
                     title: NSLocalizedString("_details_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "info"),
-                    action: { menuAction in
-                        NCFunctionCenter.shared.openShare(ViewController: self, metadata: metadata, indexPage: .activity)
+                    action: { _ in
+                        NCFunctionCenter.shared.openShare(viewController: self, metadata: metadata, indexPage: .activity)
                     }
                 )
             )
         }
-        
+
         //
         // OFFLINE
         //
@@ -130,7 +130,7 @@ extension NCCollectionViewCommon {
                 NCMenuAction(
                     title: isOffline ? NSLocalizedString("_remove_available_offline_", comment: "") :  NSLocalizedString("_set_available_offline_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "tray.and.arrow.down"),
-                    action: { menuAction in
+                    action: { _ in
                         if isOffline {
                             if metadata.directory {
                                 NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, offline: false, account: self.appDelegate.account)
@@ -142,9 +142,9 @@ extension NCCollectionViewCommon {
                                 NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, offline: true, account: self.appDelegate.account)
                                 NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorDownloadAllFile)
                             } else {
-                                NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadOffline) { (_) in }
+                                NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadOffline) { _ in }
                                 if let metadataLivePhoto = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
-                                    NCNetworking.shared.download(metadata: metadataLivePhoto, selector: NCGlobal.shared.selectorLoadOffline) { (_) in }
+                                    NCNetworking.shared.download(metadata: metadataLivePhoto, selector: NCGlobal.shared.selectorLoadOffline) { _ in }
                                 }
                             }
                         }
@@ -153,16 +153,16 @@ extension NCCollectionViewCommon {
                 )
             )
         }
-        
+
         //
         // OPEN with external editor
         //
-        if metadata.classFile == NCCommunicationCommon.typeClassFile.document.rawValue && editors.contains(NCGlobal.shared.editorText) && ((editors.contains(NCGlobal.shared.editorOnlyoffice) || isRichDocument))  {
-            
+        if metadata.classFile == NCCommunicationCommon.typeClassFile.document.rawValue && editors.contains(NCGlobal.shared.editorText) && ((editors.contains(NCGlobal.shared.editorOnlyoffice) || isRichDocument)) {
+
             var editor = ""
             var title = ""
             var icon: UIImage?
-            
+
             if editors.contains(NCGlobal.shared.editorOnlyoffice) {
                 editor = NCGlobal.shared.editorOnlyoffice
                 title = NSLocalizedString("_open_in_onlyoffice_", comment: "")
@@ -172,20 +172,20 @@ extension NCCollectionViewCommon {
                 title = NSLocalizedString("_open_in_collabora_", comment: "")
                 icon = NCUtility.shared.loadImage(named: "collabora")
             }
-            
+
             if editor != "" {
                 actions.append(
                     NCMenuAction(
                         title: title,
                         icon: icon!,
-                        action: { menuAction in
+                        action: { _ in
                             NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon, editor: editor, isRichDocument: isRichDocument)
                         }
                     )
                 )
             }
         }
-        
+
         //
         // OPEN IN
         //
@@ -206,7 +206,7 @@ extension NCCollectionViewCommon {
                 )
             )
         }
-        
+
         //
         // PRINT
         //
@@ -215,13 +215,13 @@ extension NCCollectionViewCommon {
                 NCMenuAction(
                     title: NSLocalizedString("_print_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "printer"),
-                    action: { menuAction in
+                    action: { _ in
                         NCFunctionCenter.shared.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorPrint)
                     }
                 )
             )
         }
-        
+
         //
         // SAVE
         //
@@ -233,12 +233,12 @@ extension NCCollectionViewCommon {
                 title = NSLocalizedString("_livephoto_save_", comment: "")
                 icon = NCUtility.shared.loadImage(named: "livephoto")
             }
-            
+
             actions.append(
                 NCMenuAction(
                     title: title,
                     icon: icon,
-                    action: { menuAction in
+                    action: { _ in
                         if metadataMOV != nil {
                             NCFunctionCenter.shared.saveLivePhoto(metadata: metadata, metadataMOV: metadataMOV!)
                         } else {
@@ -252,24 +252,24 @@ extension NCCollectionViewCommon {
                 )
             )
         }
-        
+
         //
         // SAVE AS SCAN
         //
         if #available(iOS 13.0, *) {
-            if (metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue && metadata.contentType != "image/svg+xml") {
+            if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue && metadata.contentType != "image/svg+xml" {
                 actions.append(
                     NCMenuAction(
                         title: NSLocalizedString("_save_as_scan_", comment: ""),
                         icon: NCUtility.shared.loadImage(named: "viewfinder.circle"),
-                        action: { menuAction in
+                        action: { _ in
                             NCFunctionCenter.shared.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorSaveAsScan)
                         }
                     )
                 )
             }
         }
-        
+
         //
         // RENAME
         //
@@ -278,22 +278,22 @@ extension NCCollectionViewCommon {
                 NCMenuAction(
                     title: NSLocalizedString("_rename_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "pencil"),
-                    action: { menuAction in
-                        
+                    action: { _ in
+
                         if let vcRename = UIStoryboard(name: "NCRenameFile", bundle: nil).instantiateInitialViewController() as? NCRenameFile {
-                            
+
                             vcRename.metadata = metadata
                             vcRename.imagePreview = imageIcon
 
                             let popup = NCPopupViewController(contentController: vcRename, popupWidth: vcRename.width, popupHeight: vcRename.height)
-                                                        
+
                             self.present(popup, animated: true)
                         }
                     }
                 )
             )
         }
-        
+
         //
         // COPY - MOVE
         //
@@ -302,13 +302,13 @@ extension NCCollectionViewCommon {
                 NCMenuAction(
                     title: NSLocalizedString("_move_or_copy_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "arrow.up.right.square"),
-                    action: { menuAction in
+                    action: { _ in
                         NCFunctionCenter.shared.openSelectView(items: [metadata], viewController: self)
                     }
                 )
             )
         }
-        
+
         //
         // COPY
         //
@@ -317,8 +317,8 @@ extension NCCollectionViewCommon {
                 NCMenuAction(
                     title: NSLocalizedString("_copy_file_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "doc.on.doc"),
-                    action: { menuAction in
-                        self.appDelegate.pasteboardOcIds = [metadata.ocId];
+                    action: { _ in
+                        self.appDelegate.pasteboardOcIds = [metadata.ocId]
                         NCFunctionCenter.shared.copyPasteboard()
                     }
                 )
@@ -347,7 +347,7 @@ extension NCCollectionViewCommon {
             }
         }
         */
-        
+
         //
         // MODIFY
         //
@@ -370,7 +370,7 @@ extension NCCollectionViewCommon {
                 )
             }
         }
-        
+
         //
         // DELETE
         //
@@ -378,22 +378,20 @@ extension NCCollectionViewCommon {
             NCMenuAction(
                 title: titleDelete,
                 icon: NCUtility.shared.loadImage(named: "trash"),
-                action: { menuAction in
+                action: { _ in
                     let alertController = UIAlertController(title: "", message: metadata.fileNameView + "\n\n" + NSLocalizedString("_want_delete_", comment: ""), preferredStyle: .alert)
-                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (action:UIAlertAction) in
+                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (_: UIAlertAction) in
                         NCOperationQueue.shared.delete(metadata: metadata, onlyLocalCache: false)
                     })
-                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_remove_local_file_", comment: ""), style: .default) { (action:UIAlertAction) in
+                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_remove_local_file_", comment: ""), style: .default) { (_: UIAlertAction) in
                         NCOperationQueue.shared.delete(metadata: metadata, onlyLocalCache: true)
                     })
-                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (action:UIAlertAction) in })
-                    self.present(alertController, animated: true, completion:nil)
+                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (_: UIAlertAction) in })
+                    self.present(alertController, animated: true, completion: nil)
                 }
             )
         )
-        
-        
-        
+
         //
         // SET FOLDER E2EE
         //
@@ -401,15 +399,15 @@ extension NCCollectionViewCommon {
             actions.append(
                 NCMenuAction(
                     title: NSLocalizedString("_e2e_set_folder_encrypted_", comment: ""),
-                    icon:NCUtility.shared.loadImage(named: "lock"),
-                    action: { menuAction in
-                        NCCommunication.shared.markE2EEFolder(fileId: metadata.fileId, delete: false) { (account, errorCode, errorDescription) in
+                    icon: NCUtility.shared.loadImage(named: "lock"),
+                    action: { _ in
+                        NCCommunication.shared.markE2EEFolder(fileId: metadata.fileId, delete: false) { account, errorCode, errorDescription in
                             if errorCode == 0 {
                                 NCManageDatabase.shared.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, serverUrl))
                                 NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, serverUrlTo: nil, etag: nil, ocId: nil, fileId: nil, encrypted: true, richWorkspace: nil, account: metadata.account)
                                 NCManageDatabase.shared.setMetadataEncrypted(ocId: metadata.ocId, encrypted: true)
-                                
-                                NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE, userInfo: ["serverUrl":metadata.serverUrl])
+
+                                NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE, userInfo: ["serverUrl": metadata.serverUrl])
                             } else {
                                 NCContentPresenter.shared.messageNotification(NSLocalizedString("_e2e_error_mark_folder_", comment: ""), description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: .error, errorCode: errorCode)
                             }
@@ -418,7 +416,7 @@ extension NCCollectionViewCommon {
                 )
             )
         }
-        
+
         //
         // UNSET FOLDER E2EE
         //
@@ -427,14 +425,14 @@ extension NCCollectionViewCommon {
                 NCMenuAction(
                     title: NSLocalizedString("_e2e_remove_folder_encrypted_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "lock"),
-                    action: { menuAction in
-                        NCCommunication.shared.markE2EEFolder(fileId: metadata.fileId, delete: true) { (account, errorCode, errorDescription) in
+                    action: { _ in
+                        NCCommunication.shared.markE2EEFolder(fileId: metadata.fileId, delete: true) { account, errorCode, errorDescription in
                             if errorCode == 0 {
                                 NCManageDatabase.shared.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, serverUrl))
                                 NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, serverUrlTo: nil, etag: nil, ocId: nil, fileId: nil, encrypted: false, richWorkspace: nil, account: metadata.account)
                                 NCManageDatabase.shared.setMetadataEncrypted(ocId: metadata.ocId, encrypted: false)
-                                
-                                NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE, userInfo: ["serverUrl":metadata.serverUrl])
+
+                                NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE, userInfo: ["serverUrl": metadata.serverUrl])
                             } else {
                                 NCContentPresenter.shared.messageNotification(NSLocalizedString("_e2e_error_delete_mark_folder_", comment: ""), description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: .error, errorCode: errorCode)
                             }
@@ -443,10 +441,10 @@ extension NCCollectionViewCommon {
                 )
             )
         }
-        
+
         presentMenu(with: actions)
     }
-    
+
     func toggleMenuSelect() {
 
         var actions = [NCMenuAction]()
@@ -458,12 +456,12 @@ extension NCCollectionViewCommon {
             NCMenuAction(
                 title: NSLocalizedString("_select_all_", comment: ""),
                 icon: NCUtility.shared.loadImage(named: "checkmark.circle.fill"),
-                action: { menuAction in
+                action: { _ in
                     self.collectionViewSelectAll()
                 }
             )
         )
-        
+
         //
         // OPEN IN
         //
@@ -471,7 +469,7 @@ extension NCCollectionViewCommon {
             NCMenuAction(
                 title: NSLocalizedString("_open_in_", comment: ""),
                 icon: NCUtility.shared.loadImage(named: "square.and.arrow.up"),
-                action: { menuAction in
+                action: { _ in
                     NCFunctionCenter.shared.openActivityViewController(selectOcId: self.selectOcId)
                     self.tapSelect(sender: self)
                 }
@@ -485,7 +483,7 @@ extension NCCollectionViewCommon {
             NCMenuAction(
                 title: NSLocalizedString("_save_selected_files_", comment: ""),
                 icon: NCUtility.shared.loadImage(named: "square.and.arrow.down"),
-                action: { menuAction in
+                action: { _ in
                     for ocId in self.selectOcId {
                         if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
                             if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue {
@@ -505,7 +503,7 @@ extension NCCollectionViewCommon {
                 }
             )
         )
-        
+
         //
         // COPY - MOVE
         //
@@ -513,7 +511,7 @@ extension NCCollectionViewCommon {
             NCMenuAction(
                 title: NSLocalizedString("_move_or_copy_selected_files_", comment: ""),
                 icon: NCUtility.shared.loadImage(named: "arrow.up.right.square"),
-                action: { menuAction in
+                action: { _ in
                     var meradatasSelect = [tableMetadata]()
                     for ocId in self.selectOcId {
                         if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
@@ -527,7 +525,7 @@ extension NCCollectionViewCommon {
                 }
             )
         )
-        
+
         //
         // COPY
         //
@@ -535,7 +533,7 @@ extension NCCollectionViewCommon {
             NCMenuAction(
                 title: NSLocalizedString("_copy_file_", comment: ""),
                 icon: NCUtility.shared.loadImage(named: "doc.on.doc"),
-                action: { menuAction in
+                action: { _ in
                     self.appDelegate.pasteboardOcIds.removeAll()
                     for ocId in self.selectOcId {
                         self.appDelegate.pasteboardOcIds.append(ocId)
@@ -545,7 +543,7 @@ extension NCCollectionViewCommon {
                 }
             )
         )
-        
+
         //
         // DELETE
         //
@@ -553,9 +551,9 @@ extension NCCollectionViewCommon {
             NCMenuAction(
                 title: NSLocalizedString("_delete_selected_files_", comment: ""),
                 icon: NCUtility.shared.loadImage(named: "trash"),
-                action: { menuAction in
+                action: { _ in
                     let alertController = UIAlertController(title: "", message: NSLocalizedString("_want_delete_", comment: ""), preferredStyle: .alert)
-                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (action:UIAlertAction) in
+                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (_: UIAlertAction) in
                         for ocId in self.selectOcId {
                             if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
                                 NCOperationQueue.shared.delete(metadata: metadata, onlyLocalCache: false)
@@ -563,7 +561,7 @@ extension NCCollectionViewCommon {
                         }
                         self.tapSelect(sender: self)
                     })
-                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_remove_local_file_", comment: ""), style: .default) { (action:UIAlertAction) in
+                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_remove_local_file_", comment: ""), style: .default) { (_: UIAlertAction) in
                         for ocId in self.selectOcId {
                             if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
                                 NCOperationQueue.shared.delete(metadata: metadata, onlyLocalCache: true)
@@ -571,8 +569,8 @@ extension NCCollectionViewCommon {
                         }
                         self.tapSelect(sender: self)
                     })
-                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (action:UIAlertAction) in })
-                    self.present(alertController, animated: true, completion:nil)
+                    alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (_: UIAlertAction) in })
+                    self.present(alertController, animated: true, completion: nil)
                 }
             )
         )

+ 6 - 7
iOSClient/Menu/NCLoginWeb+Menu.swift

@@ -27,14 +27,14 @@ import FloatingPanel
 extension NCLoginWeb {
 
     func toggleMenu() {
-        
+
         var actions = [NCMenuAction]()
-        
+
         let accounts = NCManageDatabase.shared.getAllAccount()
         var avatar = NCUtility.shared.loadImage(named: "person.crop.circle")
-        
+
         for account in accounts {
-            
+
             let title = account.user + " " + (URL(string: account.urlBase)?.host ?? "")
 
             avatar = NCUtility.shared.loadUserImage(
@@ -50,7 +50,7 @@ extension NCLoginWeb {
                     onIcon: avatar,
                     selected: account.active == true,
                     on: account.active == true,
-                    action: { menuAction in
+                    action: { _ in
                         if self.appDelegate.account != account.account {
                             NCManageDatabase.shared.setAccountActive(account.account)
                             self.dismiss(animated: true) {
@@ -71,7 +71,7 @@ extension NCLoginWeb {
                 onIcon: avatar,
                 selected: false,
                 on: false,
-                action: { menuAction in
+                action: { _ in
                     self.appDelegate.deleteAccount(self.appDelegate.account, wipe: false)
                     self.dismiss(animated: true) {
                         let accounts = NCManageDatabase.shared.getAllAccount()
@@ -88,4 +88,3 @@ extension NCLoginWeb {
         presentMenu(with: actions)
     }
 }
-

+ 32 - 33
iOSClient/Menu/NCMedia+Menu.swift

@@ -37,7 +37,7 @@ extension NCMedia {
                     NCMenuAction(
                         title: NSLocalizedString("_select_", comment: ""),
                         icon: NCUtility.shared.loadImage(named: "checkmark.circle.fill"),
-                        action: { menuAction in
+                        action: { _ in
                             self.isEditMode = true
                         }
                     )
@@ -50,10 +50,10 @@ extension NCMedia {
                     icon: NCUtility.shared.loadImage(named: "photo"),
                     selected: filterClassTypeImage,
                     on: true,
-                    action: { menuAction in
+                    action: { _ in
                         self.filterClassTypeImage = !self.filterClassTypeImage
                         self.filterClassTypeVideo = false
-                        self.reloadDataSourceWithCompletion { (_) in }
+                        self.reloadDataSourceWithCompletion { _ in }
                     }
                 )
             )
@@ -64,72 +64,72 @@ extension NCMedia {
                     icon: NCUtility.shared.loadImage(named: "video"),
                     selected: filterClassTypeVideo,
                     on: true,
-                    action: { menuAction in
+                    action: { _ in
                         self.filterClassTypeVideo = !self.filterClassTypeVideo
                         self.filterClassTypeImage = false
-                        self.reloadDataSourceWithCompletion { (_) in }
+                        self.reloadDataSourceWithCompletion { _ in }
                     }
                 )
             )
-            
+
             actions.append(
                 NCMenuAction(
                     title: NSLocalizedString("_select_media_folder_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "folder"),
-                    action: { menuAction in
+                    action: { _ in
                         let navigationController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
                         let viewController = navigationController.topViewController as! NCSelect
-                        
+
                         viewController.delegate = self
                         viewController.typeOfCommandView = .select
                         viewController.type = "mediaFolder"
-                        
+
                         self.present(navigationController, animated: true, completion: nil)
                     }
                 )
             )
-            
+
             actions.append(
                 NCMenuAction(
                     title: NSLocalizedString("_media_by_modified_date_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "circle.grid.cross.up.fill"),
                     selected: CCUtility.getMediaSortDate() == "date",
                     on: true,
-                    action: { menuAction in
+                    action: { _ in
                         CCUtility.setMediaSortDate("date")
-                        self.reloadDataSourceWithCompletion { (_) in }
+                        self.reloadDataSourceWithCompletion { _ in }
                     }
                 )
             )
-            
+
             actions.append(
                 NCMenuAction(
                     title: NSLocalizedString("_media_by_created_date_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "circle.grid.cross.down.fill"),
                     selected: CCUtility.getMediaSortDate() == "creationDate",
                     on: true,
-                    action: { menuAction in
+                    action: { _ in
                         CCUtility.setMediaSortDate("creationDate")
-                        self.reloadDataSourceWithCompletion { (_) in }
+                        self.reloadDataSourceWithCompletion { _ in }
                     }
                 )
             )
-            
+
             actions.append(
                 NCMenuAction(
                     title: NSLocalizedString("_media_by_upload_date_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "circle.grid.cross.right.fill"),
                     selected: CCUtility.getMediaSortDate() == "uploadDate",
                     on: true,
-                    action: { menuAction in
+                    action: { _ in
                         CCUtility.setMediaSortDate("uploadDate")
-                        self.reloadDataSourceWithCompletion { (_) in }
+                        self.reloadDataSourceWithCompletion { _ in }
                     }
                 )
             )
-            
+
         } else {
-           
+
             //
             // CANCEL
             //
@@ -137,14 +137,14 @@ extension NCMedia {
                 NCMenuAction(
                     title: NSLocalizedString("_cancel_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "xmark"),
-                    action: { menuAction in
+                    action: { _ in
                         self.isEditMode = false
                         self.selectOcId.removeAll()
                         self.reloadDataThenPerform { }
                     }
                 )
             )
-            
+
             //
             // OPEN IN
             //
@@ -152,7 +152,7 @@ extension NCMedia {
                 NCMenuAction(
                     title: NSLocalizedString("_open_in_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "square.and.arrow.up"),
-                    action: { menuAction in
+                    action: { _ in
                         self.isEditMode = false
                         NCFunctionCenter.shared.openActivityViewController(selectOcId: self.selectOcId)
                         self.selectOcId.removeAll()
@@ -160,7 +160,7 @@ extension NCMedia {
                     }
                 )
             )
-            
+
             //
             // SAVE TO PHOTO GALLERY
             //
@@ -168,7 +168,7 @@ extension NCMedia {
                 NCMenuAction(
                     title: NSLocalizedString("_save_selected_files_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "square.and.arrow.down"),
-                    action: { menuAction in
+                    action: { _ in
                         self.isEditMode = false
                         for ocId in self.selectOcId {
                             if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
@@ -190,7 +190,7 @@ extension NCMedia {
                     }
                 )
             )
-            
+
             //
             // COPY - MOVE
             //
@@ -198,7 +198,7 @@ extension NCMedia {
                 NCMenuAction(
                     title: NSLocalizedString("_move_or_copy_selected_files_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "arrow.up.right.square"),
-                    action: { menuAction in
+                    action: { _ in
                         self.isEditMode = false
                         var meradatasSelect = [tableMetadata]()
                         for ocId in self.selectOcId {
@@ -214,7 +214,7 @@ extension NCMedia {
                     }
                 )
             )
-            
+
             //
             // COPY
             //
@@ -222,7 +222,7 @@ extension NCMedia {
                 NCMenuAction(
                     title: NSLocalizedString("_copy_file_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "doc.on.doc"),
-                    action: { menuAction in
+                    action: { _ in
                         self.isEditMode = false
                         self.appDelegate.pasteboardOcIds.removeAll()
                         for ocId in self.selectOcId {
@@ -234,7 +234,7 @@ extension NCMedia {
                     }
                 )
             )
-            
+
             //
             // DELETE
             //
@@ -242,11 +242,11 @@ extension NCMedia {
                 NCMenuAction(
                     title: NSLocalizedString("_delete_selected_files_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "trash"),
-                    action: { menuAction in
+                    action: { _ in
                         self.isEditMode = false
                         for ocId in self.selectOcId {
                             if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
-                                NCNetworking.shared.deleteMetadata(metadata, onlyLocalCache: false) { (errorCode, errorDescription) in
+                                NCNetworking.shared.deleteMetadata(metadata, onlyLocalCache: false) { errorCode, errorDescription in
                                     if errorCode != 0 {
                                         NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
                                     }
@@ -263,4 +263,3 @@ extension NCMedia {
         presentMenu(with: actions)
     }
 }
-

+ 6 - 6
iOSClient/Menu/NCMenu.swift

@@ -35,7 +35,7 @@ class NCMenu: UITableViewController {
         menuViewController.actions = actions
         return menuViewController
     }
-    
+
     // MARK: - View Life Cycle
 
     override func viewDidLoad() {
@@ -71,7 +71,7 @@ class NCMenu: UITableViewController {
             cell.selectionStyle = .none
         }
 
-        if (action.isOn) {
+        if action.isOn {
             actionIconView.image = action.onIcon
             actionNameLabel.text = action.onTitle
         } else {
@@ -85,7 +85,7 @@ class NCMenu: UITableViewController {
     }
 
     // MARK: - Accessibility
-    
+
     open override func accessibilityPerformEscape() -> Bool {
         dismiss(animated: true)
         return true
@@ -98,7 +98,7 @@ extension NCMenu: FloatingPanelControllerDelegate {
         let safeAreaInsetsBottom = Int(UIApplication.shared.keyWindow?.rootViewController?.view.safeAreaInsets.bottom ?? 0)
         return NCMenuFloatingPanelLayout(height: self.actions.count * 60 + safeAreaInsetsBottom)
     }
-    
+
     func floatingPanel(_ vc: FloatingPanelController, behaviorFor newCollection: UITraitCollection) -> FloatingPanelBehavior? {
         return NCMenuFloatingPanelBehavior()
     }
@@ -127,7 +127,7 @@ class NCMenuFloatingPanelLayout: FloatingPanelLayout {
     }
 
     func insetFor(position: FloatingPanelPosition) -> CGFloat? {
-        if (position == .full) {
+        if position == .full {
             return max(48, UIScreen.main.bounds.size.height - height)
         } else {
             return nil
@@ -141,7 +141,7 @@ class NCMenuFloatingPanelLayout: FloatingPanelLayout {
     public func prepareLayout(surfaceView: UIView, in view: UIView) -> [NSLayoutConstraint] {
         return [
             surfaceView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0),
-            surfaceView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0),
+            surfaceView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0)
         ]
     }
 

+ 20 - 20
iOSClient/Menu/NCSortMenu.swift

@@ -26,25 +26,25 @@ import FloatingPanel
 import NCCommunication
 
 class NCSortMenu: NSObject {
-    
+
     private var sortButton: UIButton?
     private var serverUrl: String = ""
     private var hideDirectoryOnTop: Bool?
-    
+
     private var key = ""
 
     func toggleMenu(viewController: UIViewController, key: String, sortButton: UIButton?, serverUrl: String, hideDirectoryOnTop: Bool = false) {
-        
+
         self.key = key
         self.sortButton = sortButton
         self.serverUrl = serverUrl
         self.hideDirectoryOnTop = hideDirectoryOnTop
-        
+
         var layoutForView = NCUtility.shared.getLayoutForView(key: key, serverUrl: serverUrl)
         var actions = [NCMenuAction]()
         var title = ""
         var icon = UIImage()
-        
+
         if layoutForView.ascending {
             title = NSLocalizedString("_order_by_name_z_a_", comment: "")
             icon = UIImage(named: "sortFileNameZA")!.image(color: NCBrandColor.shared.gray, size: 50)
@@ -52,14 +52,14 @@ class NCSortMenu: NSObject {
             title = NSLocalizedString("_order_by_name_a_z_", comment: "")
             icon = UIImage(named: "sortFileNameAZ")!.image(color: NCBrandColor.shared.gray, size: 50)
         }
-       
+
         actions.append(
             NCMenuAction(
                 title: title,
                 icon: icon,
                 selected: layoutForView.sort == "fileName",
                 on: layoutForView.sort == "fileName",
-                action: { menuAction in
+                action: { _ in
                     layoutForView.sort = "fileName"
                     layoutForView.ascending = !layoutForView.ascending
                     self.actionMenu(layoutForView: layoutForView)
@@ -74,14 +74,14 @@ class NCSortMenu: NSObject {
             title = NSLocalizedString("_order_by_date_less_recent_", comment: "")
             icon = UIImage(named: "sortDateLessRecent")!.image(color: NCBrandColor.shared.gray, size: 50)
         }
-        
+
         actions.append(
             NCMenuAction(
                 title: title,
                 icon: icon,
                 selected: layoutForView.sort == "date",
                 on: layoutForView.sort == "date",
-                action: { menuAction in
+                action: { _ in
                     layoutForView.sort = "date"
                     layoutForView.ascending = !layoutForView.ascending
                     self.actionMenu(layoutForView: layoutForView)
@@ -96,14 +96,14 @@ class NCSortMenu: NSObject {
             title = NSLocalizedString("_order_by_size_smallest_", comment: "")
             icon = UIImage(named: "sortSmallest")!.image(color: NCBrandColor.shared.gray, size: 50)
         }
-        
+
         actions.append(
             NCMenuAction(
                 title: title,
                 icon: icon,
                 selected: layoutForView.sort == "size",
                 on: layoutForView.sort == "size",
-                action: { menuAction in
+                action: { _ in
                     layoutForView.sort = "size"
                     layoutForView.ascending = !layoutForView.ascending
                     self.actionMenu(layoutForView: layoutForView)
@@ -118,21 +118,21 @@ class NCSortMenu: NSObject {
                     icon: UIImage(named: "foldersOnTop")!.image(color: NCBrandColor.shared.gray, size: 50),
                     selected: layoutForView.directoryOnTop,
                     on: layoutForView.directoryOnTop,
-                    action: { menuAction in
+                    action: { _ in
                         layoutForView.directoryOnTop = !layoutForView.directoryOnTop
                         self.actionMenu(layoutForView: layoutForView)
                     }
                 )
             )
         }
-        
+
         viewController.presentMenu(with: actions)
     }
-    
+
     func actionMenu(layoutForView: NCGlobal.layoutForViewType) {
-                
+
         var layoutForView = layoutForView
-        
+
         switch layoutForView.sort {
         case "fileName":
             layoutForView.titleButtonHeader = layoutForView.ascending ? "_sorted_by_name_a_z_" : "_sorted_by_name_z_a_"
@@ -143,11 +143,11 @@ class NCSortMenu: NSObject {
         default:
             break
         }
-        
+
         self.sortButton?.setTitle(NSLocalizedString(layoutForView.titleButtonHeader, comment: ""), for: .normal)
-        
+
         NCUtility.shared.setLayoutForView(key: key, serverUrl: serverUrl, layoutForView: layoutForView)
-        
-        NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl":self.serverUrl])
+
+        NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl": self.serverUrl])
     }
 }

+ 8 - 9
iOSClient/Menu/NCTrash+Menu.swift

@@ -36,7 +36,7 @@ extension NCTrash {
                 NCMenuAction(
                     title: NSLocalizedString("_trash_delete_selected_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "trash"),
-                    action: { menuAction in
+                    action: { _ in
                         let alert = UIAlertController(title: NSLocalizedString("_trash_delete_selected_", comment: ""), message: "", preferredStyle: .alert)
                         alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .destructive, handler: { _ in
                             for ocId in self.selectOcId {
@@ -57,7 +57,7 @@ extension NCTrash {
                 NCMenuAction(
                     title: NSLocalizedString("_trash_delete_all_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "trash"),
-                    action: { menuAction in
+                    action: { _ in
                         let alert = UIAlertController(title: NSLocalizedString("_trash_delete_all_", comment: ""), message: "", preferredStyle: .alert)
                         alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .destructive, handler: { _ in
                             self.emptyTrash()
@@ -85,7 +85,7 @@ extension NCTrash {
         if let icon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)) {
             iconHeader = icon
         } else {
-            if(tableTrash.directory) {
+            if tableTrash.directory {
                 iconHeader = UIImage(named: "folder")!.image(color: NCBrandColor.shared.gray, size: 50)
             } else {
                 iconHeader = UIImage(named: tableTrash.iconName)
@@ -104,7 +104,7 @@ extension NCTrash {
             NCMenuAction(
                 title: NSLocalizedString("_delete_", comment: ""),
                 icon: NCUtility.shared.loadImage(named: "trash"),
-                action: { menuAction in
+                action: { _ in
                     self.deleteItem(with: objectId)
                 }
             )
@@ -112,7 +112,7 @@ extension NCTrash {
 
         self.presentMenu(with: actions)
     }
-    
+
     func toggleMenuMoreGrid(with objectId: String, namedButtonMore: String, image: UIImage?) {
 
         var actions: [NCMenuAction] = []
@@ -125,7 +125,7 @@ extension NCTrash {
         if let icon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)) {
             iconHeader = icon
         } else {
-            if(tableTrash.directory) {
+            if tableTrash.directory {
                 iconHeader = UIImage(named: "folder")!.image(color: NCBrandColor.shared.gray, size: 50)
             } else {
                 iconHeader = UIImage(named: tableTrash.iconName)
@@ -144,7 +144,7 @@ extension NCTrash {
             NCMenuAction(
                 title: NSLocalizedString("_restore_", comment: ""),
                 icon: UIImage(named: "restore")!.image(color: NCBrandColor.shared.gray, size: 50),
-                action: { menuAction in
+                action: { _ in
                     self.restoreItem(with: objectId)
                 }
             )
@@ -154,7 +154,7 @@ extension NCTrash {
             NCMenuAction(
                 title: NSLocalizedString("_delete_", comment: ""),
                 icon: NCUtility.shared.loadImage(named: "trash"),
-                action: { menuAction in
+                action: { _ in
                     self.deleteItem(with: objectId)
                 }
             )
@@ -163,4 +163,3 @@ extension NCTrash {
         presentMenu(with: actions)
     }
 }
-

+ 66 - 66
iOSClient/Menu/NCViewer+Menu.swift

@@ -28,20 +28,20 @@ import NCCommunication
 extension NCViewer {
 
     func toggleMenu(viewController: UIViewController, metadata: tableMetadata, webView: Bool, imageIcon: UIImage?) {
-        
+
         var actions = [NCMenuAction]()
-        
+
         var titleFavorite = NSLocalizedString("_add_favorites_", comment: "")
         if metadata.favorite { titleFavorite = NSLocalizedString("_remove_favorites_", comment: "") }
         let localFile = NCManageDatabase.shared.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
-        
+
         var titleOffline = ""
-        if (localFile == nil || localFile!.offline == false) {
+        if localFile == nil || localFile!.offline == false {
             titleOffline = NSLocalizedString("_set_available_offline_", comment: "")
         } else {
             titleOffline = NSLocalizedString("_remove_available_offline_", comment: "")
         }
-        
+
         var titleDelete = NSLocalizedString("_delete_", comment: "")
         if NCManageDatabase.shared.isMetadataShareOrMounted(metadata: metadata, metadataFolder: nil) {
             titleDelete = NSLocalizedString("_leave_share_", comment: "")
@@ -50,9 +50,9 @@ extension NCViewer {
         } else {
             titleDelete = NSLocalizedString("_delete_file_", comment: "")
         }
-        
+
         let isFolderEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase)
-        
+
         //
         // FAVORITE
         //
@@ -60,8 +60,8 @@ extension NCViewer {
             NCMenuAction(
                 title: titleFavorite,
                 icon: NCUtility.shared.loadImage(named: "star.fill", color: NCBrandColor.shared.yellowFavorite),
-                action: { menuAction in
-                    NCNetworking.shared.favoriteMetadata(metadata) { (errorCode, errorDescription) in
+                action: { _ in
+                    NCNetworking.shared.favoriteMetadata(metadata) { errorCode, errorDescription in
                         if errorCode != 0 {
                             NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
                         }
@@ -69,7 +69,7 @@ extension NCViewer {
                 }
             )
         )
-        
+
         //
         // DETAIL
         //
@@ -78,13 +78,13 @@ extension NCViewer {
                 NCMenuAction(
                     title: NSLocalizedString("_details_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "info"),
-                    action: { menuAction in
-                        NCFunctionCenter.shared.openShare(ViewController: viewController, metadata: metadata, indexPage: .activity)
+                    action: { _ in
+                        NCFunctionCenter.shared.openShare(viewController: viewController, metadata: metadata, indexPage: .activity)
                     }
                 )
             )
         }
-        
+
         //
         // OFFLINE
         //
@@ -93,9 +93,9 @@ extension NCViewer {
                 NCMenuAction(
                     title: titleOffline,
                     icon: NCUtility.shared.loadImage(named: "tray.and.arrow.down"),
-                    action: { menuAction in
-                        if ((localFile == nil || !CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView)) && metadata.session == "") {
-                            NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadOffline) { (_) in }
+                    action: { _ in
+                        if (localFile == nil || !CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView)) && metadata.session == "" {
+                            NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadOffline) { _ in }
                         } else {
                             NCManageDatabase.shared.setLocalFile(ocId: metadata.ocId, offline: !localFile!.offline)
                         }
@@ -103,7 +103,7 @@ extension NCViewer {
                 )
             )
         }
-        
+
         //
         // OPEN IN
         //
@@ -112,13 +112,13 @@ extension NCViewer {
                 NCMenuAction(
                     title: NSLocalizedString("_open_in_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "square.and.arrow.up"),
-                    action: { menuAction in
+                    action: { _ in
                         NCFunctionCenter.shared.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorOpenIn)
                     }
                 )
             )
         }
-        
+
         //
         // PRINT
         //
@@ -127,18 +127,18 @@ extension NCViewer {
                 NCMenuAction(
                     title: NSLocalizedString("_print_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "printer"),
-                    action: { menuAction in
+                    action: { _ in
                         NCFunctionCenter.shared.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorPrint)
                     }
                 )
             )
         }
-        
+
         //
         // SAVE IMAGE / VIDEO
         //
         if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue {
-            
+
             var title: String = NSLocalizedString("_save_selected_files_", comment: "")
             var icon = NCUtility.shared.loadImage(named: "square.and.arrow.down")
             let metadataMOV = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
@@ -146,12 +146,12 @@ extension NCViewer {
                 title = NSLocalizedString("_livephoto_save_", comment: "")
                 icon = NCUtility.shared.loadImage(named: "livephoto")
             }
-            
+
             actions.append(
                 NCMenuAction(
                     title: title,
                     icon: icon,
-                    action: { menuAction in
+                    action: { _ in
                         if metadataMOV != nil {
                             NCFunctionCenter.shared.saveLivePhoto(metadata: metadata, metadataMOV: metadataMOV!)
                         } else {
@@ -161,24 +161,24 @@ extension NCViewer {
                 )
             )
         }
-        
+
         //
         // SAVE AS SCAN
         //
         if #available(iOS 13.0, *) {
-            if (metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue && metadata.contentType != "image/svg+xml") {
+            if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue && metadata.contentType != "image/svg+xml" {
                 actions.append(
                     NCMenuAction(
                         title: NSLocalizedString("_save_as_scan_", comment: ""),
                         icon: NCUtility.shared.loadImage(named: "viewfinder.circle"),
-                        action: { menuAction in
+                        action: { _ in
                             NCFunctionCenter.shared.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorSaveAsScan)
                         }
                     )
                 )
             }
         }
-        
+
         //
         // RENAME
         //
@@ -187,23 +187,23 @@ extension NCViewer {
                 NCMenuAction(
                     title: NSLocalizedString("_rename_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "pencil"),
-                    action: { menuAction in
-                        
+                    action: { _ in
+
                         if let vcRename = UIStoryboard(name: "NCRenameFile", bundle: nil).instantiateInitialViewController() as? NCRenameFile {
-                            
+
                             vcRename.metadata = metadata
                             vcRename.disableChangeExt = true
                             vcRename.imagePreview = imageIcon
-                            
+
                             let popup = NCPopupViewController(contentController: vcRename, popupWidth: vcRename.width, popupHeight: vcRename.height)
-                            
+
                             viewController.present(popup, animated: true)
                         }
                     }
                 )
             )
         }
-        
+
         //
         // COPY - MOVE
         //
@@ -212,22 +212,22 @@ extension NCViewer {
                 NCMenuAction(
                     title: NSLocalizedString("_move_or_copy_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "arrow.up.right.square"),
-                    action: { menuAction in
-                        
+                    action: { _ in
+
                         let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
                         let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
                         let viewController = navigationController.topViewController as! NCSelect
-                        
+
                         viewController.delegate = NCViewer.shared
                         viewController.typeOfCommandView = .copyMove
                         viewController.items = [metadata]
-                        
+
                         self.appDelegate.window?.rootViewController?.present(navigationController, animated: true, completion: nil)
                     }
                 )
             )
         }
-        
+
         //
         // COPY
         //
@@ -235,13 +235,13 @@ extension NCViewer {
             NCMenuAction(
                 title: NSLocalizedString("_copy_file_", comment: ""),
                 icon: NCUtility.shared.loadImage(named: "doc.on.doc"),
-                action: { menuAction in
-                    self.appDelegate.pasteboardOcIds = [metadata.ocId];
+                action: { _ in
+                    self.appDelegate.pasteboardOcIds = [metadata.ocId]
                     NCFunctionCenter.shared.copyPasteboard()
                 }
             )
         )
-        
+
         //
         // VIEW IN FOLDER
         //
@@ -256,7 +256,7 @@ extension NCViewer {
                 )
             )
         }
-        
+
         //
         // DOWNLOAD IMAGE MAX RESOLUTION
         //
@@ -266,14 +266,14 @@ extension NCViewer {
                     NCMenuAction(
                         title: NSLocalizedString("_download_image_max_", comment: ""),
                         icon: NCUtility.shared.loadImage(named: "square.and.arrow.down"),
-                        action: { menuAction in
-                            NCNetworking.shared.download(metadata: metadata, selector: "") { (_) in }
+                        action: { _ in
+                            NCNetworking.shared.download(metadata: metadata, selector: "") { _ in }
                         }
                     )
                 )
             }
         }
-        
+
         //
         // PDF
         //
@@ -282,15 +282,15 @@ extension NCViewer {
                 NCMenuAction(
                     title: NSLocalizedString("_search_", comment: ""),
                     icon: UIImage(named: "search")!.image(color: NCBrandColor.shared.gray, size: 50),
-                    action: { menuAction in
+                    action: { _ in
                         NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterMenuSearchTextPDF)
                     }
                 )
             )
-            
+
             var title = ""
             var icon = UIImage()
-            
+
             if CCUtility.getPDFDisplayDirection() == .horizontal {
                 title = NSLocalizedString("_pdf_vertical_", comment: "")
                 icon = UIImage(named: "pdf-vertical")!.image(color: NCBrandColor.shared.gray, size: 50)
@@ -298,12 +298,12 @@ extension NCViewer {
                 title = NSLocalizedString("_pdf_horizontal_", comment: "")
                 icon = UIImage(named: "pdf-horizontal")!.image(color: NCBrandColor.shared.gray, size: 50)
             }
-            
+
             actions.append(
                 NCMenuAction(
                     title: title,
                     icon: icon,
-                    action: { menuAction in
+                    action: { _ in
                         if CCUtility.getPDFDisplayDirection() == .horizontal {
                             NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterMenuPDFDisplayDirection, userInfo: ["direction": PDFDisplayDirection.vertical])
                         } else {
@@ -312,18 +312,18 @@ extension NCViewer {
                     }
                 )
             )
-            
+
             actions.append(
                 NCMenuAction(
                     title: NSLocalizedString("_go_to_page_", comment: ""),
                     icon: NCUtility.shared.loadImage(named: "repeat"),
-                    action: { menuAction in
+                    action: { _ in
                         NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterMenuGotToPageInPDF)
                     }
                 )
             )
         }
-        
+
         //
         // MODIFY
         //
@@ -333,14 +333,14 @@ extension NCViewer {
                     NCMenuAction(
                         title: NSLocalizedString("_modify_", comment: ""),
                         icon: NCUtility.shared.loadImage(named: "pencil.tip.crop.circle"),
-                        action: { menuAction in
+                        action: { _ in
                             NCFunctionCenter.shared.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorLoadFileQuickLook)
                         }
                     )
                 )
             }
         }
-        
+
         //
         // DELETE
         //
@@ -349,22 +349,22 @@ extension NCViewer {
                 NCMenuAction(
                     title: titleDelete,
                     icon: NCUtility.shared.loadImage(named: "trash"),
-                    action: { menuAction in
-                        
+                    action: { _ in
+
                         let alertController = UIAlertController(title: "", message: NSLocalizedString("_want_delete_", comment: ""), preferredStyle: .alert)
-                        
-                        alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (action:UIAlertAction) in
-                            
-                            NCNetworking.shared.deleteMetadata(metadata, onlyLocalCache: false) { (errorCode, errorDescription) in
+
+                        alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (_: UIAlertAction) in
+
+                            NCNetworking.shared.deleteMetadata(metadata, onlyLocalCache: false) { errorCode, errorDescription in
                                 if errorCode != 0 {
                                     NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
                                 }
                             }
                         })
-                        
-                        alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (action:UIAlertAction) in })
-                                            
-                        viewController.present(alertController, animated: true, completion:nil)
+
+                        alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (_: UIAlertAction) in })
+
+                        viewController.present(alertController, animated: true, completion: nil)
                     }
                 )
             )

+ 2 - 2
iOSClient/Menu/UIViewController+Menu.swift

@@ -63,7 +63,7 @@ extension UIViewController {
         let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
         guard serverVersionMajor >= NCGlobal.shared.nextcloudVersion23 else { return }
 
-        NCCommunication.shared.getHovercard(for: userId) { (card, errCode, err) in
+        NCCommunication.shared.getHovercard(for: userId) { card, _, _ in
             guard let card = card else { return }
 
             let personHeader = NCMenuAction(
@@ -104,7 +104,7 @@ extension UIViewController {
 
         present(mail, animated: true)
     }
-    
+
     func presentMenu(with actions: [NCMenuAction]) {
         let menuViewController = NCMenu.makeNCMenu(with: actions)
 

+ 53 - 53
iOSClient/More/NCMore.swift

@@ -55,8 +55,8 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
         tableView.backgroundColor = NCBrandColor.shared.systemGroupedBackground
         tableView.separatorColor = NCBrandColor.shared.separator
 
-        tableView.register(UINib.init(nibName: "NCMoreUserCell", bundle: nil), forCellReuseIdentifier: "userCell")
-        
+        tableView.register(UINib(nibName: "NCMoreUserCell", bundle: nil), forCellReuseIdentifier: "userCell")
+
         // create tap gesture recognizer
         let tapQuota = UITapGestureRecognizer(target: self, action: #selector(tapLabelQuotaExternalSite))
         labelQuotaExternalSite.isUserInteractionEnabled = true
@@ -68,22 +68,22 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
 
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
-        
+
         appDelegate.activeViewController = self
-        
+
         loadItems()
     }
-    
+
     // MARK: - NotificationCenter
 
     @objc func initialize() {
         loadItems()
     }
-    
+
     // MARK: -
-    
+
     func loadItems() {
-        
+
         var item = NCCommunicationExternalSite()
         var quota: String = ""
 
@@ -94,7 +94,7 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
         quotaMenu.removeAll()
         labelQuotaExternalSite.text = ""
         progressQuota.progressTintColor = NCBrandColor.shared.brandElement
-        
+
         // ITEM : Transfer
         item = NCCommunicationExternalSite()
         item.name = "_transfers_"
@@ -108,7 +108,7 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
         item.icon = "recent"
         item.url = "segueRecent"
         functionMenu.append(item)
-        
+
         // ITEM : Notification
         item = NCCommunicationExternalSite()
         item.name = "_notification_"
@@ -132,7 +132,7 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
             item.url = "segueShares"
             functionMenu.append(item)
         }
-        
+
         // ITEM : Offline
         item = NCCommunicationExternalSite()
         item.name = "_manage_file_offline_"
@@ -148,7 +148,7 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
             item.url = "openStoryboardScan"
             functionMenu.append(item)
         }
-        
+
         // ITEM : Trash
         let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
         if serverVersionMajor >= NCGlobal.shared.nextcloudVersion15 {
@@ -166,7 +166,7 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
         item.icon = "gear"
         item.url = "segueSettings"
         settingsMenu.append(item)
-        
+
         // ITEM: Test API
         if NCUtility.shared.isSimulator() {
             item = NCCommunicationExternalSite()
@@ -176,18 +176,18 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
             settingsMenu.append(item)
         }
 
-        if (quotaMenu.count > 0) {
+        if quotaMenu.count > 0 {
             let item = quotaMenu[0]
             labelQuotaExternalSite.text = item.name
         }
-        
+
         // Display Name user & Quota
 
         if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
-      
+
             self.tabAccount = activeAccount
 
-            if (activeAccount.quotaRelative > 0) {
+            if activeAccount.quotaRelative > 0 {
                 progressQuota.progress = Float(activeAccount.quotaRelative) / 100
             } else {
                 progressQuota.progress = 0
@@ -208,7 +208,7 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
 
             labelQuota.text = String.localizedStringWithFormat(NSLocalizedString("_quota_using_", comment: ""), quotaUsed, quota)
         }
-        
+
         // ITEM : External
         if NCBrandOptions.shared.disable_more_external_site == false {
             if let externalSites = NCManageDatabase.shared.getAllExternalSites(account: appDelegate.account) {
@@ -218,7 +218,7 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
                         item.name = externalSite.name
                         item.url = urlEncoded
                         item.icon = "network"
-                        if (externalSite.type == "settings") {
+                        if externalSite.type == "settings" {
                             item.icon = "gear"
                         }
                         externalSiteMenu.append(item)
@@ -237,7 +237,7 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
 
     @objc func tapLabelQuotaExternalSite() {
 
-        if (quotaMenu.count > 0) {
+        if quotaMenu.count > 0 {
 
             let item = quotaMenu[0]
             let browserWebVC = UIStoryboard(name: "NCBrowserWeb", bundle: nil).instantiateInitialViewController() as! NCBrowserWeb
@@ -251,13 +251,13 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
 
     @objc func tapImageLogoManageAccount() {
 
-        let controller = CCManageAccount.init()
+        let controller = CCManageAccount()
 
         self.navigationController?.pushViewController(controller, animated: true)
     }
-    
+
     // MARK: -
-    
+
     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
         if indexPath.section == 0 {
             return 100
@@ -265,10 +265,10 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
             return NCGlobal.shared.heightCellSettings
         }
     }
-    
+
     func numberOfSections(in tableView: UITableView) -> Int {
 
-        if (externalSiteMenu.count == 0) {
+        if externalSiteMenu.count == 0 {
             return 3
         } else {
             return 4
@@ -278,26 +278,26 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
 
         var cont = 0
-        
-        if (section == 0) {
+
+        if section == 0 {
             cont = tabAccount == nil ? 0 : 1
-        } else if (section == 1) {
+        } else if section == 1 {
             // Menu Normal
             cont = functionMenu.count
         } else {
-            switch (numberOfSections(in: tableView)) {
+            switch numberOfSections(in: tableView) {
             case 3:
                 // Menu Settings
-                if (section == 2) {
+                if section == 2 {
                     cont = settingsMenu.count
                 }
             case 4:
                 // Menu External Site
-                if (section == 2) {
+                if section == 2 {
                     cont = externalSiteMenu.count
                 }
                 // Menu Settings
-                if (section == 3) {
+                if section == 3 {
                     cont = settingsMenu.count
                 }
             default:
@@ -314,10 +314,10 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
 
         // change color selection and disclosure indicator
         let selectionColor: UIView = UIView()
-        if (indexPath.section == 0) {
-            
+        if indexPath.section == 0 {
+
             let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath) as! NCMoreUserCell
-            
+
             cell.avatar.image = nil
             cell.icon.image = nil
             cell.status.text = ""
@@ -339,7 +339,7 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
             cell.selectedBackgroundView = selectionColor
             cell.backgroundColor = NCBrandColor.shared.secondarySystemGroupedBackground
             cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
-            
+
             if NCManageDatabase.shared.getCapabilitiesServerBool(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesUserStatusEnabled, exists: false) {
                 if let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", appDelegate.account)) {
                     let status = NCUtility.shared.getUserStatus(userIcon: account.userStatusIcon, userStatus: account.userStatusStatus, userMessage: account.userStatusMessage)
@@ -354,35 +354,35 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
                     }
                 }
             }
-            
+
             return cell
-            
+
         } else {
-            
+
             let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CCCellMore
-            
+
             // Menu Normal
-            if (indexPath.section == 1) {
+            if indexPath.section == 1 {
 
                 item = functionMenu[indexPath.row]
             }
             // Menu External Site
-            if (numberOfSections(in: tableView) == 4 && indexPath.section == 2) {
+            if numberOfSections(in: tableView) == 4 && indexPath.section == 2 {
                 item = externalSiteMenu[indexPath.row]
             }
             // Menu Settings
-            if ((numberOfSections(in: tableView) == 3 && indexPath.section == 2) || (numberOfSections(in: tableView) == 4 && indexPath.section == 3)) {
+            if (numberOfSections(in: tableView) == 3 && indexPath.section == 2) || (numberOfSections(in: tableView) == 4 && indexPath.section == 3) {
                 item = settingsMenu[indexPath.row]
             }
 
             cell.imageIcon?.image = NCUtility.shared.loadImage(named: item.icon)
             cell.labelText?.text = NSLocalizedString(item.name, comment: "")
             cell.labelText.textColor = NCBrandColor.shared.label
-            
+
             cell.selectedBackgroundView = selectionColor
             cell.backgroundColor = NCBrandColor.shared.secondarySystemGroupedBackground
             cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
-            
+
             return cell
         }
     }
@@ -403,12 +403,12 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
         }
 
         // Menu External Site
-        if (numberOfSections(in: tableView) == 4 && indexPath.section == 2) {
+        if numberOfSections(in: tableView) == 4 && indexPath.section == 2 {
             item = externalSiteMenu[indexPath.row]
         }
 
         // Menu Settings
-        if ((numberOfSections(in: tableView) == 3 && indexPath.section == 2) || (numberOfSections(in: tableView) == 4 && indexPath.section == 3)) {
+        if (numberOfSections(in: tableView) == 3 && indexPath.section == 2) || (numberOfSections(in: tableView) == 4 && indexPath.section == 3) {
             item = settingsMenu[indexPath.row]
         }
 
@@ -427,7 +427,7 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
             }
 
         } else if item.url.contains("//") {
-           
+
             let browserWebVC = UIStoryboard(name: "NCBrowserWeb", bundle: nil).instantiateInitialViewController() as! NCBrowserWeb
             browserWebVC.urlBase = item.url
             browserWebVC.isHiddenButtonExit = true
@@ -440,24 +440,24 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
 
             let alertController = UIAlertController(title: "", message: NSLocalizedString("_want_delete_", comment: ""), preferredStyle: .alert)
 
-            let actionYes = UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (action: UIAlertAction) in
+            let actionYes = UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (_: UIAlertAction) in
 
                 let manageAccount = CCManageAccount()
                 manageAccount.delete(self.appDelegate.account)
 
-                self.appDelegate.openLogin(viewController:self, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
+                self.appDelegate.openLogin(viewController: self, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
             }
 
-            let actionNo = UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (action: UIAlertAction) in
+            let actionNo = UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (_: UIAlertAction) in
                 print("You've pressed No button")
             }
 
             alertController.addAction(actionYes)
             alertController.addAction(actionNo)
             self.present(alertController, animated: true, completion: nil)
-            
+
         } else if item.url == "test" {
-            
+
         }
     }
 }

+ 26 - 54
iOSClient/NCGlobal.swift

@@ -39,7 +39,7 @@ class NCGlobal: NSObject {
             in: username,
             range: NSRange(username.startIndex..., in: username))
 
-        if (!matches.isEmpty) {
+        if !matches.isEmpty {
             // Already a md5 hash?
             // done, use as is.
             hash = lowerUsername
@@ -68,7 +68,7 @@ class NCGlobal: NSObject {
         var totalBytes: Int64
         var totalBytesExpected: Int64
     }
-    
+
     // Struct for LayoutForView
     //
     struct layoutForViewType {
@@ -82,7 +82,7 @@ class NCGlobal: NSObject {
         var imageBackgroud: String
         var imageBackgroudContentMode: String
     }
-    
+
     // Directory on Group
     //
     @objc let appDatabaseNextcloud                  = "Library/Application Support/Nextcloud"
@@ -99,7 +99,7 @@ class NCGlobal: NSObject {
     let metadataKeyedUnarchiver                     = "it.twsweb.nextcloud.metadata"
     let refreshTask                                 = "com.nextcloud.refreshTask"
     let processingTask                              = "com.nextcloud.processingTask"
-    
+
     // Nextcloud version
     //
     let nextcloudVersion12: Int                     =  12
@@ -113,23 +113,23 @@ class NCGlobal: NSObject {
     //
     let databaseDefault                             = "nextcloud.realm"
     let databaseSchemaVersion: UInt64               = 213
-    
+
     // Intro selector
     //
     @objc let introLogin: Int                       = 0
     let introSignup: Int                            = 1
-    
+
     // Varie size GUI
     //
     @objc let heightCellSettings: CGFloat           = 50
-    
+
     // Avatar & Preview size
     //
     let avatarSize: Int                             = 128 * Int(UIScreen.main.scale)
     let avatarSizeRounded: Int                      = 128
     let sizePreview: Int                            = 1024
     let sizeIcon: Int                               = 512
-    
+
     // E2EE
     //
     let e2eeMaxFileSize: UInt64                     = 500000000     // 500 MB
@@ -155,12 +155,12 @@ class NCGlobal: NSObject {
     // Nextcloud unsupported
     //
     let nextcloud_unsupported_version: Int          = 16
-    
+
     // Layout
     //
     let layoutList                                  = "typeLayoutList"
     let layoutGrid                                  = "typeLayoutGrid"
-    
+
     let layoutViewMove                              = "LayoutMove"
     let layoutViewTrash                             = "LayoutTrash"
     let layoutViewOffline                           = "LayoutOffline"
@@ -176,7 +176,7 @@ class NCGlobal: NSObject {
     //
     let buttonMoreMore                              = "more"
     let buttonMoreStop                              = "stop"
-    
+
     // Text -  OnlyOffice - Collabora - QuickLook
     //
     let editorText                                  = "text"
@@ -193,19 +193,19 @@ class NCGlobal: NSObject {
     let templateDocument                            = "document"
     let templateSpreadsheet                         = "spreadsheet"
     let templatePresentation                        = "presentation"
-    
+
     // Rich Workspace
     //
     let fileNameRichWorkspace                       = "Readme.md"
-    
+
     // Extension
     @objc let extensionPreview                      = "ico"
-    
+
     // ContentPresenter
     //
     @objc let dismissAfterSecond: TimeInterval      = 4
     @objc let dismissAfterSecondLong: TimeInterval  = 10
-    
+
     // Error
     //
     @objc let errorNoError: Int                     = 0
@@ -238,23 +238,23 @@ class NCGlobal: NSObject {
     @objc let permissionCanDelete                   = "D"
     @objc let permissionCanRename                   = "N"
     @objc let permissionCanMove                     = "V"
-    
-    //Share permission
-    //permissions - (int) 1 = read; 2 = update; 4 = create; 8 = delete; 16 = share; 31 = all
+
+    // Share permission
+    // permissions - (int) 1 = read; 2 = update; 4 = create; 8 = delete; 16 = share; 31 = all
     //
     @objc let permissionReadShare: Int              = 1
     @objc let permissionUpdateShare: Int            = 2
     @objc let permissionCreateShare: Int            = 4
     @objc let permissionDeleteShare: Int            = 8
     @objc let permissionShareShare: Int             = 16
-    
+
     @objc let permissionMinFileShare: Int           = 1
     @objc let permissionMaxFileShare: Int           = 19
     @objc let permissionMinFolderShare: Int         = 1
     @objc let permissionMaxFolderShare: Int         = 31
     @objc let permissionDefaultFileRemoteShareNoSupportShareOption: Int     = 3
     @objc let permissionDefaultFolderRemoteShareNoSupportShareOption: Int   = 15
-        
+
     // Filename Mask and Type
     //
     let keyFileNameMask                             = "fileNameMask"
@@ -304,7 +304,7 @@ class NCGlobal: NSObject {
     let metadataStatusInUpload: Int                 = 2
     let metadataStatusUploading: Int                = 3
     let metadataStatusUploadError: Int              = 4
-    
+
     // Notification Center
     //
     @objc let notificationCenterApplicationDidEnterBackground   = "applicationDidEnterBackground"
@@ -335,7 +335,7 @@ class NCGlobal: NSObject {
     let notificationCenterUploadCancelFile                      = "uploadCancelFile"                // userInfo: ocId, serverUrl, account
 
     let notificationCenterProgressTask                          = "progressTask"                    // userInfo: account, ocId, serverUrl, status, progress, totalBytes, totalBytesExpected
-    
+
     let notificationCenterCreateFolder                          = "createFolder"                    // userInfo: ocId
     let notificationCenterDeleteFile                            = "deleteFile"                      // userInfo: ocId, fileNameView, classFile, onlyLocalCache
     let notificationCenterRenameFile                            = "renameFile"                      // userInfo: ocId, errorCode, errorDescription
@@ -347,47 +347,19 @@ class NCGlobal: NSObject {
     let notificationCenterMenuPDFDisplayDirection               = "menuPDFDisplayDirection"         // userInfo: direction
     let notificationCenterMenuGotToPageInPDF                    = "menuGotToPageInPDF"
     let notificationCenterMenuDetailClose                       = "menuDetailClose"
-    
+
     let notificationCenterChangedLocation                       = "changedLocation"
     let notificationStatusAuthorizationChangedLocation          = "statusAuthorizationChangedLocation"
-    
+
     let notificationCenterShareChangePermissions                = "shareChangePermissions"          // userInfo: idShare, permissions, hideDownload
-    
+
     let notificationCenterDownloadedThumbnail                   = "DownloadedThumbnail"             // userInfo: ocId
-    
+
     let notificationCenterHidePlayerToolBar                     = "hidePlayerToolBar"               // userInfo: ocId
     let notificationCenterShowPlayerToolBar                     = "showPlayerToolBar"               // userInfo: ocId, enableTimerAutoHide
-    
     let notificationCenterOpenMediaDetail                       = "openMediaDetail"                 // userInfo: ocId
 
     let notificationCenterReloadMediaPage                       = "reloadMediaPage"
     let notificationCenterPlayMedia                             = "playMedia"
     let notificationCenterPauseMedia                            = "pauseMedia"
 }
-
-//let rootView = UIApplication.shared.keyWindow?.rootViewController?.view
-
-/*
-DispatchQueue.main.async {
-DispatchQueue.main.asyncAfter(deadline: .now() + 0.1)
-DispatchQueue.global().async
-DispatchQueue.global(qos: .background).async
-
-#if targetEnvironment(simulator)
-#endif
-
-dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
-dispatch_async(dispatch_get_main_queue(), ^{
-dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
-
-#if TARGET_OS_SIMULATOR
-#endif
-
-if let popoverController = alertController.popoverPresentationController {
-    popoverController.sourceView = self.view
-    popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
-    popoverController.permittedArrowDirections = []
-}
-
-@discardableResult
-*/

+ 76 - 72
iOSClient/Networking/NCAutoUpload.swift

@@ -30,44 +30,44 @@ class NCAutoUpload: NSObject, CLLocationManagerDelegate {
         let instance = NCAutoUpload()
         return instance
     }()
-    
+
     private let appDelegate = UIApplication.shared.delegate as! AppDelegate
     public var locationManager: CLLocationManager?
     private var endForAssetToUpload: Bool = false
 
     // MARK: -
-    
+
     @objc func startSignificantChangeUpdates() {
-        
+
         if locationManager == nil {
-            
-            locationManager = CLLocationManager.init()
+
+            locationManager = CLLocationManager()
             locationManager?.delegate = self
             locationManager?.distanceFilter = 10
         }
-        
+
         locationManager?.requestAlwaysAuthorization()
         locationManager?.startMonitoringSignificantLocationChanges()
     }
-    
+
     @objc func stopSignificantChangeUpdates() {
-        
+
         locationManager?.stopMonitoringSignificantLocationChanges()
     }
-    
+
     func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
-        
+
         let location = locations.last
         guard let latitude = location?.coordinate.latitude else { return }
         guard let longitude = location?.coordinate.longitude else { return }
-        
+
         NCCommunicationCommon.shared.writeLog("Location manager: latitude \(latitude) longitude \(longitude)")
-        
+
         if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
             if activeAccount.autoUpload && activeAccount.autoUploadBackground && UIApplication.shared.applicationState == UIApplication.State.background {
-                NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: nil) { (hasPermission) in
+                NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: nil) { hasPermission in
                     if hasPermission {
-                        self.uploadAssetsNewAndFull(viewController: nil, selector: NCGlobal.shared.selectorUploadAutoUpload, log: "Change location") { (items) in
+                        self.uploadAssetsNewAndFull(viewController: nil, selector: NCGlobal.shared.selectorUploadAutoUpload, log: "Change location") { items in
                             NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUpdateBadgeNumber)
                             if items > 0 {
                                 self.appDelegate.networkingProcessUpload?.startProcess()
@@ -78,38 +78,38 @@ class NCAutoUpload: NSObject, CLLocationManagerDelegate {
             }
         }
     }
-    
+
     func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
         if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.authorizedAlways {
             NCManageDatabase.shared.setAccountAutoUploadProperty("autoUploadBackground", state: false)
             self.stopSignificantChangeUpdates()
         }
     }
-    
+
     func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
-        NCAskAuthorization.shared.askAuthorizationLocationManager() { (hasFullPermissions) in
+        NCAskAuthorization.shared.askAuthorizationLocationManager { hasFullPermissions in
             if !hasFullPermissions {
                 NCManageDatabase.shared.setAccountAutoUploadProperty("autoUploadBackground", state: false)
                 self.stopSignificantChangeUpdates()
             }
         }
     }
-    
+
     // MARK: -
-    
-    @objc func initAutoUpload(viewController: UIViewController?, completion: @escaping (_ items: Int)->()) {
+
+    @objc func initAutoUpload(viewController: UIViewController?, completion: @escaping (_ items: Int) -> Void) {
         if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
             if activeAccount.autoUpload {
-                NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { (hasPermission) in
+                NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { hasPermission in
                     if hasPermission {
-                        self.uploadAssetsNewAndFull(viewController:viewController, selector: NCGlobal.shared.selectorUploadAutoUpload, log: "Init Auto Upload") { (items) in
+                        self.uploadAssetsNewAndFull(viewController: viewController, selector: NCGlobal.shared.selectorUploadAutoUpload, log: "Init Auto Upload") { items in
                             if items > 0 {
                                 self.appDelegate.networkingProcessUpload?.startProcess()
                             }
                             completion(items)
                         }
                         if activeAccount.autoUploadBackground {
-                            NCAskAuthorization.shared.askAuthorizationLocationManager() { (hasFullPermissions) in
+                            NCAskAuthorization.shared.askAuthorizationLocationManager { hasFullPermissions in
                                 if hasFullPermissions {
                                     self.startSignificantChangeUpdates()
                                 } else {
@@ -132,32 +132,32 @@ class NCAutoUpload: NSObject, CLLocationManagerDelegate {
             completion(0)
         }
     }
-    
+
     @objc func autoUploadFullPhotos(viewController: UIViewController?, log: String) {
-        NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: appDelegate.window?.rootViewController) { (hasPermission) in
+        NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: appDelegate.window?.rootViewController) { hasPermission in
             if hasPermission {
                 NCContentPresenter.shared.messageNotification("_attention_", description: "_create_full_upload_", delay: NCGlobal.shared.dismissAfterSecondLong, type: .info, errorCode: NCGlobal.shared.errorNoError, priority: .max)
                 NCUtility.shared.startActivityIndicator(backgroundView: nil, blurEffect: true)
-                self.uploadAssetsNewAndFull(viewController: viewController, selector: NCGlobal.shared.selectorUploadAutoUploadAll, log: log) { (items) in
+                self.uploadAssetsNewAndFull(viewController: viewController, selector: NCGlobal.shared.selectorUploadAutoUploadAll, log: log) { _ in
                     NCUtility.shared.stopActivityIndicator()
                 }
             }
         }
     }
-    
-    private func uploadAssetsNewAndFull(viewController: UIViewController?, selector: String, log: String, completion: @escaping (_ items: Int)->()) {
-        
+
+    private func uploadAssetsNewAndFull(viewController: UIViewController?, selector: String, log: String, completion: @escaping (_ items: Int) -> Void) {
+
         if appDelegate.account == "" { return }
-        
+
         guard let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", appDelegate.account)) else { return }
         let autoUploadPath = NCManageDatabase.shared.getAccountAutoUploadPath(urlBase: account.urlBase, account: account.account)
         var counterLivePhoto: Int = 0
         var metadataFull: [tableMetadata] = []
         var counterItemsUpload: Int = 0
         DispatchQueue.global(qos: .background).async {
-        
-            self.getCameraRollAssets(viewController: viewController, account: account, selector: selector, alignPhotoLibrary: false) { (assets) in
-                
+
+            self.getCameraRollAssets(viewController: viewController, account: account, selector: selector, alignPhotoLibrary: false) { assets in
+
                 if assets == nil || assets?.count == 0 {
                     NCCommunicationCommon.shared.writeLog("Automatic upload, no new assets found [" + log + "]")
                     DispatchQueue.main.async {
@@ -168,7 +168,7 @@ class NCAutoUpload: NSObject, CLLocationManagerDelegate {
                     NCCommunicationCommon.shared.writeLog("Automatic upload, new \(assets?.count ?? 0) assets found [" + log + "]")
                 }
                 guard let assets = assets else { return }
-                
+
                 // Create the folder for auto upload & if request the subfolders
                 if !NCNetworking.shared.createFolder(assets: assets, selector: selector, useSubFolder: account.autoUploadCreateSubfolder, account: account.account, urlBase: account.urlBase) {
                     DispatchQueue.main.async {
@@ -178,39 +178,43 @@ class NCAutoUpload: NSObject, CLLocationManagerDelegate {
                         return completion(counterItemsUpload)
                     }
                 }
-                
+
                 self.endForAssetToUpload = false
-                
+
                 for asset in assets {
-                    
+
                     var livePhoto = false
                     var session: String = ""
                     guard let assetDate = asset.creationDate else { continue }
                     let assetMediaType = asset.mediaType
                     let formatter = DateFormatter()
                     var serverUrl: String = ""
-                    
+
                     let fileName = CCUtility.createFileName(asset.value(forKey: "filename") as? String, fileDate: assetDate, fileType: assetMediaType, keyFileName: NCGlobal.shared.keyFileNameAutoUploadMask, keyFileNameType: NCGlobal.shared.keyFileNameAutoUploadType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginalAutoUpload, forcedNewFileName: false)!
-                    
+
                     if asset.mediaSubtypes.contains(.photoLive) && CCUtility.getLivePhoto() {
                         livePhoto = true
                     }
-                    
+
                     if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
                         session = NCCommunicationCommon.shared.sessionIdentifierUpload
                     } else {
-                        if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto == false { session = NCNetworking.shared.sessionIdentifierBackground }
-                        else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo == false { session = NCNetworking.shared.sessionIdentifierBackground }
-                        else if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto { session = NCNetworking.shared.sessionIdentifierBackgroundWWan }
-                        else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo { session = NCNetworking.shared.sessionIdentifierBackgroundWWan }
-                        else { session = NCNetworking.shared.sessionIdentifierBackground }
+                        if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto == false {
+                            session = NCNetworking.shared.sessionIdentifierBackground
+                        } else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo == false {
+                            session = NCNetworking.shared.sessionIdentifierBackground
+                        } else if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto {
+                            session = NCNetworking.shared.sessionIdentifierBackgroundWWan
+                        } else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo {
+                            session = NCNetworking.shared.sessionIdentifierBackgroundWWan
+                        } else { session = NCNetworking.shared.sessionIdentifierBackground }
                     }
-                    
+
                     formatter.dateFormat = "yyyy"
                     let yearString = formatter.string(from: assetDate)
                     formatter.dateFormat = "MM"
                     let monthString = formatter.string(from: assetDate)
-                    
+
                     if account.autoUploadCreateSubfolder {
                         serverUrl = autoUploadPath + "/" + yearString + "/" + monthString
                     } else {
@@ -223,15 +227,15 @@ class NCAutoUpload: NSObject, CLLocationManagerDelegate {
                     if ext == "HEIC" && CCUtility.getFormatCompatibility() {
                         fileNameSearchMetadata = (fileNameSearchMetadata as NSString).deletingPathExtension + ".jpg"
                     }
-                    
+
                     if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account.account, serverUrl, fileNameSearchMetadata)) != nil {
-                        
+
                         if selector == NCGlobal.shared.selectorUploadAutoUpload {
                             NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
                         }
-                        
+
                     } else {
-                        
+
                         /* INSERT METADATA FOR UPLOAD */
                         let metadataForUpload = NCManageDatabase.shared.createMetadata(account: account.account, user: account.user, userId: account.userId, fileName: fileName, fileNameView: fileName, ocId: NSUUID().uuidString, serverUrl: serverUrl, urlBase: account.urlBase, url: "", contentType: "", livePhoto: livePhoto)
                         metadataForUpload.assetLocalIdentifier = asset.localIdentifier
@@ -241,10 +245,10 @@ class NCAutoUpload: NSObject, CLLocationManagerDelegate {
                         metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
                         if assetMediaType == PHAssetMediaType.video {
                             metadataForUpload.classFile = NCCommunicationCommon.typeClassFile.video.rawValue
-                        } else if (assetMediaType == PHAssetMediaType.image) {
+                        } else if assetMediaType == PHAssetMediaType.image {
                             metadataForUpload.classFile = NCCommunicationCommon.typeClassFile.image.rawValue
                         }
-                        
+
                         if selector == NCGlobal.shared.selectorUploadAutoUpload {
                             NCCommunicationCommon.shared.writeLog("Automatic upload added \(metadataForUpload.fileNameView) (\(metadataForUpload.size) bytes) with Identifier \(metadataForUpload.assetLocalIdentifier)")
                             self.appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: [metadataForUpload], verifyAlreadyExists: true)
@@ -253,16 +257,16 @@ class NCAutoUpload: NSObject, CLLocationManagerDelegate {
                             metadataFull.append(metadataForUpload)
                         }
                         counterItemsUpload += 1
-                        
+
                         /* INSERT METADATA MOV LIVE PHOTO FOR UPLOAD */
                         if livePhoto {
-                            
+
                             counterLivePhoto += 1
                             let fileName = (fileName as NSString).deletingPathExtension + ".mov"
                             let ocId = NSUUID().uuidString
                             let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
-                            
-                            CCUtility.extractLivePhotoAsset(asset, filePath: filePath) { (url) in
+
+                            CCUtility.extractLivePhotoAsset(asset, filePath: filePath) { url in
                                 if url != nil {
                                     let metadataForUpload = NCManageDatabase.shared.createMetadata(account: account.account, user: account.user, userId: account.userId, fileName: fileName, fileNameView: fileName, ocId: ocId, serverUrl: serverUrl, urlBase: account.urlBase, url: "", contentType: "", livePhoto: livePhoto)
                                     metadataForUpload.session = session
@@ -270,11 +274,11 @@ class NCAutoUpload: NSObject, CLLocationManagerDelegate {
                                     metadataForUpload.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
                                     metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
                                     metadataForUpload.classFile = NCCommunicationCommon.typeClassFile.video.rawValue
-                                    
+
                                     if selector == NCGlobal.shared.selectorUploadAutoUpload {
                                         NCCommunicationCommon.shared.writeLog("Automatic upload added Live Photo \(metadataForUpload.fileNameView) (\(metadataForUpload.size) bytes) with Identifier \(metadataForUpload.assetLocalIdentifier)")
                                         self.appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: [metadataForUpload], verifyAlreadyExists: true)
-                                        
+
                                     } else if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
                                         metadataFull.append(metadataForUpload)
                                     }
@@ -293,9 +297,9 @@ class NCAutoUpload: NSObject, CLLocationManagerDelegate {
                         }
                     }
                 }
-                
+
                 self.endForAssetToUpload = true
-                
+
                 if counterLivePhoto == 0 {
                     DispatchQueue.main.async {
                         if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
@@ -307,12 +311,12 @@ class NCAutoUpload: NSObject, CLLocationManagerDelegate {
             }
         }
     }
-    
+
     // MARK: -
 
     @objc func alignPhotoLibrary(viewController: UIViewController?) {
         if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
-            getCameraRollAssets(viewController: viewController, account: activeAccount, selector: NCGlobal.shared.selectorUploadAutoUploadAll, alignPhotoLibrary: true) { (assets) in
+            getCameraRollAssets(viewController: viewController, account: activeAccount, selector: NCGlobal.shared.selectorUploadAutoUploadAll, alignPhotoLibrary: true) { assets in
                 NCManageDatabase.shared.clearTable(tablePhotoLibrary.self, account: activeAccount.account)
                 if let assets = assets {
                     NCManageDatabase.shared.addPhotoLibrary(assets, account: activeAccount.account)
@@ -321,14 +325,14 @@ class NCAutoUpload: NSObject, CLLocationManagerDelegate {
             }
         }
     }
-    
-    private func getCameraRollAssets(viewController: UIViewController?, account: tableAccount, selector: String, alignPhotoLibrary: Bool, completion: @escaping (_ assets: [PHAsset]?)->()) {
-                
-        NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { (hasPermission) in
+
+    private func getCameraRollAssets(viewController: UIViewController?, account: tableAccount, selector: String, alignPhotoLibrary: Bool, completion: @escaping (_ assets: [PHAsset]?) -> Void) {
+
+        NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { hasPermission in
             if hasPermission {
                 let assetCollection = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.smartAlbumUserLibrary, options: nil)
                 if assetCollection.count > 0 {
-                    
+
                     let predicateImage = NSPredicate(format: "mediaType == %i", PHAssetMediaType.image.rawValue)
                     let predicateVideo = NSPredicate(format: "mediaType == %i", PHAssetMediaType.video.rawValue)
                     var predicate: NSPredicate?
@@ -344,15 +348,15 @@ class NCAutoUpload: NSObject, CLLocationManagerDelegate {
                     } else {
                         return completion(nil)
                     }
-                    
+
                     fetchOptions.predicate = predicate
                     let assets: PHFetchResult<PHAsset> = PHAsset.fetchAssets(in: assetCollection.firstObject!, options: fetchOptions)
-                    
+
                     if selector == NCGlobal.shared.selectorUploadAutoUpload {
                         var creationDate = ""
                         var idAsset = ""
                         let idsAsset = NCManageDatabase.shared.getPhotoLibraryIdAsset(image: account.autoUploadImage, video: account.autoUploadVideo, account: account.account)
-                        assets.enumerateObjects { (asset, _, _) in
+                        assets.enumerateObjects { asset, _, _ in
                             if asset.creationDate != nil { creationDate = String(describing: asset.creationDate!) }
                             idAsset = account.account + asset.localIdentifier + creationDate
                             if !(idsAsset?.contains(idAsset) ?? false) {
@@ -360,7 +364,7 @@ class NCAutoUpload: NSObject, CLLocationManagerDelegate {
                             }
                         }
                     } else {
-                        assets.enumerateObjects { (asset, _, _) in
+                        assets.enumerateObjects { asset, _, _ in
                             newAssets.append(asset)
                         }
                     }

Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 283 - 264
iOSClient/Networking/NCNetworking.swift


+ 20 - 20
iOSClient/Networking/NCNetworkingCheckRemoteUser.swift

@@ -28,69 +28,69 @@ import NCCommunication
         let instance = NCNetworkingCheckRemoteUser()
         return instance
     }()
-    
+
     let appDelegate = UIApplication.shared.delegate as! AppDelegate
     var checkRemoteUserInProgress = false
 
     @objc func checkRemoteUser(account: String, errorCode: Int, errorDescription: String) {
-           
+
         if self.checkRemoteUserInProgress {
             return
         } else {
             self.checkRemoteUserInProgress = true
         }
-        
+
         let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
         guard let tableAccount = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) else {
             self.checkRemoteUserInProgress = false
             return
         }
-        
+
         if serverVersionMajor >= NCGlobal.shared.nextcloudVersion17 {
-            
+
             if errorCode == 401 {
-                
+
                 let token = CCUtility.getPassword(account)!
                 if token == "" {
                     self.checkRemoteUserInProgress = false
                     return
                 }
-                
-                NCCommunication.shared.getRemoteWipeStatus(serverUrl: tableAccount.urlBase, token: token) { (account, wipe, errorCode, errorDescriptiuon) in
-                    
+
+                NCCommunication.shared.getRemoteWipeStatus(serverUrl: tableAccount.urlBase, token: token) { account, wipe, errorCode, _ in
+
                     if wipe {
-                        
+
                         self.appDelegate.deleteAccount(account, wipe: true)
                         NCContentPresenter.shared.messageNotification(tableAccount.user, description: "_wipe_account_", delay: NCGlobal.shared.dismissAfterSecondLong, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError, priority: .max)
-                        NCCommunication.shared.setRemoteWipeCompletition(serverUrl: tableAccount.urlBase, token: token) { (account, errorCode, errorDescription) in print("wipe") }
-                        
+                        NCCommunication.shared.setRemoteWipeCompletition(serverUrl: tableAccount.urlBase, token: token) { _, _, _ in print("wipe") }
+
                     } else {
-                        
+
                         if UIApplication.shared.applicationState == .active &&  NCCommunication.shared.isNetworkReachable() {
                             let description = String.localizedStringWithFormat(NSLocalizedString("_error_check_remote_user_", comment: ""), tableAccount.user, tableAccount.urlBase)
                             NCContentPresenter.shared.messageNotification("_error_", description: description, delay: NCGlobal.shared.dismissAfterSecondLong, type: NCContentPresenter.messageType.error, errorCode: errorCode, priority: .max)
                             CCUtility.setPassword(account, password: nil)
                         }
                     }
-                    
+
                     self.checkRemoteUserInProgress = false
                 }
-                
+
             } else {
-                
+
                 NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecondLong, type: NCContentPresenter.messageType.error, errorCode: errorCode, priority: .max)
-                
+
                 self.checkRemoteUserInProgress = false
             }
-            
+
         } else if CCUtility.getPassword(account) != "" {
-               
+
             if UIApplication.shared.applicationState == .active &&  NCCommunication.shared.isNetworkReachable() {
                 let description = String.localizedStringWithFormat(NSLocalizedString("_error_check_remote_user_", comment: ""), tableAccount.user, tableAccount.urlBase)
                 NCContentPresenter.shared.messageNotification("_error_", description: description, delay: NCGlobal.shared.dismissAfterSecondLong, type: NCContentPresenter.messageType.error, errorCode: errorCode, priority: .max)
                 CCUtility.setPassword(account, password: nil)
             }
-            
+
             self.checkRemoteUserInProgress = false
         }
     }

+ 92 - 81
iOSClient/Networking/NCNetworkingChunkedUpload.swift

@@ -26,167 +26,178 @@ import NCCommunication
 import Queuer
 
 extension NCNetworking {
-    
-    internal func uploadChunkedFile(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
-        
+
+    internal func uploadChunkedFile(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
+
         let directoryProviderStorageOcId = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)!
         let chunkFolder = NCManageDatabase.shared.getChunkFolder(account: metadata.account, ocId: metadata.ocId)
         let chunkFolderPath = metadata.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: metadata.account) + "/uploads/" + metadata.userId + "/" + chunkFolder
         let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
         let chunkSize = CCUtility.getChunkSize()
-        
+
         var uploadErrorCode: Int = 0
         var uploadErrorDescription: String = ""
         var filesNames = NCManageDatabase.shared.getChunks(account: metadata.account, ocId: metadata.ocId)
         if filesNames.count == 0 {
-               
+
             filesNames = NCCommunicationCommon.shared.chunkedFile(inputDirectory: directoryProviderStorageOcId, outputDirectory: directoryProviderStorageOcId, fileName: metadata.fileName, chunkSizeMB: chunkSize)
-            
+
             if filesNames.count > 0 {
                 NCManageDatabase.shared.addChunks(account: metadata.account, ocId: metadata.ocId, chunkFolder: chunkFolder, fileNames: filesNames)
             } else {
-                NCContentPresenter.shared.messageNotification("_error_", description: "_err_file_not_found_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode:NCGlobal.shared.errorReadFile)
+                NCContentPresenter.shared.messageNotification("_error_", description: "_err_file_not_found_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorReadFile)
                 NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
                 return completion(uploadErrorCode, uploadErrorDescription)
             }
-            
+
         } else {
-            
-            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
+
+            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl": metadata.serverUrl])
         }
 
         NCContentPresenter.shared.noteTop(text: NSLocalizedString("_upload_chunk_", comment: ""), image: nil, type: NCContentPresenter.messageType.info, delay: NCGlobal.shared.dismissAfterSecond, priority: .max)
-                
-        createChunkedFolder(chunkFolderPath: chunkFolderPath, account: metadata.account) { (errorCode, errorDescription) in
-            
+
+        createChunkedFolder(chunkFolderPath: chunkFolderPath, account: metadata.account) { errorCode, errorDescription in
+
             start()
 
             if errorCode == 0 {
-                    
+
                 NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId": metadata.ocId])
-                
+
                 for fileName in filesNames {
-                        
+
                     let serverUrlFileName = chunkFolderPath + "/" + fileName
                     let fileNameChunkLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: fileName)!
-                    
+
                     var size: Int64?
                     if let tableChunk = NCManageDatabase.shared.getChunk(account: metadata.account, fileName: fileName) {
                         size = tableChunk.size - NCUtilityFileSystem.shared.getFileSize(filePath: fileNameChunkLocalPath)
                     }
-                                            
+
                     let semaphore = Semaphore()
-                                                
-                    NCCommunication.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameChunkLocalPath, requestHandler: { (request) in
-                            
+
+                    NCCommunication.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameChunkLocalPath, requestHandler: { request in
+
                         self.uploadRequest[fileNameLocalPath] = request
-                        
-                    }, taskHandler: { (task) in
-                        
+
+                    }, taskHandler: { task in
+
                         NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: NCGlobal.shared.metadataStatusUploading)
-                        
-                        NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId":metadata.ocId])
-                        
+
+                        NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId": metadata.ocId])
+
                         NCCommunicationCommon.shared.writeLog("Upload chunk: " + fileName)
-                       
-                    }, progressHandler: { (progress) in
-                        
+
+                    }, progressHandler: { progress in
+
                         if let size = size {
-                            
+
                             let totalBytesExpected = size + progress.completedUnitCount
                             let totalBytes = metadata.size
                             let fractionCompleted = Float(totalBytesExpected) / Float(totalBytes)
-                                
-                            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterProgressTask, object: nil, userInfo: ["account":metadata.account, "ocId":metadata.ocId, "fileName":metadata.fileName, "serverUrl":metadata.serverUrl, "status":NSNumber(value: NCGlobal.shared.metadataStatusInUpload), "progress":NSNumber(value: fractionCompleted), "totalBytes":NSNumber(value: totalBytes), "totalBytesExpected":NSNumber(value: totalBytesExpected)])
+
+                            NotificationCenter.default.postOnMainThread(
+                                name: NCGlobal.shared.notificationCenterProgressTask,
+                                object: nil,
+                                userInfo: [
+                                    "account": metadata.account,
+                                    "ocId": metadata.ocId,
+                                    "fileName": metadata.fileName,
+                                    "serverUrl": metadata.serverUrl,
+                                    "status": NSNumber(value: NCGlobal.shared.metadataStatusInUpload),
+                                    "progress": NSNumber(value: fractionCompleted),
+                                    "totalBytes": NSNumber(value: totalBytes),
+                                    "totalBytesExpected": NSNumber(value: totalBytesExpected)])
                         }
-                        
-                    }) { (_, _, _, _, _, _, _, errorCode, errorDescription) in
-                           
+
+                    }) { _, _, _, _, _, _, _, errorCode, errorDescription in
+
                         self.uploadRequest[fileNameLocalPath] = nil
                         uploadErrorCode = errorCode
                         uploadErrorDescription = errorDescription
                         semaphore.continue()
                     }
-                        
+
                     semaphore.wait()
-                        
+
                     if uploadErrorCode == 0 {
                         NCManageDatabase.shared.deleteChunk(account: metadata.account, ocId: metadata.ocId, fileName: fileName)
                     } else {
                         break
                     }
                 }
-                    
+
                 if uploadErrorCode == 0 {
-                        
+
                     // Assembling the chunks
                     let serverUrlFileNameSource = chunkFolderPath + "/.file"
                     let pathServerUrl = CCUtility.returnPathfromServerUrl(metadata.serverUrl, urlBase: metadata.urlBase, account: metadata.account)!
                     let serverUrlFileNameDestination = metadata.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: metadata.account) + "/files/" + metadata.userId + pathServerUrl + "/" + metadata.fileName
-                    
-                    var addCustomHeaders: [String:String] = [:]
+
+                    var addCustomHeaders: [String: String] = [:]
                     let creationDate = "\(metadata.creationDate.timeIntervalSince1970)"
                     let modificationDate = "\(metadata.date.timeIntervalSince1970)"
-                        
+
                     addCustomHeaders["X-OC-CTime"] = creationDate
                     addCustomHeaders["X-OC-MTime"] = modificationDate
 
-                    NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: true, addCustomHeaders: addCustomHeaders) { (_, errorCode, errorDescription) in
-                                   
+                    NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: true, addCustomHeaders: addCustomHeaders) { _, errorCode, errorDescription in
+
                         NCCommunicationCommon.shared.writeLog("Assembling chunk with error code: \(errorCode)")
-                        
+
                         if errorCode == 0 {
-                                                            
+
                             let serverUrl = metadata.serverUrl
 
                             NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
                             NCManageDatabase.shared.deleteChunks(account: metadata.account, ocId: metadata.ocId)
                             NCUtilityFileSystem.shared.deleteFile(filePath: directoryProviderStorageOcId)
 
-                            self.readFile(serverUrlFileName: serverUrlFileNameDestination, account: metadata.account) { (_, metadata, _, _) in
-                                    
+                            self.readFile(serverUrlFileName: serverUrlFileNameDestination, account: metadata.account) { _, metadata, _, _ in
+
                                 if errorCode == 0, let metadata = metadata {
-                                    
+
                                     NCManageDatabase.shared.addMetadata(metadata)
-                                    NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl":serverUrl])
-                                    
+                                    NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl": serverUrl])
+
                                 } else {
-                                    
+
                                     NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced, userInfo: ["serverUrl": serverUrl])
                                 }
-                                
+
                                 completion(errorCode, errorDescription)
                             }
-                            
+
                         } else {
-                            
+
                             self.uploadChunkFileError(metadata: metadata, chunkFolderPath: chunkFolderPath, directoryProviderStorageOcId: directoryProviderStorageOcId, errorCode: errorCode, errorDescription: errorDescription)
                             completion(errorCode, errorDescription)
                         }
                     }
-                                                    
+
                 } else {
-                                                        
+
                     self.uploadChunkFileError(metadata: metadata, chunkFolderPath: chunkFolderPath, directoryProviderStorageOcId: directoryProviderStorageOcId, errorCode: uploadErrorCode, errorDescription: uploadErrorDescription)
                     completion(errorCode, errorDescription)
                 }
-                
+
             } else {
-                
+
                 self.uploadChunkFileError(metadata: metadata, chunkFolderPath: chunkFolderPath, directoryProviderStorageOcId: directoryProviderStorageOcId, errorCode: errorCode, errorDescription: errorDescription)
                 completion(errorCode, errorDescription)
             }
         }
     }
-    
-    private func createChunkedFolder(chunkFolderPath: String, account: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
-        
-        NCCommunication.shared.readFileOrFolder(serverUrlFileName: chunkFolderPath, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: NCCommunicationCommon.shared.backgroundQueue) { (_, _, _, errorCode, errorDescription) in
-        
+
+    private func createChunkedFolder(chunkFolderPath: String, account: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
+
+        NCCommunication.shared.readFileOrFolder(serverUrlFileName: chunkFolderPath, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: NCCommunicationCommon.shared.backgroundQueue) { _, _, _, errorCode, errorDescription in
+
             if errorCode == 0 {
                 completion(0, "")
             } else if errorCode == NCGlobal.shared.errorResourceNotFound {
-                NCCommunication.shared.createFolder(chunkFolderPath, queue: NCCommunicationCommon.shared.backgroundQueue) { (_, _, _, errorCode, errorDescription) in
+                NCCommunication.shared.createFolder(chunkFolderPath, queue: NCCommunicationCommon.shared.backgroundQueue) { _, _, _, errorCode, errorDescription in
                     completion(errorCode, errorDescription)
                 }
             } else {
@@ -196,26 +207,26 @@ extension NCNetworking {
     }
 
     private func uploadChunkFileError(metadata: tableMetadata, chunkFolderPath: String, directoryProviderStorageOcId: String, errorCode: Int, errorDescription: String) {
-              
+
         var errorDescription = errorDescription
-        
+
         NCCommunicationCommon.shared.writeLog("Upload chunk error code: \(errorCode)")
-        
+
         if errorCode == NSURLErrorCancelled || errorCode == NCGlobal.shared.errorRequestExplicityCancelled {
-            
+
             // Delete chunk folder
-            NCCommunication.shared.deleteFileOrFolder(chunkFolderPath) { (_, _, _) in }
-            
+            NCCommunication.shared.deleteFileOrFolder(chunkFolderPath) { _, _, _ in }
+
             NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
             NCManageDatabase.shared.deleteChunks(account: metadata.account, ocId: metadata.ocId)
             NCUtilityFileSystem.shared.deleteFile(filePath: directoryProviderStorageOcId)
-            
-            NCCommunication.shared.deleteFileOrFolder(chunkFolderPath) { (_, _, _) in }
-            
-            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "account":metadata.account])
-            
+
+            NCCommunication.shared.deleteFileOrFolder(chunkFolderPath) { _, _, _ in }
+
+            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
+
         } else {
-            
+
             // NO report for the connection lost
             if errorCode == NCGlobal.shared.errorConnectionLost {
                 errorDescription = ""
@@ -223,10 +234,10 @@ extension NCNetworking {
                 let description = errorDescription + " code: \(errorCode)"
                 NCContentPresenter.shared.messageNotification("_error_", description: description, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError)
             }
-                        
+
             NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: NCGlobal.shared.metadataStatusNormal, status: NCGlobal.shared.metadataStatusUploadError)
         }
-        
-        NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId":metadata.ocId, "ocIdTemp":metadata.ocId, "errorCode":errorCode, "errorDescription":""])
+
+        NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "ocIdTemp": metadata.ocId, "errorCode": errorCode, "errorDescription": ""])
     }
 }

+ 150 - 142
iOSClient/Networking/NCNetworkingE2EE.swift

@@ -30,43 +30,43 @@ import Alamofire
         let instance = NCNetworkingE2EE()
         return instance
     }()
-    
-    //MARK: - WebDav Create Folder
-    
-    func createFolder(fileName: String, serverUrl: String, account: String, urlBase: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
-        
+
+    // MARK: - WebDav Create Folder
+
+    func createFolder(fileName: String, serverUrl: String, account: String, urlBase: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
+
         var fileNameFolder = CCUtility.removeForbiddenCharactersServer(fileName)!
         var fileNameFolderUrl = ""
         var fileNameIdentifier = ""
         var key: NSString?
         var initializationVector: NSString?
-        
+
         fileNameFolder = NCUtilityFileSystem.shared.createFileName(fileNameFolder, serverUrl: serverUrl, account: account)
         if fileNameFolder.count == 0 {
             return completion(0, "")
         }
         fileNameIdentifier = CCUtility.generateRandomIdentifier()
         fileNameFolderUrl = serverUrl + "/" + fileNameIdentifier
-       
-        self.lock(account: account, serverUrl: serverUrl) { (directory, e2eToken, errorCode, errorDescription) in
+
+        self.lock(account: account, serverUrl: serverUrl) { directory, e2eToken, errorCode, errorDescription in
             if errorCode == 0 && e2eToken != nil && directory != nil {
-                               
-                NCCommunication.shared.createFolder(fileNameFolderUrl, addCustomHeaders: ["e2e-token" : e2eToken!]) { (account, ocId, date, errorCode, errorDescription) in
+
+                NCCommunication.shared.createFolder(fileNameFolderUrl, addCustomHeaders: ["e2e-token": e2eToken!]) { account, ocId, _, errorCode, errorDescription in
                     if errorCode == 0 {
                         guard let fileId = NCUtility.shared.ocIdToFileId(ocId: ocId) else {
                             // unlock
                             if let tableLock = NCManageDatabase.shared.getE2ETokenLock(account: account, serverUrl: serverUrl) {
-                                NCCommunication.shared.lockE2EEFolder(fileId: tableLock.fileId, e2eToken: tableLock.e2eToken, method: "DELETE") { (_, _, _, _) in }
+                                NCCommunication.shared.lockE2EEFolder(fileId: tableLock.fileId, e2eToken: tableLock.e2eToken, method: "DELETE") { _, _, _, _ in }
                             }
                             return completion(NCGlobal.shared.errorInternalError, "Error convert ocId")
                         }
-                        NCCommunication.shared.markE2EEFolder(fileId: fileId, delete: false) { (account, errorCode, errorDescription) in
+                        NCCommunication.shared.markE2EEFolder(fileId: fileId, delete: false) { account, errorCode, errorDescription in
                             if errorCode == 0 {
-                                                                         
+
                                 let object = tableE2eEncryption()
-                                
+
                                 NCEndToEndEncryption.sharedManager()?.encryptkey(&key, initializationVector: &initializationVector)
-                                
+
                                 object.account = account
                                 object.authenticationTag = nil
                                 object.fileName = fileNameFolder
@@ -74,7 +74,7 @@ import Alamofire
                                 object.fileNamePath = ""
                                 object.key = key! as String
                                 object.initializationVector = initializationVector! as String
-                                
+
                                 if let result = NCManageDatabase.shared.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl)) {
                                     object.metadataKey = result.metadataKey
                                     object.metadataKeyIndex = result.metadataKeyIndex
@@ -85,33 +85,33 @@ import Alamofire
                                 object.mimeType = "httpd/unix-directory"
                                 object.serverUrl = serverUrl
                                 object.version = 1
-                               
-                                let _ = NCManageDatabase.shared.addE2eEncryption(object)
-                                
-                                self.sendE2EMetadata(account: account, serverUrl: serverUrl, fileNameRename: nil, fileNameNewRename: nil, deleteE2eEncryption: nil, urlBase: urlBase) { (e2eToken, errorCode, errorDescription) in
+
+                                _ = NCManageDatabase.shared.addE2eEncryption(object)
+
+                                self.sendE2EMetadata(account: account, serverUrl: serverUrl, fileNameRename: nil, fileNameNewRename: nil, deleteE2eEncryption: nil, urlBase: urlBase) { e2eToken, errorCode, errorDescription in
                                     // unlock
                                     if let tableLock = NCManageDatabase.shared.getE2ETokenLock(account: account, serverUrl: serverUrl) {
-                                        NCCommunication.shared.lockE2EEFolder(fileId: tableLock.fileId, e2eToken: tableLock.e2eToken, method: "DELETE") { (_, _, _, _) in }
+                                        NCCommunication.shared.lockE2EEFolder(fileId: tableLock.fileId, e2eToken: tableLock.e2eToken, method: "DELETE") { _, _, _, _ in }
                                     }
                                     if errorCode == 0 {
                                         NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCreateFolder, userInfo: nil)
                                     }
                                     completion(errorCode, errorDescription)
                                 }
-                                
+
                             } else {
                                 // unlock
                                 if let tableLock = NCManageDatabase.shared.getE2ETokenLock(account: account, serverUrl: serverUrl) {
-                                    NCCommunication.shared.lockE2EEFolder(fileId: tableLock.fileId, e2eToken: tableLock.e2eToken, method: "DELETE") { (_, _, _, _) in }
+                                    NCCommunication.shared.lockE2EEFolder(fileId: tableLock.fileId, e2eToken: tableLock.e2eToken, method: "DELETE") { _, _, _, _ in }
                                 }
                                 completion(errorCode, errorDescription)
                             }
                         }
-                        
+
                     } else {
                         // unlock
                         if let tableLock = NCManageDatabase.shared.getE2ETokenLock(account: account, serverUrl: serverUrl) {
-                            NCCommunication.shared.lockE2EEFolder(fileId: tableLock.fileId, e2eToken: tableLock.e2eToken, method: "DELETE") { (_, _, _, _) in }
+                            NCCommunication.shared.lockE2EEFolder(fileId: tableLock.fileId, e2eToken: tableLock.e2eToken, method: "DELETE") { _, _, _, _ in }
                         }
                         completion(errorCode, errorDescription)
                     }
@@ -121,29 +121,29 @@ import Alamofire
             }
         }
     }
-    
-    //MARK: - WebDav Delete
-    
-    func deleteMetadata(_ metadata: tableMetadata, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
-                        
-        self.lock(account:metadata.account, serverUrl: metadata.serverUrl) { (directory, e2eToken, errorCode, errorDescription) in
+
+    // MARK: - WebDav Delete
+
+    func deleteMetadata(_ metadata: tableMetadata, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
+
+        self.lock(account: metadata.account, serverUrl: metadata.serverUrl) { directory, e2eToken, errorCode, errorDescription in
             if errorCode == 0 && e2eToken != nil && directory != nil {
                 let deleteE2eEncryption = NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", metadata.account, metadata.serverUrl, metadata.fileName)
-                NCNetworking.shared.deleteMetadataPlain(metadata, addCustomHeaders: ["e2e-token" :e2eToken!]) { (errorCode, errorDescription) in
-                    
+                NCNetworking.shared.deleteMetadataPlain(metadata, addCustomHeaders: ["e2e-token": e2eToken!]) { errorCode, errorDescription in
+
                     let home = NCUtilityFileSystem.shared.getHomeServer(account: metadata.account)
                     if metadata.serverUrl != home {
-                        self.sendE2EMetadata(account: metadata.account, serverUrl: metadata.serverUrl, fileNameRename: nil, fileNameNewRename: nil, deleteE2eEncryption: deleteE2eEncryption, urlBase: metadata.urlBase) { (e2eToken, errorCode, errorDescription) in
+                        self.sendE2EMetadata(account: metadata.account, serverUrl: metadata.serverUrl, fileNameRename: nil, fileNameNewRename: nil, deleteE2eEncryption: deleteE2eEncryption, urlBase: metadata.urlBase) { e2eToken, errorCode, errorDescription in
                             // unlock
                             if let tableLock = NCManageDatabase.shared.getE2ETokenLock(account: metadata.account, serverUrl: metadata.serverUrl) {
-                                NCCommunication.shared.lockE2EEFolder(fileId: tableLock.fileId, e2eToken: tableLock.e2eToken, method: "DELETE") { (_, _, _, _) in }
+                                NCCommunication.shared.lockE2EEFolder(fileId: tableLock.fileId, e2eToken: tableLock.e2eToken, method: "DELETE") { _, _, _, _ in }
                             }
                             completion(errorCode, errorDescription)
                         }
                     } else {
                         // unlock
                         if let tableLock = NCManageDatabase.shared.getE2ETokenLock(account: metadata.account, serverUrl: metadata.serverUrl) {
-                            NCCommunication.shared.lockE2EEFolder(fileId: tableLock.fileId, e2eToken: tableLock.e2eToken, method: "DELETE") { (_, _, _, _) in }
+                            NCCommunication.shared.lockE2EEFolder(fileId: tableLock.fileId, e2eToken: tableLock.e2eToken, method: "DELETE") { _, _, _, _ in }
                         }
                         completion(errorCode, errorDescription)
                     }
@@ -153,61 +153,61 @@ import Alamofire
             }
         }
     }
-    
-    //MARK: - WebDav Rename
-    
-    func renameMetadata(_ metadata: tableMetadata, fileNameNew: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
-        
+
+    // MARK: - WebDav Rename
+
+    func renameMetadata(_ metadata: tableMetadata, fileNameNew: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String?) -> Void) {
+
         // verify if exists the new fileName
         if NCManageDatabase.shared.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileName == %@", metadata.account, metadata.serverUrl, fileNameNew)) != nil {
-            
+
             completion(NCGlobal.shared.errorInternalError, "_file_already_exists_")
 
         } else {
-            
-            self.sendE2EMetadata(account: metadata.account, serverUrl: metadata.serverUrl, fileNameRename: metadata.fileName, fileNameNewRename: fileNameNew, deleteE2eEncryption: nil, urlBase: metadata.urlBase) { (e2eToken, errorCode, errorDescription) in
-                
+
+            self.sendE2EMetadata(account: metadata.account, serverUrl: metadata.serverUrl, fileNameRename: metadata.fileName, fileNameNewRename: fileNameNew, deleteE2eEncryption: nil, urlBase: metadata.urlBase) { e2eToken, errorCode, errorDescription in
+
                 if errorCode == 0 {
                     NCManageDatabase.shared.setMetadataFileNameView(serverUrl: metadata.serverUrl, fileName: metadata.fileName, newFileNameView: fileNameNew, account: metadata.account)
-                    
+
                     // Move file system
                     let atPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileNameView
                     let toPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + fileNameNew
                     do {
                         try FileManager.default.moveItem(atPath: atPath, toPath: toPath)
                     } catch { }
-                    
+
                     NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterRenameFile, userInfo: ["ocId": metadata.ocId])
                 }
-                
+
                 // unlock
                 if let tableLock = NCManageDatabase.shared.getE2ETokenLock(account: metadata.account, serverUrl: metadata.serverUrl) {
-                    NCCommunication.shared.lockE2EEFolder(fileId: tableLock.fileId, e2eToken: tableLock.e2eToken, method: "DELETE") { (_, _, _, _) in }
+                    NCCommunication.shared.lockE2EEFolder(fileId: tableLock.fileId, e2eToken: tableLock.e2eToken, method: "DELETE") { _, _, _, _ in }
                 }
-                
+
                 completion(errorCode, errorDescription)
             }
         }
     }
-    
-    //MARK: - Upload
-    
-    func upload(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
-        
+
+    // MARK: - Upload
+
+    func upload(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
+
         let objectE2eEncryption = tableE2eEncryption()
         var key: NSString?, initializationVector: NSString?, authenticationTag: NSString?
         let ocIdTemp = metadata.ocId
         let serverUrl = metadata.serverUrl
-                
+
         // Verify max size
         if metadata.size > NCGlobal.shared.e2eeMaxFileSize {
             NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
 
-            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId":metadata.ocId, "ocIdTemp":ocIdTemp, "errorCode":NCGlobal.shared.errorInternalError, "errorDescription":"E2E Error file too big"])
+            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "ocIdTemp": ocIdTemp, "errorCode": NCGlobal.shared.errorInternalError, "errorDescription": "E2E Error file too big"])
             start()
             return completion(NCGlobal.shared.errorInternalError, "E2E Error file too big")
         }
-        
+
         // Update metadata
         var metadata = tableMetadata.init(value: metadata)
         metadata.fileName = CCUtility.generateRandomIdentifier()!
@@ -215,19 +215,19 @@ import Alamofire
         metadata.session = NCCommunicationCommon.shared.sessionIdentifierUpload
         metadata.sessionError = ""
         NCManageDatabase.shared.addMetadata(metadata)
-        
+
         let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)!
         let fileNameLocalPathRequest = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
         let serverUrlFileName = serverUrl + "/" + metadata.fileName
-        
+
         if NCEndToEndEncryption.sharedManager()?.encryptFileName(metadata.fileNameView, fileNameIdentifier: metadata.fileName, directory: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId), key: &key, initializationVector: &initializationVector, authenticationTag: &authenticationTag) == false {
-            
+
             NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
-            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId":metadata.ocId, "ocIdTemp":ocIdTemp, "errorCode":NCGlobal.shared.errorInternalError, "errorDescription":"_e2e_error_create_encrypted_"])
+            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "ocIdTemp": ocIdTemp, "errorCode": NCGlobal.shared.errorInternalError, "errorDescription": "_e2e_error_create_encrypted_"])
             start()
             return completion(NCGlobal.shared.errorInternalError, "_e2e_error_create_encrypted_")
         }
-        
+
         if let result = NCManageDatabase.shared.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, serverUrl)) {
             objectE2eEncryption.metadataKey = result.metadataKey
             objectE2eEncryption.metadataKeyIndex = result.metadataKeyIndex
@@ -236,7 +236,7 @@ import Alamofire
             objectE2eEncryption.metadataKey = key!.base64EncodedString()
             objectE2eEncryption.metadataKeyIndex = 0
         }
-        
+
         objectE2eEncryption.account = metadata.account
         objectE2eEncryption.authenticationTag = authenticationTag as String?
         objectE2eEncryption.fileName = metadata.fileNameView
@@ -247,178 +247,188 @@ import Alamofire
         objectE2eEncryption.mimeType = metadata.contentType
         objectE2eEncryption.serverUrl = serverUrl
         objectE2eEncryption.version = 1
-        
+
         NCManageDatabase.shared.addE2eEncryption(objectE2eEncryption)
-        
+
         if let getMetadata = NCManageDatabase.shared.getMetadataFromOcId(ocIdTemp) {
             metadata = getMetadata
         } else {
             start()
             return completion(NCGlobal.shared.errorInternalError, "_e2e_error_create_encrypted_")
         }
-        
-        NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
-        
+
+        NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl])
+
         NCContentPresenter.shared.noteTop(text: NSLocalizedString("_upload_e2ee_", comment: ""), image: nil, type: NCContentPresenter.messageType.info, delay: NCGlobal.shared.dismissAfterSecond, priority: .max)
-        
-        NCNetworkingE2EE.shared.sendE2EMetadata(account: metadata.account, serverUrl: serverUrl, fileNameRename: nil, fileNameNewRename: nil, deleteE2eEncryption: nil, urlBase: metadata.urlBase, upload: true) { (e2eToken, errorCode, errorDescription) in
-            
+
+        NCNetworkingE2EE.shared.sendE2EMetadata(account: metadata.account, serverUrl: serverUrl, fileNameRename: nil, fileNameNewRename: nil, deleteE2eEncryption: nil, urlBase: metadata.urlBase, upload: true) { e2eToken, errorCode, errorDescription in
+
             start()
-            
+
             if errorCode == 0 && e2eToken != nil {
-                                                
-                NCCommunication.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: metadata.date as Date, dateModificationFile: metadata.date as Date, addCustomHeaders: ["e2e-token":e2eToken!], requestHandler: { (request) in
-                    
+
+                NCCommunication.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: metadata.date as Date, dateModificationFile: metadata.date as Date, addCustomHeaders: ["e2e-token": e2eToken!], requestHandler: { request in
+
                     NCNetworking.shared.uploadRequest[fileNameLocalPathRequest] = request
                     NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: nil, sessionSelector: nil, sessionTaskIdentifier: nil, status: NCGlobal.shared.metadataStatusUploading)
-                    
-                    NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId":metadata.ocId])
-                
-                }, taskHandler: { (_) in
-                    
-                }, progressHandler: { (progress) in
-                    
-                    NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterProgressTask, userInfo: ["account":metadata.account, "ocId":metadata.ocId, "fileName":metadata.fileName, "serverUrl":serverUrl, "status":NSNumber(value: NCGlobal.shared.metadataStatusInUpload), "progress":NSNumber(value: progress.fractionCompleted), "totalBytes":NSNumber(value: progress.totalUnitCount), "totalBytesExpected":NSNumber(value: progress.completedUnitCount)])
-                    
-                }) { (account, ocId, etag, date, size, allHeaderFields, error, errorCode, errorDescription) in
-                                    
+
+                    NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId": metadata.ocId])
+
+                }, taskHandler: { _ in
+
+                }, progressHandler: { progress in
+
+                    NotificationCenter.default.postOnMainThread(
+                        name: NCGlobal.shared.notificationCenterProgressTask,
+                        userInfo: [
+                            "account": metadata.account,
+                            "ocId": metadata.ocId,
+                            "fileName": metadata.fileName,
+                            "serverUrl": serverUrl,
+                            "status": NSNumber(value: NCGlobal.shared.metadataStatusInUpload),
+                            "progress": NSNumber(value: progress.fractionCompleted),
+                            "totalBytes": NSNumber(value: progress.totalUnitCount),
+                            "totalBytesExpected": NSNumber(value: progress.completedUnitCount)])
+
+                }) { account, ocId, etag, date, _, _, error, errorCode, errorDescription in
+
                     NCNetworking.shared.uploadRequest[fileNameLocalPath] = nil
-                    
+
                     if let metadata = NCManageDatabase.shared.getMetadataFromOcId(metadata.ocId) {
-                        
+
                         let metadata = tableMetadata.init(value: metadata)
-                        
+
                         if error?.isExplicitlyCancelledError ?? false {
-                        
+
                             CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
                             NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
-                            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId":metadata.ocId, "ocIdTemp":ocIdTemp, "errorCode":errorCode, "errorDescription":""])
+                            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "ocIdTemp": ocIdTemp, "errorCode": errorCode, "errorDescription": ""])
                             completion(0, "")
 
                         } else if errorCode == 0 && ocId != nil {
-                            
+
                             NCUtilityFileSystem.shared.moveFileInBackground(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId))
-                            
+
                             metadata.date = date ?? NSDate()
                             metadata.etag = etag ?? ""
                             metadata.ocId = ocId!
-                            
+
                             metadata.session = ""
                             metadata.sessionError = ""
                             metadata.sessionTaskIdentifier = 0
                             metadata.status = NCGlobal.shared.metadataStatusNormal
-                            
+
                             NCManageDatabase.shared.addMetadata(metadata)
                             NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
                             NCManageDatabase.shared.addLocalFile(metadata: metadata)
-                            
+
                             NCUtility.shared.createImageFrom(fileName: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile)
-                                                    
-                            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId":metadata.ocId, "ocIdTemp":ocIdTemp ,"errorCode":errorCode, "errorDescription":""])
-                            
+
+                            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "ocIdTemp": ocIdTemp, "errorCode": errorCode, "errorDescription": ""])
+
                         } else {
-                            
+
                             if errorCode == 401 || errorCode == 403 {
-                            
+
                                 #if !EXTENSION
                                 NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account, errorCode: errorCode, errorDescription: errorDescription)
                                 #endif
                                 NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
                                 
                             } else {
-                            
+
                                 NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
                             }
-                            
-                            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId":metadata.ocId, "ocIdTemp":ocIdTemp, "errorCode":errorCode, "errorDescription":""])
+
+                            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "ocIdTemp": ocIdTemp, "errorCode": errorCode, "errorDescription": ""])
                         }
                     }
-                    
-                    NCNetworkingE2EE.shared.unlock(account: metadata.account, serverUrl: serverUrl) { (_, _, _, _) in
+
+                    NCNetworkingE2EE.shared.unlock(account: metadata.account, serverUrl: serverUrl) { _, _, _, _ in
                         completion(errorCode, errorDescription)
                     }
                 }
-                
+
             } else {
-                
+
                 if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocIdTemp) {
                     NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
 
-                    NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId":metadata.ocId, "ocIdTemp":ocIdTemp, "errorCode":errorCode, "errorDescription":errorDescription])
+                    NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "ocIdTemp": ocIdTemp, "errorCode": errorCode, "errorDescription": errorDescription])
                 }
                 completion(errorCode, errorDescription)
             }
         }
     }
-    
-    //MARK: - E2EE
-    
-    @objc func lock(account:String, serverUrl: String, completion: @escaping (_ direcrtory: tableDirectory?, _ e2eToken: String?, _ errorCode: Int, _ errorDescription: String?)->()) {
-        
+
+    // MARK: - E2EE
+
+    @objc func lock(account: String, serverUrl: String, completion: @escaping (_ direcrtory: tableDirectory?, _ e2eToken: String?, _ errorCode: Int, _ errorDescription: String?) -> Void) {
+
         var e2eToken: String?
-        
+
         guard let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl)) else {
             return completion(nil, nil, 0, "")
         }
-        
+
         if let tableLock = NCManageDatabase.shared.getE2ETokenLock(account: account, serverUrl: serverUrl) {
             e2eToken = tableLock.e2eToken
         }
-        
-        NCCommunication.shared.lockE2EEFolder(fileId: directory.fileId, e2eToken: e2eToken, method: "POST") { (account, e2eToken, errorCode, errorDescription) in
+
+        NCCommunication.shared.lockE2EEFolder(fileId: directory.fileId, e2eToken: e2eToken, method: "POST") { account, e2eToken, errorCode, errorDescription in
             if errorCode == 0 && e2eToken != nil {
                 NCManageDatabase.shared.setE2ETokenLock(account: account, serverUrl: serverUrl, fileId: directory.fileId, e2eToken: e2eToken!)
             }
             completion(directory, e2eToken, errorCode, errorDescription)
         }
     }
-    
-    @objc func unlock(account:String, serverUrl: String, completion: @escaping (_ direcrtory: tableDirectory?, _ e2eToken: String?, _ errorCode: Int, _ errorDescription: String?)->()) {
-        
+
+    @objc func unlock(account: String, serverUrl: String, completion: @escaping (_ direcrtory: tableDirectory?, _ e2eToken: String?, _ errorCode: Int, _ errorDescription: String?) -> Void) {
+
         var e2eToken: String?
-        
+
         guard let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl)) else {
             return completion(nil, nil, 0, "")
         }
-        
+
         if let tableLock = NCManageDatabase.shared.getE2ETokenLock(account: account, serverUrl: serverUrl) {
             e2eToken = tableLock.e2eToken
         }
-        
-        NCCommunication.shared.lockE2EEFolder(fileId: directory.fileId, e2eToken: e2eToken, method: "DELETE") { (account, e2eToken, errorCode, errorDescription) in
+
+        NCCommunication.shared.lockE2EEFolder(fileId: directory.fileId, e2eToken: e2eToken, method: "DELETE") { account, e2eToken, errorCode, errorDescription in
             if errorCode == 0 {
                 NCManageDatabase.shared.deteleE2ETokenLock(account: account, serverUrl: serverUrl)
             }
             completion(directory, e2eToken, errorCode, errorDescription)
         }
     }
-    
-    @objc func sendE2EMetadata(account: String, serverUrl: String, fileNameRename: String?, fileNameNewRename: String?, deleteE2eEncryption : NSPredicate?, urlBase: String, upload: Bool = false, completion: @escaping (_ e2eToken: String?, _ errorCode: Int, _ errorDescription: String)->()) {
-            
-        self.lock(account: account, serverUrl: serverUrl) { (directory, e2eToken, errorCode, errorDescription) in
+
+    @objc func sendE2EMetadata(account: String, serverUrl: String, fileNameRename: String?, fileNameNewRename: String?, deleteE2eEncryption: NSPredicate?, urlBase: String, upload: Bool = false, completion: @escaping (_ e2eToken: String?, _ errorCode: Int, _ errorDescription: String) -> Void) {
+
+        self.lock(account: account, serverUrl: serverUrl) { directory, e2eToken, errorCode, errorDescription in
             if errorCode == 0 && e2eToken != nil && directory != nil {
-                          
-                NCCommunication.shared.getE2EEMetadata(fileId: directory!.fileId, e2eToken: e2eToken) { (account, e2eMetadata, errorCode, errorDescription) in
+
+                NCCommunication.shared.getE2EEMetadata(fileId: directory!.fileId, e2eToken: e2eToken) { account, e2eMetadata, errorCode, errorDescription in
                     var method = "POST"
                     var e2eMetadataNew: String?
-                    
+
                     if errorCode == 0 && e2eMetadata != nil {
                         if !NCEndToEndMetadata.shared.decoderMetadata(e2eMetadata!, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: serverUrl, account: account, urlBase: urlBase) {
                             return completion(e2eToken, NCGlobal.shared.errorInternalError, NSLocalizedString("_e2e_error_encode_metadata_", comment: ""))
                         }
                         method = "PUT"
                     }
-    
+
                     // Rename
-                    if (fileNameRename != nil && fileNameNewRename != nil) {
+                    if fileNameRename != nil && fileNameNewRename != nil {
                         NCManageDatabase.shared.renameFileE2eEncryption(serverUrl: serverUrl, fileNameIdentifier: fileNameRename!, newFileName: fileNameNewRename!, newFileNamePath: CCUtility.returnFileNamePath(fromFileName: fileNameNewRename!, serverUrl: serverUrl, urlBase: urlBase, account: account))
                     }
-                    
+
                     // Delete
                     if deleteE2eEncryption != nil {
                         NCManageDatabase.shared.deleteE2eEncryption(predicate: deleteE2eEncryption!)
                     }
-                
+
                     // Rebuild metadata for send it
                     let tableE2eEncryption = NCManageDatabase.shared.getE2eEncryptions(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl))
                     if tableE2eEncryption != nil {
@@ -426,13 +436,13 @@ import Alamofire
                     } else {
                         method = "DELETE"
                     }
-                    
-                    NCCommunication.shared.putE2EEMetadata(fileId: directory!.fileId, e2eToken: e2eToken!, e2eMetadata: e2eMetadataNew, method: method) { (account, e2eMetadata, errorCode, errorDescription) in
+
+                    NCCommunication.shared.putE2EEMetadata(fileId: directory!.fileId, e2eToken: e2eToken!, e2eMetadata: e2eMetadataNew, method: method) { account, _, errorCode, errorDescription in
 
                         if upload {
                             completion(e2eToken, errorCode, errorDescription)
                         } else {
-                            self.unlock(account: account, serverUrl: serverUrl) { (_, e2eToken, _, _) in
+                            self.unlock(account: account, serverUrl: serverUrl) { _, e2eToken, _, _ in
                                 completion(e2eToken, errorCode, errorDescription)
                             }
                         }
@@ -444,5 +454,3 @@ import Alamofire
         }
     }
 }
-
-

+ 62 - 56
iOSClient/Networking/NCNetworkingProcessUpload.swift

@@ -23,30 +23,31 @@
 
 import UIKit
 import NCCommunication
+import Photos
 
 class NCNetworkingProcessUpload: NSObject {
 
     let appDelegate = UIApplication.shared.delegate as! AppDelegate
     var timerProcess: Timer?
-    
+
     let maxConcurrentOperationUpload = 5
-    
+
     override init() {
         super.init()
         startTimer()
     }
-    
+
     @objc func startProcess() {
         if timerProcess?.isValid ?? false {
             process()
         }
     }
-    
+
     func startTimer() {
         timerProcess?.invalidate()
         timerProcess = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(process), userInfo: nil, repeats: true)
     }
-    
+
     func stopTimer() {
         timerProcess?.invalidate()
     }
@@ -54,22 +55,22 @@ class NCNetworkingProcessUpload: NSObject {
     @objc private func process() {
 
         if appDelegate.account == "" { return }
-        
+
         var counterUpload: Int = 0
         let sessionSelectors = [NCGlobal.shared.selectorUploadFile, NCGlobal.shared.selectorUploadAutoUpload, NCGlobal.shared.selectorUploadAutoUploadAll]
-        
+
         let metadatasUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status == %d OR status == %d", NCGlobal.shared.metadataStatusInUpload, NCGlobal.shared.metadataStatusUploading))
         counterUpload = metadatasUpload.count
-        
+
         stopTimer()
-        
+
         print("[LOG] PROCESS-UPLOAD \(counterUpload)")
-    
-        NCNetworking.shared.getOcIdInBackgroundSession { (listOcId) in
-            
+
+        NCNetworking.shared.getOcIdInBackgroundSession { listOcId in
+
             for sessionSelector in sessionSelectors {
                 if counterUpload < self.maxConcurrentOperationUpload {
-                    
+
                     let limit = self.maxConcurrentOperationUpload - counterUpload
                     var predicate = NSPredicate()
                     if UIApplication.shared.applicationState == .background {
@@ -81,20 +82,20 @@ class NCNetworkingProcessUpload: NSObject {
                     if metadatas.count > 0 {
                         NCCommunicationCommon.shared.writeLog("PROCESS-UPLOAD find \(metadatas.count) items")
                     }
-                    
+
                     for metadata in metadatas {
-                        
+
                         // Is already in upload background? skipped
                         if listOcId.contains(metadata.ocId) {
                             NCCommunicationCommon.shared.writeLog("Process auto upload skipped file: \(metadata.serverUrl)/\(metadata.fileNameView), because is already in session.")
                             continue
                         }
-                        
+
                         // Session Extension ? skipped
                         if metadata.session == NCNetworking.shared.sessionIdentifierBackgroundExtension {
                             continue
                         }
-                        
+
                         // Is already in upload E2EE / CHUNK ? exit [ ONLY ONE IN QUEUE ]
                         for metadata in metadatasUpload {
                             if metadata.chunk || metadata.e2eEncrypted {
@@ -102,13 +103,13 @@ class NCNetworkingProcessUpload: NSObject {
                                 return
                             }
                         }
-                        
+
                         // Chunk 
                         if metadata.chunk && UIApplication.shared.applicationState == .active {
                             if let metadata = NCManageDatabase.shared.setMetadataStatus(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusInUpload) {
                                 NCNetworking.shared.upload(metadata: metadata) {
                                     // start
-                                } completion: { (_, _) in
+                                } completion: { _, _ in
                                     DispatchQueue.main.async {
                                         self.startTimer()
                                     }
@@ -118,13 +119,13 @@ class NCNetworkingProcessUpload: NSObject {
                             }
                             return
                         }
-                        
+
                         // E2EE
                         if metadata.e2eEncrypted && UIApplication.shared.applicationState == .active {
                             if let metadata = NCManageDatabase.shared.setMetadataStatus(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusInUpload) {
                                 NCNetworking.shared.upload(metadata: metadata) {
                                     // start
-                                } completion: { (_, _) in
+                                } completion: { _, _ in
                                     DispatchQueue.main.async {
                                         self.startTimer()
                                     }
@@ -134,28 +135,28 @@ class NCNetworkingProcessUpload: NSObject {
                             }
                             return
                         }
-                        
+
                         counterUpload += 1
                         if let metadata = NCManageDatabase.shared.setMetadataStatus(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusInUpload) {
                             NCNetworking.shared.upload(metadata: metadata) {
                                 // start
-                            } completion: { (_, _) in
+                            } completion: { _, _ in
                                 // completion
                             }
                         }
                     }
-                    
+
                 } else {
                     self.startTimer()
                     return
                 }
             }
-            
+
             // No upload available ? --> Retry Upload in Error
             if counterUpload == 0 {
                 let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status == %d", NCGlobal.shared.metadataStatusUploadError))
                 for metadata in metadatas {
-                    NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: NCNetworking.shared.sessionIdentifierBackground, sessionError: "", sessionTaskIdentifier: 0 ,status: NCGlobal.shared.metadataStatusWaitUpload)
+                    NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: NCNetworking.shared.sessionIdentifierBackground, sessionError: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusWaitUpload)
                 }
             }
              
@@ -171,54 +172,54 @@ class NCNetworkingProcessUpload: NSObject {
             }
         }
     }
-    
-    private func deleteAssetLocalIdentifiers(account: String, sessionSelector: String, completition: @escaping () -> ()) {
-        
+
+    private func deleteAssetLocalIdentifiers(account: String, sessionSelector: String, completition: @escaping () -> Void) {
+
         if UIApplication.shared.applicationState != .active {
             completition()
             return
         }
         let metadatasSessionUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND session CONTAINS[cd] %@", account, "upload"))
-        if metadatasSessionUpload.count > 0 {
+        if !metadatasSessionUpload.isEmpty {
             completition()
             return
         }
         let localIdentifiers = NCManageDatabase.shared.getAssetLocalIdentifiersUploaded(account: account, sessionSelector: sessionSelector)
-        if localIdentifiers.count == 0 {
+        if localIdentifiers.isEmpty {
             completition()
             return
         }
         let assets = PHAsset.fetchAssets(withLocalIdentifiers: localIdentifiers, options: nil)
-        
+
         PHPhotoLibrary.shared().performChanges({
             PHAssetChangeRequest.deleteAssets(assets as NSFastEnumeration)
-        }, completionHandler: { success, error in
+        }, completionHandler: { _, _ in
             DispatchQueue.main.async {
                 NCManageDatabase.shared.clearAssetLocalIdentifiers(localIdentifiers, account: account)
                 completition()
             }
         })
     }
-    
-    //MARK: -
-    
+
+    // MARK: -
+
     @objc func createProcessUploads(metadatas: [tableMetadata], verifyAlreadyExists: Bool = false) {
-        
+
         var metadatasForUpload: [tableMetadata] = []
-        
+
         for metadata in metadatas {
-            
+
             if verifyAlreadyExists {
                 if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ && serverUrl == %@ && fileName == %@ && session != ''", metadata.account, metadata.serverUrl, metadata.fileName)) != nil {
                     continue
                 }
             }
-            
+
             // E2EE
             if CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase) {
                 metadata.e2eEncrypted = true
             }
-            
+
             // CHUNCK
             let chunckSize = CCUtility.getChunkSize() * 1000000
             if chunckSize == 0 || metadata.size <= chunckSize {
@@ -229,20 +230,26 @@ class NCNetworkingProcessUpload: NSObject {
                 metadatasForUpload.append(tableMetadata.init(value: metadata))
             }
         }
-        
+
         NCManageDatabase.shared.addMetadatas(metadatasForUpload)
-        
+
         startProcess()
     }
-    
-    //MARK: -
+
+    // MARK: -
 
     @objc func verifyUploadZombie() {
-        
+
         var session: URLSession?
-        
+
         // verify metadataStatusInUpload (BACKGROUND)
-        let metadatasInUploadBackground = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "(session == %@ OR session == %@ OR session == %@) AND status == %d AND sessionTaskIdentifier == 0", NCNetworking.shared.sessionIdentifierBackground, NCNetworking.shared.sessionIdentifierBackgroundExtension, NCNetworking.shared.sessionIdentifierBackgroundWWan, NCGlobal.shared.metadataStatusInUpload))
+        let metadatasInUploadBackground = NCManageDatabase.shared.getMetadatas(
+            predicate: NSPredicate(
+                format: "(session == %@ OR session == %@ OR session == %@) AND status == %d AND sessionTaskIdentifier == 0",
+                NCNetworking.shared.sessionIdentifierBackground,
+                NCNetworking.shared.sessionIdentifierBackgroundExtension,
+                NCNetworking.shared.sessionIdentifierBackgroundWWan,
+                NCGlobal.shared.metadataStatusInUpload))
         for metadata in metadatasInUploadBackground {
             DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                 if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "ocId == %@ AND status == %d AND sessionTaskIdentifier == 0", metadata.ocId, NCGlobal.shared.metadataStatusInUpload)) {
@@ -250,26 +257,26 @@ class NCNetworkingProcessUpload: NSObject {
                 }
             }
         }
-        
+
         // metadataStatusUploading (BACKGROUND)
         let metadatasUploadingBackground = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "(session == %@ OR session == %@ OR session == %@) AND status == %d", NCNetworking.shared.sessionIdentifierBackground, NCNetworking.shared.sessionIdentifierBackgroundWWan, NCNetworking.shared.sessionIdentifierBackgroundExtension, NCGlobal.shared.metadataStatusUploading))
         for metadata in metadatasUploadingBackground {
-            
+
             if metadata.session == NCNetworking.shared.sessionIdentifierBackground {
                 session = NCNetworking.shared.sessionManagerBackground
             } else if metadata.session == NCNetworking.shared.sessionIdentifierBackgroundWWan {
                 session = NCNetworking.shared.sessionManagerBackgroundWWan
             }
-            
+
             var taskUpload: URLSessionTask?
-            
-            session?.getAllTasks(completionHandler: { (tasks) in
+
+            session?.getAllTasks(completionHandler: { tasks in
                 for task in tasks {
                     if task.taskIdentifier == metadata.sessionTaskIdentifier {
                         taskUpload = task
                     }
                 }
-                
+
                 if taskUpload == nil {
                     if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "ocId == %@ AND status == %d", metadata.ocId, NCGlobal.shared.metadataStatusUploading)) {
                         NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: NCNetworking.shared.sessionIdentifierBackground, sessionError: "", sessionSelector: nil, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusWaitUpload)
@@ -277,7 +284,7 @@ class NCNetworkingProcessUpload: NSObject {
                 }
             })
         }
-        
+
         // metadataStatusUploading OR metadataStatusInUpload (FOREGROUND)
         let metadatasUploading = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "session == %@ AND (status == %d OR status == %d)", NCCommunicationCommon.shared.sessionIdentifierUpload, NCGlobal.shared.metadataStatusUploading, NCGlobal.shared.metadataStatusInUpload))
         for metadata in metadatasUploading {
@@ -288,4 +295,3 @@ class NCNetworkingProcessUpload: NSObject {
         }
     }
 }
-

+ 115 - 109
iOSClient/Networking/NCOperationQueue.swift

@@ -21,7 +21,6 @@
 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 //
 
-
 import UIKit
 import Queuer
 import NCCommunication
@@ -31,7 +30,7 @@ import NCCommunication
         let instance = NCOperationQueue()
         return instance
     }()
-    
+
     private var downloadQueue = Queuer(name: "downloadQueue", maxConcurrentOperationCount: 5, qualityOfService: .default)
     private let deleteQueue = Queuer(name: "deleteQueue", maxConcurrentOperationCount: 1, qualityOfService: .default)
     private let copyMoveQueue = Queuer(name: "copyMoveQueue", maxConcurrentOperationCount: 1, qualityOfService: .default)
@@ -49,16 +48,16 @@ import NCCommunication
         downloadThumbnailCancelAll()
         downloadAvatarCancelAll()
     }
-    
+
     // Download file
-    
+
     func download(metadata: tableMetadata, selector: String) {
-        for operation in downloadQueue.operations as! [NCOperationDownload]  {
+        for operation in downloadQueue.operations as! [NCOperationDownload] {
             if operation.metadata.ocId == metadata.ocId {
                 return
             }
         }
-        downloadQueue.addOperation(NCOperationDownload.init(metadata: metadata, selector: selector))
+        downloadQueue.addOperation(NCOperationDownload(metadata: metadata, selector: selector))
     }
     @objc func downloadCancelAll() {
         downloadQueue.cancelAll()
@@ -67,23 +66,23 @@ import NCCommunication
         return downloadQueue.operationCount
     }
     @objc func downloadExists(metadata: tableMetadata) -> Bool {
-        for operation in downloadQueue.operations as! [NCOperationDownload]  {
+        for operation in downloadQueue.operations as! [NCOperationDownload] {
             if operation.metadata.ocId == metadata.ocId {
                 return true
             }
         }
         return false
     }
-    
+
     // Delete file
-    
+
     @objc func delete(metadata: tableMetadata, onlyLocalCache: Bool) {
-        for operation in deleteQueue.operations as! [NCOperationDelete]  {
+        for operation in deleteQueue.operations as! [NCOperationDelete] {
             if operation.metadata.ocId == metadata.ocId {
                 return
             }
         }
-        deleteQueue.addOperation(NCOperationDelete.init(metadata: metadata, onlyLocalCache: onlyLocalCache))
+        deleteQueue.addOperation(NCOperationDelete(metadata: metadata, onlyLocalCache: onlyLocalCache))
     }
     @objc func deleteCancelAll() {
         deleteQueue.cancelAll()
@@ -91,16 +90,16 @@ import NCCommunication
     @objc func deleteCount() -> Int {
         return deleteQueue.operationCount
     }
-    
+
     // Copy Move file
-    
+
     @objc func copyMove(metadata: tableMetadata, serverUrl: String, overwrite: Bool, move: Bool) {
-        for operation in copyMoveQueue.operations as! [NCOperationCopyMove]  {
+        for operation in copyMoveQueue.operations as! [NCOperationCopyMove] {
             if operation.metadata.ocId == metadata.ocId {
                 return
             }
         }
-        copyMoveQueue.addOperation(NCOperationCopyMove.init(metadata: metadata, serverUrlTo: serverUrl, overwrite: overwrite, move: move))
+        copyMoveQueue.addOperation(NCOperationCopyMove(metadata: metadata, serverUrlTo: serverUrl, overwrite: overwrite, move: move))
     }
     @objc func copyMoveCancelAll() {
         copyMoveQueue.cancelAll()
@@ -108,45 +107,45 @@ import NCCommunication
     @objc func copyMoveCount() -> Int {
         return copyMoveQueue.operationCount
     }
-    
+
     // Synchronization
-    
+
     @objc func synchronizationMetadata(_ metadata: tableMetadata, selector: String) {
         for operation in synchronizationQueue.operations as! [NCOperationSynchronization] {
             if operation.metadata.ocId == metadata.ocId {
                 return
             }
         }
-        synchronizationQueue.addOperation(NCOperationSynchronization.init(metadata: metadata, selector: selector))
+        synchronizationQueue.addOperation(NCOperationSynchronization(metadata: metadata, selector: selector))
     }
     @objc func synchronizationCancelAll() {
         synchronizationQueue.cancelAll()
     }
-    
+
     // Download Thumbnail
-    
+
     @objc func downloadThumbnail(metadata: tableMetadata, placeholder: Bool, cell: UIView?, view: UIView?) {
-        
+
         let cell: NCCellProtocol? = cell as? NCCellProtocol
-        
+
         if placeholder {
             if metadata.iconName.count > 0 {
-                cell?.filePreviewImageView?.image = UIImage.init(named: metadata.iconName)
+                cell?.filePreviewImageView?.image = UIImage(named: metadata.iconName)
             } else {
                 cell?.filePreviewImageView?.image = NCBrandColor.cacheImages.file
             }
         }
-        
+
         if metadata.hasPreview && metadata.status == NCGlobal.shared.metadataStatusNormal && (!CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)) {
             for operation in downloadThumbnailQueue.operations as! [NCOperationDownloadThumbnail] {
                 if operation.metadata.ocId == metadata.ocId {
                     return
                 }
             }
-            downloadThumbnailQueue.addOperation(NCOperationDownloadThumbnail.init(metadata: metadata, cell: cell, view: view))
+            downloadThumbnailQueue.addOperation(NCOperationDownloadThumbnail(metadata: metadata, cell: cell, view: view))
         }
     }
-    
+
     func cancelDownloadThumbnail(metadata: tableMetadata) {
         for operation in  downloadThumbnailQueue.operations as! [NCOperationDownloadThumbnail] {
             if operation.metadata.ocId == metadata.ocId {
@@ -154,17 +153,17 @@ import NCCommunication
             }
         }
     }
-    
+
     @objc func downloadThumbnailCancelAll() {
         downloadThumbnailQueue.cancelAll()
     }
-    
+
     // Download Avatar
-    
+
     func downloadAvatar(user: String, dispalyName: String?, fileName: String, cell: NCCellProtocol, view: UIView?) {
 
         let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
-        
+
         if let image = NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) {
             cell.fileAvatarImageView?.image = image
             return
@@ -182,9 +181,9 @@ import NCCommunication
                 return
             }
         }
-        downloadAvatarQueue.addOperation(NCOperationDownloadAvatar.init(user: user, fileName: fileName, fileNameLocalPath: fileNameLocalPath, cell: cell, view: view))
+        downloadAvatarQueue.addOperation(NCOperationDownloadAvatar(user: user, fileName: fileName, fileNameLocalPath: fileNameLocalPath, cell: cell, view: view))
     }
-    
+
     func cancelDownloadAvatar(user: String) {
         for operation in  downloadAvatarQueue.operations as! [NCOperationDownloadAvatar] {
             if operation.user == user {
@@ -192,52 +191,52 @@ import NCCommunication
             }
         }
     }
-    
+
     @objc func downloadAvatarCancelAll() {
         downloadAvatarQueue.cancelAll()
     }
 }
 
-//MARK: -
+// MARK: -
 
 class NCOperationDownload: ConcurrentOperation {
-   
+
     var metadata: tableMetadata
     var selector: String
-    
+
     init(metadata: tableMetadata, selector: String) {
         self.metadata = tableMetadata.init(value: metadata)
         self.selector = selector
     }
-    
+
     override func start() {
         if isCancelled {
             self.finish()
         } else {
-            NCNetworking.shared.download(metadata: metadata, selector: self.selector) { (_) in
+            NCNetworking.shared.download(metadata: metadata, selector: self.selector) { _ in
                 self.finish()
             }
         }
     }
 }
 
-//MARK: -
+// MARK: -
 
 class NCOperationDelete: ConcurrentOperation {
-   
+
     var metadata: tableMetadata
     var onlyLocalCache: Bool
-    
+
     init(metadata: tableMetadata, onlyLocalCache: Bool) {
         self.metadata = tableMetadata.init(value: metadata)
         self.onlyLocalCache = onlyLocalCache
     }
-    
+
     override func start() {
         if isCancelled {
             self.finish()
         } else {
-            NCNetworking.shared.deleteMetadata(metadata, onlyLocalCache: onlyLocalCache) { (errorCode, errorDescription) in
+            NCNetworking.shared.deleteMetadata(metadata, onlyLocalCache: onlyLocalCache) { errorCode, errorDescription in
                 if errorCode != 0 {
                     NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
                 }
@@ -247,10 +246,10 @@ class NCOperationDelete: ConcurrentOperation {
     }
 }
 
-//MARK: -
+// MARK: -
 
 class NCOperationCopyMove: ConcurrentOperation {
-   
+
     var metadata: tableMetadata
     var serverUrlTo: String
     var overwrite: Bool
@@ -262,20 +261,20 @@ class NCOperationCopyMove: ConcurrentOperation {
         self.overwrite = overwrite
         self.move = move
     }
-    
+
     override func start() {
         if isCancelled {
             self.finish()
         } else {
             if move {
-                NCNetworking.shared.moveMetadata(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
+                NCNetworking.shared.moveMetadata(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite) { errorCode, errorDescription in
                     if errorCode != 0 {
                         NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
                     }
                     self.finish()
                 }
             } else {
-                NCNetworking.shared.copyMetadata(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
+                NCNetworking.shared.copyMetadata(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite) { errorCode, errorDescription in
                     if errorCode != 0 {
                         NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
                     }
@@ -286,14 +285,14 @@ class NCOperationCopyMove: ConcurrentOperation {
     }
 }
 
-//MARK: -
+// MARK: -
 
 class NCOperationSynchronization: ConcurrentOperation {
-   
+
     var metadata: tableMetadata
     var selector: String
     var download: Bool
-    
+
     init(metadata: tableMetadata, selector: String) {
         self.metadata = tableMetadata.init(value: metadata)
         self.selector = selector
@@ -303,30 +302,30 @@ class NCOperationSynchronization: ConcurrentOperation {
             self.download = false
         }
     }
-    
+
     override func start() {
         if isCancelled {
             self.finish()
         } else {
             if metadata.directory {
-                
+
                 let serverUrl = metadata.serverUrl + "/" + metadata.fileName
                 let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, serverUrl))
 
-                NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
+                NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { account, files, _, errorCode, _ in
 
                     if (errorCode == 0) && (directory?.etag != files.first?.etag || self.selector == NCGlobal.shared.selectorDownloadAllFile) {
-                        
-                        NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: NCCommunicationCommon.shared.backgroundQueue) { (account, files, responseData, errorCode, errorDescription) in
-                            
+
+                        NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: NCCommunicationCommon.shared.backgroundQueue) { account, files, _, errorCode, _ in
+
                             if errorCode == 0 {
-                            
-                                NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: true, account: account) { (metadataFolder, metadatasFolder, metadatas) in
-                                    
+
+                                NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: true, account: account) { metadataFolder, _, metadatas in
+
                                     let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", account, serverUrl, NCGlobal.shared.metadataStatusNormal))
-                                    
+
                                     if self.selector == NCGlobal.shared.selectorDownloadAllFile {
-                                        
+
                                         NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult)
 
                                         for metadata in metadatas {
@@ -338,9 +337,9 @@ class NCOperationSynchronization: ConcurrentOperation {
                                                 }
                                             }
                                         }
-                                        
+
                                     } else {
-                                    
+
                                         let metadatasChanged = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addExistsInLocal: self.download, addCompareEtagLocal: true, addDirectorySynchronized: true)
 
                                         for metadata in metadatasChanged.metadatasUpdate {
@@ -348,25 +347,25 @@ class NCOperationSynchronization: ConcurrentOperation {
                                                 NCOperationQueue.shared.synchronizationMetadata(metadata, selector: self.selector)
                                             }
                                         }
-                                        
+
                                         for metadata in metadatasChanged.metadatasLocalUpdate {
                                             NCOperationQueue.shared.download(metadata: metadata, selector: self.selector)
                                         }
                                     }
-                                    
+
                                     // Update etag directory
                                     NCManageDatabase.shared.addDirectory(encrypted: metadataFolder.e2eEncrypted, favorite: metadataFolder.favorite, ocId: metadataFolder.ocId, fileId: metadataFolder.fileId, etag: metadataFolder.etag, permissions: metadataFolder.permissions, serverUrl: serverUrl, account: metadataFolder.account)
                                 }
-                            
+
                             } else if errorCode == NCGlobal.shared.errorResourceNotFound && self.metadata.directory {
                                 NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: self.metadata.serverUrl, account: self.metadata.account)
                             }
-                            
+
                             self.finish()
                         }
-                        
+
                     } else {
-                        
+
                         let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl))
                         for metadata in metadatas {
                             if metadata.directory {
@@ -377,11 +376,11 @@ class NCOperationSynchronization: ConcurrentOperation {
                                 }
                             }
                         }
-                        
+
                         self.finish()
                     }
                 }
-                
+
             } else {
                 if NCManageDatabase.shared.isDownloadMetadata(metadata, download: self.download) {
                     NCOperationQueue.shared.download(metadata: metadata, selector: self.selector)
@@ -392,17 +391,17 @@ class NCOperationSynchronization: ConcurrentOperation {
     }
 }
 
-//MARK: -
+// MARK: -
 
 class NCOperationDownloadThumbnail: ConcurrentOperation {
-   
+
     var metadata: tableMetadata
     var cell: NCCellProtocol?
     var view: UIView?
     var fileNamePath: String = ""
     var fileNamePreviewLocalPath: String = ""
     var fileNameIconLocalPath: String = ""
-    
+
     init(metadata: tableMetadata, cell: NCCellProtocol?, view: UIView?) {
         self.metadata = tableMetadata.init(value: metadata)
         self.cell = cell
@@ -411,7 +410,7 @@ class NCOperationDownloadThumbnail: ConcurrentOperation {
         self.fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
         self.fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
     }
-    
+
     override func start() {
 
         if isCancelled {
@@ -421,40 +420,47 @@ class NCOperationDownloadThumbnail: ConcurrentOperation {
             if FileManager.default.fileExists(atPath: fileNameIconLocalPath) && FileManager.default.fileExists(atPath: fileNamePreviewLocalPath) {
                 etagResource = metadata.etagResource
             }
-            NCCommunication.shared.downloadPreview(fileNamePathOrFileId: fileNamePath, fileNamePreviewLocalPath: fileNamePreviewLocalPath , widthPreview: NCGlobal.shared.sizePreview, heightPreview: NCGlobal.shared.sizePreview, fileNameIconLocalPath: fileNameIconLocalPath, sizeIcon: NCGlobal.shared.sizeIcon, etag: etagResource, queue: NCCommunicationCommon.shared.backgroundQueue) { (account, imagePreview, imageIcon, imageOriginal, etag, errorCode, errorDescription) in
-                
-                if errorCode == 0 && imageIcon != nil {
-                    NCManageDatabase.shared.setMetadataEtagResource(ocId: self.metadata.ocId, etagResource: etag)
-                    DispatchQueue.main.async {
-                        if self.metadata.ocId == self.cell?.fileObjectId {
-                            if let filePreviewImageView = self.cell?.filePreviewImageView  {
-                                UIView.transition(with: filePreviewImageView,
-                                    duration: 0.75,
-                                    options: .transitionCrossDissolve,
-                                    animations: { filePreviewImageView.image = imageIcon! },
-                                    completion: nil)
-                            }
-                        } else {
-                            if self.view is UICollectionView {
-                                (self.view as? UICollectionView)?.reloadData()
-                            } else if self.view is UITableView{
-                                (self.view as? UITableView)?.reloadData()
+            NCCommunication.shared.downloadPreview(
+                fileNamePathOrFileId: fileNamePath,
+                fileNamePreviewLocalPath: fileNamePreviewLocalPath,
+                widthPreview: NCGlobal.shared.sizePreview,
+                heightPreview: NCGlobal.shared.sizePreview,
+                fileNameIconLocalPath: fileNameIconLocalPath,
+                sizeIcon: NCGlobal.shared.sizeIcon,
+                etag: etagResource,
+                queue: NCCommunicationCommon.shared.backgroundQueue) { _, _, imageIcon, _, etag, errorCode, _ in
+
+                    if errorCode == 0 && imageIcon != nil {
+                        NCManageDatabase.shared.setMetadataEtagResource(ocId: self.metadata.ocId, etagResource: etag)
+                        DispatchQueue.main.async {
+                            if self.metadata.ocId == self.cell?.fileObjectId {
+                                if let filePreviewImageView = self.cell?.filePreviewImageView {
+                                    UIView.transition(with: filePreviewImageView,
+                                                      duration: 0.75,
+                                                      options: .transitionCrossDissolve,
+                                                      animations: { filePreviewImageView.image = imageIcon! },
+                                                      completion: nil)
+                                }
+                            } else {
+                                if self.view is UICollectionView {
+                                    (self.view as? UICollectionView)?.reloadData()
+                                } else if self.view is UITableView {
+                                    (self.view as? UITableView)?.reloadData()
+                                }
                             }
+                            NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedThumbnail, userInfo: ["ocId": self.metadata.ocId])
                         }
-                        NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedThumbnail, userInfo: ["ocId": self.metadata.ocId])
                     }
+                    self.finish()
                 }
-                self.finish()
-            }
         }
     }
 }
 
-//MARK: -
+// MARK: -
 
 class NCOperationDownloadAvatar: ConcurrentOperation {
 
-    let appDelegate = UIApplication.shared.delegate as! AppDelegate
     var user: String
     var fileName: String
     var etag: String?
@@ -470,27 +476,27 @@ class NCOperationDownloadAvatar: ConcurrentOperation {
         self.view = view
         self.etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
     }
-    
+
     override func start() {
 
         if isCancelled {
             self.finish()
         } else {
-            NCCommunication.shared.downloadAvatar(user: user, fileNameLocalPath: fileNameLocalPath, sizeImage: NCGlobal.shared.avatarSize, avatarSizeRounded: NCGlobal.shared.avatarSizeRounded, etag: self.etag, queue: NCCommunicationCommon.shared.backgroundQueue) { (account, imageAvatar, imageOriginal, etag, errorCode, errorMessage) in
-                
+            NCCommunication.shared.downloadAvatar(user: user, fileNameLocalPath: fileNameLocalPath, sizeImage: NCGlobal.shared.avatarSize, avatarSizeRounded: NCGlobal.shared.avatarSizeRounded, etag: self.etag, queue: NCCommunicationCommon.shared.backgroundQueue) { _, imageAvatar, _, etag, errorCode, _ in
+
                 if errorCode == 0, let imageAvatar = imageAvatar, let etag = etag {
-                    
+
                     NCManageDatabase.shared.addAvatar(fileName: self.fileName, etag: etag)
 
                     DispatchQueue.main.async {
                         if self.user == self.cell.fileUser {
-                            if let avatarImageView = self.cell?.fileAvatarImageView  {
+                            if let avatarImageView = self.cell?.fileAvatarImageView {
                                 UIView.transition(with: avatarImageView, duration: 0.75, options: .transitionCrossDissolve) {
                                     avatarImageView.image = imageAvatar
                                 } completion: { _ in
                                     if self.view is UICollectionView {
                                         (self.view as? UICollectionView)?.reloadData()
-                                    } else if self.view is UITableView{
+                                    } else if self.view is UITableView {
                                         (self.view as? UITableView)?.reloadData()
                                     }
                                 }
@@ -498,17 +504,17 @@ class NCOperationDownloadAvatar: ConcurrentOperation {
                         } else {
                             if self.view is UICollectionView {
                                 (self.view as? UICollectionView)?.reloadData()
-                            } else if self.view is UITableView{
+                            } else if self.view is UITableView {
                                 (self.view as? UITableView)?.reloadData()
                             }
                         }
                     }
-                    
+
                 } else if errorCode == NCGlobal.shared.errorNotModified {
-                    
+
                     NCManageDatabase.shared.setAvatarLoaded(fileName: self.fileName)
                 }
-                
+
                 self.finish()
             }
         }

+ 65 - 65
iOSClient/Networking/NCService.swift

@@ -30,29 +30,29 @@ class NCService: NSObject {
         let instance = NCService()
         return instance
     }()
-    
+
     let appDelegate = UIApplication.shared.delegate as! AppDelegate
-    
-    //MARK: -
-    
+
+    // MARK: -
+
     @objc public func startRequestServicesServer() {
-   
+
         NCManageDatabase.shared.clearAllAvatarLoaded()
-        
+
         if appDelegate.account == "" { return }
-        
+
         self.addInternalTypeIdentifier()
         self.requestUserProfile()
         self.requestServerStatus()
     }
 
-    //MARK: -
-    
+    // MARK: -
+
     func addInternalTypeIdentifier() {
 
         // txt
         NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: "text/plain", classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NCCommunicationCommon.typeIconFile.document.rawValue, name: "markdown")
-        
+
         // html
         NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: "text/html", classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NCCommunicationCommon.typeIconFile.document.rawValue, name: "markdown")
 
@@ -62,41 +62,41 @@ class NCService: NSObject {
 
         // document: text
         NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: "org.oasis-open.opendocument.text", classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorCollabora, iconName: NCCommunicationCommon.typeIconFile.document.rawValue, name: "document")
-        NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: "org.openxmlformats.wordprocessingml.document", classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorOnlyoffice ,iconName: NCCommunicationCommon.typeIconFile.document.rawValue, name: "document")
+        NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: "org.openxmlformats.wordprocessingml.document", classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorOnlyoffice, iconName: NCCommunicationCommon.typeIconFile.document.rawValue, name: "document")
         NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: "com.microsoft.word.doc", classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorQuickLook, iconName: NCCommunicationCommon.typeIconFile.document.rawValue, name: "document")
         NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: "com.apple.iwork.pages.pages", classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorQuickLook, iconName: NCCommunicationCommon.typeIconFile.document.rawValue, name: "pages")
-        
+
         // document: sheet
         NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: "org.oasis-open.opendocument.spreadsheet", classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorCollabora, iconName: NCCommunicationCommon.typeIconFile.xls.rawValue, name: "sheet")
         NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: "org.openxmlformats.spreadsheetml.sheet", classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorOnlyoffice, iconName: NCCommunicationCommon.typeIconFile.xls.rawValue, name: "sheet")
         NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: "com.microsoft.excel.xls", classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorQuickLook, iconName: NCCommunicationCommon.typeIconFile.xls.rawValue, name: "sheet")
         NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: "com.apple.iwork.numbers.numbers", classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorQuickLook, iconName: NCCommunicationCommon.typeIconFile.xls.rawValue, name: "numbers")
-        
+
         // document: presentation
         NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: "org.oasis-open.opendocument.presentation", classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorCollabora, iconName: NCCommunicationCommon.typeIconFile.ppt.rawValue, name: "presentation")
         NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: "org.openxmlformats.presentationml.presentation", classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorOnlyoffice, iconName: NCCommunicationCommon.typeIconFile.ppt.rawValue, name: "presentation")
         NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: "com.microsoft.powerpoint.ppt", classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorQuickLook, iconName: NCCommunicationCommon.typeIconFile.ppt.rawValue, name: "presentation")
         NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: "com.apple.iwork.keynote.key", classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorQuickLook, iconName: NCCommunicationCommon.typeIconFile.ppt.rawValue, name: "keynote")
     }
-    
+
     private func requestUserProfile() {
-        
+
         if appDelegate.account == "" { return }
-        
-        NCCommunication.shared.getUserProfile(queue: NCCommunicationCommon.shared.backgroundQueue) { (account, userProfile, errorCode, errorDescription) in
-               
+
+        NCCommunication.shared.getUserProfile(queue: NCCommunicationCommon.shared.backgroundQueue) { account, userProfile, errorCode, errorDescription in
+
             if errorCode == 0 && account == self.appDelegate.account {
-                  
+
                 // Update User (+ userProfile.id) & active account & account network
                 guard let tableAccount = NCManageDatabase.shared.setAccountUserProfile(userProfile!) else {
-                    NCContentPresenter.shared.messageNotification("Account", description: "Internal error : account not found on DB",  delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError, priority: .max)
+                    NCContentPresenter.shared.messageNotification("Account", description: "Internal error : account not found on DB", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError, priority: .max)
                     return
                 }
 
                 self.appDelegate.settingAccount(tableAccount.account, urlBase: tableAccount.urlBase, user: tableAccount.user, userId: tableAccount.userId, password: CCUtility.getPassword(tableAccount.account))
 
                 // Synchronize favorite
-                NCNetworking.shared.listingFavoritescompletion(selector: NCGlobal.shared.selectorReadFile) { (_, _, _, _) in }
+                NCNetworking.shared.listingFavoritescompletion(selector: NCGlobal.shared.selectorReadFile) { _, _, _, _ in }
 
                 // Synchronize Offline
                 self.synchronizeOffline(account: tableAccount.account)
@@ -106,33 +106,33 @@ class NCService: NSObject {
                 let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
                 let etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
 
-                NCCommunication.shared.downloadAvatar(user: tableAccount.userId, fileNameLocalPath: fileNameLocalPath, sizeImage: NCGlobal.shared.avatarSize, avatarSizeRounded: NCGlobal.shared.avatarSizeRounded, etag: etag, queue: NCCommunicationCommon.shared.backgroundQueue) { (account, image, imageOriginal, etag, errorCode, errorMessage) in
+                NCCommunication.shared.downloadAvatar(user: tableAccount.userId, fileNameLocalPath: fileNameLocalPath, sizeImage: NCGlobal.shared.avatarSize, avatarSizeRounded: NCGlobal.shared.avatarSizeRounded, etag: etag, queue: NCCommunicationCommon.shared.backgroundQueue) { _, _, _, etag, errorCode, _ in
 
                     if let etag = etag, errorCode == 0 {
                         NCManageDatabase.shared.addAvatar(fileName: fileName, etag: etag)
                         NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadAvatar, userInfo: nil)
                     } else if errorCode == NCGlobal.shared.errorNotModified {
-                        
+
                         NCManageDatabase.shared.setAvatarLoaded(fileName: fileName)
                     }
                 }
                 self.requestServerCapabilities()
-                
+
             } else {
-                
+
                 if errorCode == 401 || errorCode == 403 {
                     NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: account, errorCode: errorCode, errorDescription: errorDescription)
                 }
             }
         }
     }
-    
+
     private func requestServerStatus() {
-        
-        NCCommunication.shared.getServerStatus(serverUrl: appDelegate.urlBase, queue: NCCommunicationCommon.shared.backgroundQueue) { (serverProductName, serverVersion, versionMajor, versionMinor, versionMicro, extendedSupport, errorCode, errorMessage) in
-                        
+
+        NCCommunication.shared.getServerStatus(serverUrl: appDelegate.urlBase, queue: NCCommunicationCommon.shared.backgroundQueue) { serverProductName, _, versionMajor, _, _, extendedSupport, errorCode, _ in
+
             if errorCode == 0 && extendedSupport == false {
-                                
+
                 if serverProductName == "owncloud" {
                     NCContentPresenter.shared.messageNotification("_warning_", description: "_warning_owncloud_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorInternalError, priority: .max)
                 } else if versionMajor <=  NCGlobal.shared.nextcloud_unsupported_version {
@@ -141,32 +141,32 @@ class NCService: NSObject {
             }
         }
     }
-    
+
     private func requestServerCapabilities() {
-        
+
         if appDelegate.account == "" { return }
-        
-        NCCommunication.shared.getCapabilities(queue: NCCommunicationCommon.shared.backgroundQueue) { (account, data, errorCode, errorDescription) in
-            
+
+        NCCommunication.shared.getCapabilities(queue: NCCommunicationCommon.shared.backgroundQueue) { account, data, errorCode, errorDescription in
+
             if errorCode == 0 && data != nil {
-                
+
                 NCManageDatabase.shared.addCapabilitiesJSon(data!, account: account)
-            
+
                 let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
-                
+
                 // Setup communication
                 if serverVersionMajor > 0 {
                     NCCommunicationCommon.shared.setup(nextcloudVersion: serverVersionMajor)
                 }
                 NCCommunicationCommon.shared.setup(webDav: NCUtilityFileSystem.shared.getWebDAV(account: account))
-                
+
                 // Theming
                 NCBrandColor.shared.settingThemingColor(account: account)
-            
+
                 // File Sharing
                 let isFilesSharingEnabled = NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesFileSharingApiEnabled, exists: false)
                 if isFilesSharingEnabled {
-                    NCCommunication.shared.readShares(parameters: NCCShareParameter(), queue: NCCommunicationCommon.shared.backgroundQueue) { (account, shares, errorCode, ErrorDescription) in
+                    NCCommunication.shared.readShares(parameters: NCCShareParameter(), queue: NCCommunicationCommon.shared.backgroundQueue) { account, shares, errorCode, errorDescription in
                         if errorCode == 0 {
                             NCManageDatabase.shared.deleteTableShare(account: account)
                             if shares != nil {
@@ -174,33 +174,33 @@ class NCService: NSObject {
                             }
                             self.appDelegate.shares = NCManageDatabase.shared.getTableShares(account: account)
                         } else {
-                            NCContentPresenter.shared.messageNotification("_share_", description: ErrorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
+                            NCContentPresenter.shared.messageNotification("_share_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
                         }
                     }
                 }
-                
+
                 let comments = NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesFilesComments, exists: false)
                 let activity = NCManageDatabase.shared.getCapabilitiesServerArray(account: account, elements: NCElementsJSON.shared.capabilitiesActivity)
-                
+
                 if !isFilesSharingEnabled && !comments && activity == nil {
                     self.appDelegate.disableSharesView = true
                 } else {
                     self.appDelegate.disableSharesView = false
                 }
-            
+
                 // Text direct editor detail
                 if serverVersionMajor >= NCGlobal.shared.nextcloudVersion18 {
-                    NCCommunication.shared.NCTextObtainEditorDetails(queue: NCCommunicationCommon.shared.backgroundQueue) { (account, editors, creators, errorCode, errorMessage) in
+                    NCCommunication.shared.NCTextObtainEditorDetails(queue: NCCommunicationCommon.shared.backgroundQueue) { account, editors, creators, errorCode, _ in
                         if errorCode == 0 && account == self.appDelegate.account {
                             NCManageDatabase.shared.addDirectEditing(account: account, editors: editors, creators: creators)
                         }
                     }
                 }
-                
+
                 // External file Server
                 let isExternalSitesServerEnabled = NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesExternalSitesExists, exists: true)
-                if (isExternalSitesServerEnabled) {
-                    NCCommunication.shared.getExternalSite(queue: NCCommunicationCommon.shared.backgroundQueue) { (account, externalSites, errorCode, errorDescription) in
+                if isExternalSitesServerEnabled {
+                    NCCommunication.shared.getExternalSite(queue: NCCommunicationCommon.shared.backgroundQueue) { account, externalSites, errorCode, _ in
                         if errorCode == 0 && account == self.appDelegate.account {
                             NCManageDatabase.shared.deleteExternalSites(account: account)
                             for externalSite in externalSites {
@@ -208,15 +208,15 @@ class NCService: NSObject {
                             }
                         }
                     }
-                    
+
                 } else {
                     NCManageDatabase.shared.deleteExternalSites(account: account)
                 }
-                
+
                 // User Status
                 let userStatus = NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesUserStatusEnabled, exists: false)
                 if userStatus {
-                    NCCommunication.shared.getUserStatus(queue: NCCommunicationCommon.shared.backgroundQueue) { (account, clearAt, icon, message, messageId, messageIsPredefined, status, statusIsUserDefined, userId, errorCode, errorDescription) in
+                    NCCommunication.shared.getUserStatus(queue: NCCommunicationCommon.shared.backgroundQueue) { account, clearAt, icon, message, messageId, messageIsPredefined, status, statusIsUserDefined, userId, errorCode, _ in
                         if errorCode == 0 && account == self.appDelegate.account && userId == self.appDelegate.userId {
                             NCManageDatabase.shared.setAccountUserStatus(userStatusClearAt: clearAt, userStatusIcon: icon, userStatusMessage: message, userStatusMessageId: messageId, userStatusMessageIsPredefined: messageIsPredefined, userStatusStatus: status, userStatusStatusIsUserDefined: statusIsUserDefined, account: account)
                         }
@@ -226,14 +226,14 @@ class NCService: NSObject {
                 // Added UTI for Collabora
                 if let richdocumentsMimetypes = NCManageDatabase.shared.getCapabilitiesServerArray(account: account, elements: NCElementsJSON.shared.capabilitiesRichdocumentsMimetypes) {
                     for mimeType in richdocumentsMimetypes {
-                        NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: mimeType, classFile:  NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorCollabora, iconName: NCCommunicationCommon.typeIconFile.document.rawValue, name: "document")
+                        NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: mimeType, classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: NCGlobal.shared.editorCollabora, iconName: NCCommunicationCommon.typeIconFile.document.rawValue, name: "document")
                     }
                 }
-                
+
                 // Added UTI for ONLYOFFICE & Text
                 if let directEditingCreators = NCManageDatabase.shared.getDirectEditingCreators(account: account) {
                     for directEditing in directEditingCreators {
-                        NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: directEditing.mimetype, classFile:  NCCommunicationCommon.typeClassFile.document.rawValue, editor: directEditing.editor, iconName: NCCommunicationCommon.typeIconFile.document.rawValue, name: "document")
+                        NCCommunicationCommon.shared.addInternalTypeIdentifier(typeIdentifier: directEditing.mimetype, classFile: NCCommunicationCommon.typeClassFile.document.rawValue, editor: directEditing.editor, iconName: NCCommunicationCommon.typeIconFile.document.rawValue, name: "document")
                     }
                 }
 
@@ -242,23 +242,23 @@ class NCService: NSObject {
                 //                    if (isHandwerkcloudEnabled) {
                 //                        self.requestHC()
                 //                    }
-                
+
             } else if errorCode != 0 {
-                
+
                 NCBrandColor.shared.settingThemingColor(account: account)
-                
+
                 if errorCode == 401 || errorCode == 403 {
                     NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: account, errorCode: errorCode, errorDescription: errorDescription)
                 }
-                
+
             } else {
                 NCBrandColor.shared.settingThemingColor(account: account)
             }
         }
     }
-    
+
     @objc func synchronizeOffline(account: String) {
-        
+
         // Synchronize Offline Directory
         if let directories = NCManageDatabase.shared.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", account), sorted: "serverUrl", ascending: true) {
             for directory: tableDirectory in directories {
@@ -268,7 +268,7 @@ class NCService: NSObject {
                 NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorDownloadFile)
             }
         }
-    
+
         // Synchronize Offline Files
         let files = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", account), sorted: "fileName", ascending: true)
         for file: tableLocalFile in files {
@@ -278,9 +278,9 @@ class NCService: NSObject {
             NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorDownloadFile)
         }
     }
-    
-    //MARK: - Thirt Part
-    
+
+    // MARK: - Thirt Part
+
     private func requestHC() {
 
     }

+ 61 - 61
iOSClient/Notification/NCNotification.swift

@@ -27,7 +27,7 @@ import NCCommunication
 import SwiftyJSON
 
 class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmptyDataSetDelegate {
-  
+
     let appDelegate = UIApplication.shared.delegate as! AppDelegate
     var notifications: [NCCommunicationNotifications] = []
     var emptyDataSet: NCEmptyDataSet?
@@ -36,7 +36,7 @@ class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmpty
 
     override func viewDidLoad() {
         super.viewDidLoad()
-        
+
         title = NSLocalizedString("_notification_", comment: "")
         view.backgroundColor = NCBrandColor.shared.systemBackground
 
@@ -45,91 +45,91 @@ class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmpty
         tableView.estimatedRowHeight = 50.0
         tableView.allowsSelection = false
         tableView.backgroundColor = NCBrandColor.shared.systemBackground
-        
+
         // Empty
         let offset = (self.navigationController?.navigationBar.bounds.height ?? 0) - 20
-        emptyDataSet = NCEmptyDataSet.init(view: tableView, offset: -offset, delegate: self)
-        
+        emptyDataSet = NCEmptyDataSet(view: tableView, offset: -offset, delegate: self)
+
         NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
-        
+
         changeTheming()
     }
-    
+
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
-        
+
         appDelegate.activeViewController = self
-        
+
         //
         NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
     }
-    
+
     override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)
-        
+
         getNetwokingNotification()
     }
-    
+
     override func viewWillDisappear(_ animated: Bool) {
         super.viewWillDisappear(animated)
-        
+
         NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
     }
-    
+
     @objc func viewClose() {
         self.dismiss(animated: true, completion: nil)
     }
-    
+
     // MARK: - NotificationCenter
 
     @objc func initialize() {
         getNetwokingNotification()
     }
-    
+
     @objc func changeTheming() {
         tableView.reloadData()
     }
-    
+
     // MARK: - Empty
-    
+
     func emptyDataSetView(_ view: NCEmptyView) {
-        
-        view.emptyImage.image = UIImage.init(named: "bell")?.image(color: .gray, size: UIScreen.main.bounds.width)
+
+        view.emptyImage.image = UIImage(named: "bell")?.image(color: .gray, size: UIScreen.main.bounds.width)
         view.emptyTitle.text = NSLocalizedString("_no_notification_", comment: "")
         view.emptyDescription.text = ""
     }
-    
+
     // MARK: - Table
 
     @objc func reloadDatasource() {
         self.tableView.reloadData()
     }
-    
+
     override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         emptyDataSet?.numberOfItemsInSection(notifications.count, section: section)
         return notifications.count
     }
-    
+
     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 
         let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! NCNotificationCell
         cell.delegate = self
-        
+
         let notification = notifications[indexPath.row]
         let urlIcon = URL(string: notification.icon)
         var image: UIImage?
-        
+
         if let urlIcon = urlIcon {
             let pathFileName = String(CCUtility.getDirectoryUserData()) + "/" + urlIcon.deletingPathExtension().lastPathComponent + ".png"
             image = UIImage(contentsOfFile: pathFileName)
         }
-        
+
         if let image = image {
             cell.icon.image = image.imageColor(NCBrandColor.shared.brandElement)
         } else {
             cell.icon.image = NCUtility.shared.loadImage(named: "bell", color: NCBrandColor.shared.brandElement)
         }
-        
+
         // Avatar
         cell.avatar.isHidden = true
         cell.avatarLeadingMargin.constant = 10
@@ -149,7 +149,7 @@ class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmpty
                 NCOperationQueue.shared.downloadAvatar(user: user, dispalyName: json["user"]?["name"].string, fileName: fileName, cell: cell, view: tableView)
             }
         }
-        
+
         cell.date.text = DateFormatter.localizedString(from: notification.date as Date, dateStyle: .medium, timeStyle: .medium)
         cell.notification = notification
         cell.date.text = CCUtility.dateDiff(notification.date as Date)
@@ -182,24 +182,24 @@ class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmpty
            let jsonActions = JSON(actions).array {
             if jsonActions.count == 1 {
                 let action = jsonActions[0]
-                
+
                 cell.primary.isEnabled = true
                 cell.primary.isHidden = false
                 cell.primary.setTitle(action["label"].stringValue, for: .normal)
-                
+
             } else if jsonActions.count == 2 {
-                
+
                 cell.primary.isEnabled = true
                 cell.primary.isHidden = false
-                
+
                 cell.secondary.isEnabled = true
                 cell.secondary.isHidden = false
-                
+
                 for action in jsonActions {
-                    
+
                     let label =  action["label"].stringValue
                     let primary = action["primary"].boolValue
-                    
+
                     if primary {
                         cell.primary.setTitle(label, for: .normal)
                     } else {
@@ -213,7 +213,7 @@ class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmpty
             cell.primaryWidth.constant = buttonWidth
             cell.secondaryWidth.constant = buttonWidth
         }
-        
+
         return cell
     }
 
@@ -228,9 +228,9 @@ class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmpty
                     .firstIndex(where: { $0.idNotification == notification.idNotification })  {
                     self.notifications.remove(at: index)
                 }
-                
+
                 self.reloadDatasource()
-                
+
             } else if errorCode != 0 {
                 NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
             } else {
@@ -273,30 +273,30 @@ class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmpty
             }
         } // else: Action not found
     }
-    
+
     // MARK: - Load notification networking
-    
+
     func getNetwokingNotification() {
-    
+
         NCUtility.shared.startActivityIndicator(backgroundView: self.navigationController?.view, blurEffect: true)
 
-        NCCommunication.shared.getNotifications() { (account, notifications, errorCode, errorDescription) in
-         
+        NCCommunication.shared.getNotifications { account, notifications, errorCode, _ in
+
             if errorCode == 0 && account == self.appDelegate.account {
-                    
+
                 self.notifications.removeAll()
                 let sortedListOfNotifications = (notifications! as NSArray).sortedArray(using: [NSSortDescriptor(key: "date", ascending: false)])
-                    
+
                 for notification in sortedListOfNotifications {
                     if let icon = (notification as! NCCommunicationNotifications).icon {
-                        NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: icon, fileName: nil, width: 25, rewrite: false, account: self.appDelegate.account, closure: { (imageNamePath) in })
-                    }                    
+                        NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: icon, fileName: nil, width: 25, rewrite: false, account: self.appDelegate.account, closure: { _ in })
+                    }
                     self.notifications.append(notification as! NCCommunicationNotifications)
                 }
-                
+
                 self.reloadDatasource()
             }
-            
+
             NCUtility.shared.stopActivityIndicator()
         }
     }
@@ -305,9 +305,9 @@ class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmpty
 // MARK: -
 
 class NCNotificationCell: UITableViewCell, NCCellProtocol {
-    
-    @IBOutlet weak var icon : UIImageView!
-    @IBOutlet weak var avatar : UIImageView!
+
+    @IBOutlet weak var icon: UIImageView!
+    @IBOutlet weak var avatar: UIImageView!
     @IBOutlet weak var date: UILabel!
     @IBOutlet weak var subject: UILabel!
     @IBOutlet weak var message: UILabel!
@@ -317,13 +317,13 @@ class NCNotificationCell: UITableViewCell, NCCellProtocol {
     @IBOutlet weak var avatarLeadingMargin: NSLayoutConstraint!
     @IBOutlet weak var primaryWidth: NSLayoutConstraint!
     @IBOutlet weak var secondaryWidth: NSLayoutConstraint!
-    
+
     private var user = ""
 
-    var delegate: NCNotificationCellDelegate?
+    weak var delegate: NCNotificationCellDelegate?
     var notification: NCCommunicationNotifications?
-    
-    var filePreviewImageView : UIImageView? {
+
+    var filePreviewImageView: UIImageView? {
         get {
             return nil
         }
@@ -346,16 +346,16 @@ class NCNotificationCell: UITableViewCell, NCCellProtocol {
             user = newValue ?? ""
         }
     }
-    
+
     override func awakeFromNib() {
         super.awakeFromNib()
     }
-    
+
     @IBAction func touchUpInsideRemove(_ sender: Any) {
         guard let notification = notification else { return }
         delegate?.tapRemove(with: notification)
     }
-    
+
     @IBAction func touchUpInsidePrimary(_ sender: Any) {
         guard let notification = notification,
                 let button = sender as? UIButton,
@@ -363,7 +363,7 @@ class NCNotificationCell: UITableViewCell, NCCellProtocol {
         else { return }
         delegate?.tapAction(with: notification, label: label)
     }
-    
+
     @IBAction func touchUpInsideSecondary(_ sender: Any) {
         guard let notification = notification,
                 let button = sender as? UIButton,
@@ -373,7 +373,7 @@ class NCNotificationCell: UITableViewCell, NCCellProtocol {
     }
 }
 
-protocol NCNotificationCellDelegate {
+protocol NCNotificationCellDelegate: AnyObject {
     func tapRemove(with notification: NCCommunicationNotifications)
     func tapAction(with notification: NCCommunicationNotifications, label: String)
 }

+ 26 - 26
iOSClient/Offline/NCOffline.swift

@@ -24,80 +24,80 @@
 import UIKit
 import NCCommunication
 
-class NCOffline: NCCollectionViewCommon  {
-    
+class NCOffline: NCCollectionViewCommon {
+
     // MARK: - View Life Cycle
 
     required init?(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)
-        
+
         titleCurrentFolder = NSLocalizedString("_manage_file_offline_", comment: "")
         layoutKey = NCGlobal.shared.layoutViewOffline
         enableSearchBar = true
-        emptyImage = UIImage.init(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
+        emptyImage = UIImage(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
         emptyTitle = "_files_no_files_"
         emptyDescription = "_tutorial_offline_view_"
     }
-    
+
     // MARK: - DataSource + NC Endpoint
 
     override func reloadDataSource() {
         super.reloadDataSource()
-              
+
         DispatchQueue.global().async {
-            
+
             var ocIds: [String] = []
-            
+
             if !self.isSearching {
-                
+
                 if self.serverUrl == "" {
-                   
+
                     if let directories = NCManageDatabase.shared.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", self.appDelegate.account), sorted: "serverUrl", ascending: true) {
                         for directory: tableDirectory in directories {
                             ocIds.append(directory.ocId)
                         }
                     }
-                   
+
                     let files = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", self.appDelegate.account), sorted: "fileName", ascending: true)
                     for file: tableLocalFile in files {
                         ocIds.append(file.ocId)
                     }
-                   
+
                     self.metadatasSource = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND ocId IN %@", self.appDelegate.account, ocIds))
-                    
+
                 } else {
-                   
+
                     self.metadatasSource = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
                 }
             }
-            
-            self.dataSource = NCDataSource.init(metadatasSource: self.metadatasSource, sort: self.layoutForView?.sort, ascending: self.layoutForView?.ascending, directoryOnTop: self.layoutForView?.directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
-            
+
+            self.dataSource = NCDataSource(metadatasSource: self.metadatasSource, sort: self.layoutForView?.sort, ascending: self.layoutForView?.ascending, directoryOnTop: self.layoutForView?.directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
+
             DispatchQueue.main.async {
                 self.refreshControl.endRefreshing()
                 self.collectionView.reloadData()
             }
         }
     }
-       
+
     override func reloadDataSourceNetwork(forced: Bool = false) {
         super.reloadDataSourceNetwork(forced: forced)
-        
+
         if isSearching {
             networkSearch()
             return
         }
-                    
+
         if serverUrl == "" {
-            
+
             self.reloadDataSource()
-            
+
         } else {
-           
+
             isReloadDataSourceNetworkInProgress = true
             collectionView?.reloadData()
-            
-            networkReadFolder(forced: forced) { (tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, errorDescription) in
+
+            networkReadFolder(forced: forced) { tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, _ in
                 if errorCode == 0 {
                     for metadata in metadatas ?? [] {
                         if !metadata.directory {
@@ -107,7 +107,7 @@ class NCOffline: NCCollectionViewCommon  {
                         }
                     }
                 }
-                
+
                 DispatchQueue.main.async {
                     self.refreshControl.endRefreshing()
                     self.isReloadDataSourceNetworkInProgress = false

+ 25 - 26
iOSClient/Recent/NCRecent.swift

@@ -24,52 +24,52 @@
 import UIKit
 import NCCommunication
 
-class NCRecent: NCCollectionViewCommon  {
-    
+class NCRecent: NCCollectionViewCommon {
+
     // MARK: - View Life Cycle
 
     required init?(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)
-        
+
         titleCurrentFolder = NSLocalizedString("_recent_", comment: "")
         layoutKey = NCGlobal.shared.layoutViewRecent
         enableSearchBar = false
-        emptyImage = UIImage.init(named: "recent")?.image(color: .gray, size: UIScreen.main.bounds.width)
+        emptyImage = UIImage(named: "recent")?.image(color: .gray, size: UIScreen.main.bounds.width)
         emptyTitle = "_files_no_files_"
         emptyDescription = ""
     }
-    
+
     // MARK: - Collection View
-    
+
     override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
         return CGSize(width: collectionView.frame.width, height: 0)
     }
-    
+
     // MARK: - DataSource + NC Endpoint
-    
+
     override func reloadDataSource() {
         super.reloadDataSource()
-        
+
         DispatchQueue.global().async {
-            
+
             self.metadatasSource = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "account == %@", self.appDelegate.account), page: 1, limit: 100, sorted: "date", ascending: false)
-            self.dataSource = NCDataSource.init(metadatasSource: self.metadatasSource, directoryOnTop: false, favoriteOnTop: false)
-            
+            self.dataSource = NCDataSource(metadatasSource: self.metadatasSource, directoryOnTop: false, favoriteOnTop: false)
+
             DispatchQueue.main.async {
                 self.refreshControl.endRefreshing()
                 self.collectionView.reloadData()
             }
         }
     }
-    
+
     override func reloadDataSourceNetwork(forced: Bool = false) {
         super.reloadDataSourceNetwork(forced: forced)
-        
+
         if isSearching {
             networkSearch()
             return
         }
-        
+
         let requestBodyRecent =
         """
         <?xml version=\"1.0\"?>
@@ -131,21 +131,21 @@ class NCRecent: NCCollectionViewCommon  {
         </d:basicsearch>
         </d:searchrequest>
         """
-        
+
         let dateFormatter = DateFormatter()
-        dateFormatter.locale = Locale.init(identifier: "en_US_POSIX")
+        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
         dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
         let lessDateString = dateFormatter.string(from: Date())
         let requestBody = String(format: requestBodyRecent, "/files/"+appDelegate.userId, lessDateString)
-        
+
         isReloadDataSourceNetworkInProgress = true
         collectionView?.reloadData()
-        
-        NCCommunication.shared.searchBodyRequest(serverUrl: appDelegate.urlBase, requestBody: requestBody, showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: NCCommunicationCommon.shared.backgroundQueue) { (account, files, errorCode, errorDescription) in
-            
+
+        NCCommunication.shared.searchBodyRequest(serverUrl: appDelegate.urlBase, requestBody: requestBody, showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: NCCommunicationCommon.shared.backgroundQueue) { account, files, errorCode, _ in
+
             if errorCode == 0 {
-                NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { (metadataFolder, metadatasFolder, metadatas) in
-                    
+                NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { _, metadatasFolder, metadatas in
+
                     // Update sub directories
                     for metadata in metadatasFolder {
                         let serverUrl = metadata.serverUrl + "/" + metadata.fileName
@@ -153,7 +153,7 @@ class NCRecent: NCCollectionViewCommon  {
                     }
                     // Add metadatas
                     NCManageDatabase.shared.addMetadatas(metadatas)
-                    
+
                     self.reloadDataSource()
                 }
             } else {
@@ -161,7 +161,7 @@ class NCRecent: NCCollectionViewCommon  {
                     self.collectionView?.reloadData()
                 }
             }
-            
+
             DispatchQueue.main.async {
                 self.refreshControl.endRefreshing()
                 self.isReloadDataSourceNetworkInProgress = false
@@ -169,4 +169,3 @@ class NCRecent: NCCollectionViewCommon  {
         }
     }
 }
-

+ 56 - 56
iOSClient/Rename file/NCRenameFile.swift

@@ -24,7 +24,7 @@
 import UIKit
 import NCCommunication
 
-public protocol NCRenameFileDelegate {
+public protocol NCRenameFileDelegate: AnyObject {
     func rename(fileName: String, fileNameNew: String)
 }
 
@@ -46,62 +46,62 @@ class NCRenameFile: UIViewController, UITextFieldDelegate {
 
     let width: CGFloat = 300
     let height: CGFloat = 310
-    
+
     var metadata: tableMetadata?
     var fileName: String?
     var imagePreview: UIImage?
     var disableChangeExt: Bool = false
-    var delegate: NCRenameFileDelegate?
-    
+    weak var delegate: NCRenameFileDelegate?
+
     // MARK: - View Life Cycle
 
     override func viewDidLoad() {
         super.viewDidLoad()
-        
+
         if let metadata = self.metadata {
-                
+
             if metadata.directory {
                 titleLabel.text = NSLocalizedString("_rename_folder_", comment: "")
             } else {
                 titleLabel.text = NSLocalizedString("_rename_file_", comment: "")
             }
-            
+
             fileNameWithoutExt.text = (metadata.fileNameView as NSString).deletingPathExtension
             fileNameWithoutExt.delegate = self
             fileNameWithoutExt.becomeFirstResponder()
-            
+
             ext.text = (metadata.fileNameView as NSString).pathExtension
             ext.delegate = self
             if disableChangeExt {
                 ext.isEnabled = false
                 ext.textColor = .lightGray
             }
-            
+
             previewFile.image = imagePreview
             previewFile.layer.cornerRadius = 10
             previewFile.layer.masksToBounds = true
 
             if metadata.directory {
-                
+
                 if imagePreview == nil {
                     previewFile.image = NCBrandColor.cacheImages.folder
                 }
-                
+
                 ext.isHidden = true
                 point.isHidden = true
                 fileNameWithoutExtTrailingContraint.constant = 20
-                
+
             } else {
-                
+
                 if imagePreview == nil {
                     previewFile.image = NCBrandColor.cacheImages.file
                 }
-                
+
                 fileNameWithoutExtTrailingContraint.constant = 90
             }
-            
+
         } else if let fileName = self.fileName {
-        
+
             titleLabel.text = NSLocalizedString("_rename_file_", comment: "")
 
             fileNameWithoutExt.text = (fileName as NSString).deletingPathExtension
@@ -111,7 +111,7 @@ class NCRenameFile: UIViewController, UITextFieldDelegate {
 
             ext.text = (fileName as NSString).pathExtension
             ext.delegate = self
-            
+
             if imagePreview == nil {
                 previewFile.image = NCBrandColor.cacheImages.file
             } else {
@@ -120,96 +120,96 @@ class NCRenameFile: UIViewController, UITextFieldDelegate {
             previewFile.layer.cornerRadius = 10
             previewFile.layer.masksToBounds = true
         }
-        
+
         cancelButton.setTitle(NSLocalizedString("_cancel_", comment: ""), for: .normal)
         renameButton.setTitle(NSLocalizedString("_rename_", comment: ""), for: .normal)
     }
-    
+
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
     }
-    
+
     override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)
-        
+
         if metadata == nil && fileName == nil {
             dismiss(animated: true)
         }
-        
+
         fileNameWithoutExt.selectAll(nil)
     }
-    
+
     func textFieldShouldReturn(_ textField: UITextField) -> Bool {
-        
+
         textField.resignFirstResponder()
         rename(textField)
         return true
     }
-    
+
     // MARK: - Action
-    
+
     @IBAction func cancel(_ sender: Any) {
-        
+
         dismiss(animated: true)
     }
-    
+
     @IBAction func rename(_ sender: Any) {
 
         var fileNameWithoutExtNew = ""
         var extNew = ""
         var fileNameNew = ""
-        
+
         if let metadata = self.metadata {
-        
+
             if fileNameWithoutExt.text == nil || fileNameWithoutExt.text?.count == 0 {
                 self.fileNameWithoutExt.text = (metadata.fileNameView as NSString).deletingPathExtension
                 return
             } else {
                 fileNameWithoutExtNew = fileNameWithoutExt.text!
             }
-            
+
             if metadata.directory {
-                
+
                 fileNameNew = fileNameWithoutExtNew
                 renameMetadata(metadata, fileNameNew: fileNameNew)
-                
+
             } else {
-                
+
                 if ext.text == nil || ext.text?.count == 0 {
                     self.ext.text = (metadata.fileNameView as NSString).pathExtension
                     return
                 } else {
                     extNew = ext.text!
                 }
-                
+
                 if extNew != metadata.ext {
-                    
+
                     let message = String(format: NSLocalizedString("_rename_ext_message_", comment: ""), extNew, metadata.ext)
                     let alertController = UIAlertController(title: NSLocalizedString("_rename_ext_title_", comment: ""), message: message, preferredStyle: .alert)
-                                
+
                     var title = NSLocalizedString("_use_", comment: "") + " ." + extNew
-                    alertController.addAction(UIAlertAction(title: title, style: .default, handler: { action in
-                        
+                    alertController.addAction(UIAlertAction(title: title, style: .default, handler: { _ in
+
                         fileNameNew = fileNameWithoutExtNew + "." + extNew
                         self.renameMetadata(metadata, fileNameNew: fileNameNew)
                     }))
-                    
+
                     title = NSLocalizedString("_keep_", comment: "") + " ." + metadata.ext
-                    alertController.addAction(UIAlertAction(title: title, style: .default, handler: { action in
+                    alertController.addAction(UIAlertAction(title: title, style: .default, handler: { _ in
                         self.ext.text = (metadata.fileNameView as NSString).pathExtension
                     }))
-                    
+
                     self.present(alertController, animated: true)
-                    
+
                 } else {
-                
+
                     fileNameNew = fileNameWithoutExtNew + "." + extNew
                     renameMetadata(metadata, fileNameNew: fileNameNew)
                 }
             }
-            
+
         } else if let fileName = self.fileName {
-            
+
             if fileNameWithoutExt.text == nil || fileNameWithoutExt.text?.count == 0 {
                 fileNameWithoutExt.text = (fileName as NSString).deletingPathExtension
                 return
@@ -217,29 +217,29 @@ class NCRenameFile: UIViewController, UITextFieldDelegate {
                 ext.text = (fileName as NSString).pathExtension
                 return
             }
-            
+
             fileNameNew = (fileNameWithoutExt.text ?? "") + "." + (ext.text ?? "")
             self.delegate?.rename(fileName: fileName, fileNameNew: fileNameNew)
             self.dismiss(animated: true)
         }
     }
-    
+
     // MARK: - Networking
 
     func renameMetadata(_ metadata: tableMetadata, fileNameNew: String) {
-        
+
         NCUtility.shared.startActivityIndicator(backgroundView: nil, blurEffect: true)
-        
-        NCNetworking.shared.renameMetadata(metadata, fileNameNew: fileNameNew, viewController: self) { (errorCode, errorDescription) in
-            
+
+        NCNetworking.shared.renameMetadata(metadata, fileNameNew: fileNameNew, viewController: self) { errorCode, errorDescription in
+
             NCUtility.shared.stopActivityIndicator()
-            
+
             if errorCode == 0 {
-                
+
                 self.dismiss(animated: true)
-                
+
             } else {
-                
+
                 NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
             }
         }

+ 35 - 35
iOSClient/RichWorkspace/NCRichWorkspaceCommon.swift

@@ -28,81 +28,81 @@ import NCCommunication
 
     let appDelegate = UIApplication.shared.delegate as! AppDelegate
 
-    @objc func createViewerNextcloudText(serverUrl: String,viewController: UIViewController) {
-        
+    @objc func createViewerNextcloudText(serverUrl: String, viewController: UIViewController) {
+
         if !NCCommunication.shared.isNetworkReachable() {
             NCContentPresenter.shared.messageNotification("_error_", description: "_go_online_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorInternalError)
-            return;
+            return
         }
-        
+
         guard let directEditingCreator = NCManageDatabase.shared.getDirectEditingCreators(predicate: NSPredicate(format: "account == %@ AND editor == 'text'", appDelegate.account))?.first else { return }
-        
+
         NCUtility.shared.startActivityIndicator(backgroundView: viewController.view, blurEffect: true)
-        
+
         let fileNamePath = CCUtility.returnFileNamePath(fromFileName: NCGlobal.shared.fileNameRichWorkspace, serverUrl: serverUrl, urlBase: appDelegate.urlBase, account: appDelegate.account)!
-        NCCommunication.shared.NCTextCreateFile(fileNamePath: fileNamePath, editorId: directEditingCreator.editor, creatorId: directEditingCreator.identifier ,templateId: "") { (account, url, errorCode, errorMessage) in
-            
+        NCCommunication.shared.NCTextCreateFile(fileNamePath: fileNamePath, editorId: directEditingCreator.editor, creatorId: directEditingCreator.identifier, templateId: "") { account, url, errorCode, errorMessage in
+
             NCUtility.shared.stopActivityIndicator()
-            
+
             if errorCode == 0 && account == self.appDelegate.account {
-                
-                if let viewerRichWorkspaceWebView = UIStoryboard.init(name: "NCViewerRichWorkspace", bundle: nil).instantiateViewController(withIdentifier: "NCViewerRichWorkspaceWebView") as? NCViewerRichWorkspaceWebView {
-                    
+
+                if let viewerRichWorkspaceWebView = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateViewController(withIdentifier: "NCViewerRichWorkspaceWebView") as? NCViewerRichWorkspaceWebView {
+
                     viewerRichWorkspaceWebView.url = url!
                     viewerRichWorkspaceWebView.presentationController?.delegate = viewController as? UIAdaptivePresentationControllerDelegate
-                    
+
                     viewController.present(viewerRichWorkspaceWebView, animated: true, completion: nil)
                 }
-                
+
             } else if errorCode != 0 {
                 NCContentPresenter.shared.messageNotification("_error_", description: errorMessage, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: errorCode)
             }
         }
     }
-    
+
     @objc func openViewerNextcloudText(serverUrl: String, viewController: UIViewController) {
-        
+
         if !NCCommunication.shared.isNetworkReachable() {
-            
+
             NCContentPresenter.shared.messageNotification("_error_", description: "_go_online_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorInternalError)
-            return;
+            return
         }
-        
+
         if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", appDelegate.account, serverUrl, NCGlobal.shared.fileNameRichWorkspace.lowercased())) {
-            
+
             if metadata.url == "" {
-                
+
                 NCUtility.shared.startActivityIndicator(backgroundView: viewController.view, blurEffect: true)
-                
+
                 let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: appDelegate.urlBase, account: appDelegate.account)!
-                NCCommunication.shared.NCTextOpenFile(fileNamePath: fileNamePath, editor: "text") { (account, url, errorCode, errorMessage) in
-                    
+                NCCommunication.shared.NCTextOpenFile(fileNamePath: fileNamePath, editor: "text") { account, url, errorCode, errorMessage in
+
                     NCUtility.shared.stopActivityIndicator()
-                    
+
                     if errorCode == 0 && account == self.appDelegate.account {
-                        
-                        if let viewerRichWorkspaceWebView = UIStoryboard.init(name: "NCViewerRichWorkspace", bundle: nil).instantiateViewController(withIdentifier: "NCViewerRichWorkspaceWebView") as? NCViewerRichWorkspaceWebView {
-                            
+
+                        if let viewerRichWorkspaceWebView = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateViewController(withIdentifier: "NCViewerRichWorkspaceWebView") as? NCViewerRichWorkspaceWebView {
+
                             viewerRichWorkspaceWebView.url = url!
                             viewerRichWorkspaceWebView.metadata = metadata
                             viewerRichWorkspaceWebView.presentationController?.delegate = viewController as? UIAdaptivePresentationControllerDelegate
-                            
+
                             viewController.present(viewerRichWorkspaceWebView, animated: true, completion: nil)
                         }
-                        
+
                     } else if errorCode != 0 {
                         NCContentPresenter.shared.messageNotification("_error_", description: errorMessage, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: errorCode)
                     }
                 }
-                
+
             } else {
-                
-                if let viewerRichWorkspaceWebView = UIStoryboard.init(name: "NCViewerRichWorkspace", bundle: nil).instantiateViewController(withIdentifier: "NCViewerRichWorkspaceWebView") as? NCViewerRichWorkspaceWebView {
-                    
+
+                if let viewerRichWorkspaceWebView = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateViewController(withIdentifier: "NCViewerRichWorkspaceWebView") as? NCViewerRichWorkspaceWebView {
+
                     viewerRichWorkspaceWebView.url = metadata.url
                     viewerRichWorkspaceWebView.metadata = metadata
                     viewerRichWorkspaceWebView.presentationController?.delegate = viewController as? UIAdaptivePresentationControllerDelegate
-                    
+
                     viewController.present(viewerRichWorkspaceWebView, animated: true, completion: nil)
                 }
             }

+ 14 - 14
iOSClient/RichWorkspace/NCViewerRichWorkspace.swift

@@ -28,7 +28,7 @@ import MarkdownKit
 @objc class NCViewerRichWorkspace: UIViewController, UIAdaptivePresentationControllerDelegate {
 
     @IBOutlet weak var textView: UITextView!
-    
+
     private let appDelegate = UIApplication.shared.delegate as! AppDelegate
     private let richWorkspaceCommon = NCRichWorkspaceCommon()
     private var markdownParser = MarkdownParser()
@@ -36,32 +36,32 @@ import MarkdownKit
 
     @objc public var richWorkspaceText: String = ""
     @objc public var serverUrl: String = ""
-   
+
     // MARK: - View Life Cycle
 
     override func viewDidLoad() {
         super.viewDidLoad()
-        
+
         view.backgroundColor = NCBrandColor.shared.systemBackground
         presentationController?.delegate = self
-        
+
         let closeItem = UIBarButtonItem(title: NSLocalizedString("_back_", comment: ""), style: .plain, target: self, action: #selector(closeItemTapped(_:)))
         self.navigationItem.leftBarButtonItem = closeItem
-                
+
         let editItem = UIBarButtonItem(image: UIImage(named: "actionSheetModify"), style: UIBarButtonItem.Style.plain, target: self, action: #selector(editItemAction(_:)))
         self.navigationItem.rightBarButtonItem = editItem
-        
+
         markdownParser = MarkdownParser(font: UIFont.systemFont(ofSize: 15), color: NCBrandColor.shared.label)
         markdownParser.header.font = UIFont.systemFont(ofSize: 25)
         textView.attributedText = markdownParser.parse(richWorkspaceText)
         textViewColor = NCBrandColor.shared.label
     }
-    
+
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
-        
-        NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { (account, metadata, errorCode, errorDescription) in
-            
+
+        NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { account, metadata, errorCode, _ in
+
             if errorCode == 0 && account == self.appDelegate.account {
                 guard let metadata = metadata else { return }
                 NCManageDatabase.shared.setDirectory(richWorkspace: metadata.richWorkspace, serverUrl: self.serverUrl, account: account)
@@ -75,17 +75,17 @@ import MarkdownKit
             }
         }
     }
-    
+
     public func presentationControllerWillDismiss(_ presentationController: UIPresentationController) {
         self.viewWillAppear(true)
     }
-    
+
     @objc func closeItemTapped(_ sender: UIBarButtonItem) {
         self.dismiss(animated: false, completion: nil)
     }
-    
+
     @IBAction func editItemAction(_ sender: Any) {
-        
+
         richWorkspaceCommon.openViewerNextcloudText(serverUrl: serverUrl, viewController: self)
     }
 }

+ 30 - 31
iOSClient/RichWorkspace/NCViewerRichWorkspaceWebView.swift

@@ -25,11 +25,10 @@ import UIKit
 import WebKit
 
 class NCViewerRichWorkspaceWebView: UIViewController, WKNavigationDelegate, WKScriptMessageHandler {
-    
+
     @IBOutlet weak var webView: WKWebView!
     @IBOutlet weak var webViewBottomConstraint: NSLayoutConstraint!
 
-    let appDelegate = UIApplication.shared.delegate as! AppDelegate
     @objc var metadata: tableMetadata?
     @objc var url: String = ""
 
@@ -37,23 +36,23 @@ class NCViewerRichWorkspaceWebView: UIViewController, WKNavigationDelegate, WKSc
 
     override func viewDidLoad() {
         super.viewDidLoad()
-        
-        let userAgent : String = CCUtility.getUserAgent()
-        
+
+        let userAgent: String = CCUtility.getUserAgent()
+
         NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)
         NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
-                
+
         var request = URLRequest(url: URL(string: url)!)
         request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
         let language = NSLocale.preferredLanguages[0] as String
         request.addValue(language, forHTTPHeaderField: "Accept-Language")
-                
+
         webView.configuration.userContentController.add(self, name: "DirectEditingMobileInterface")
         webView.navigationDelegate = self
         webView.customUserAgent = userAgent
         webView.load(request)
     }
-    
+
     @objc func keyboardDidShow(notification: Notification) {
         let safeAreaInsetsBottom = UIApplication.shared.keyWindow!.safeAreaInsets.bottom
         guard let info = notification.userInfo else { return }
@@ -61,67 +60,67 @@ class NCViewerRichWorkspaceWebView: UIViewController, WKNavigationDelegate, WKSc
         let keyboardFrame = frameInfo.cgRectValue
         webViewBottomConstraint.constant = keyboardFrame.size.height - safeAreaInsetsBottom
     }
-    
+
     @objc func keyboardWillHide(notification: Notification) {
         webViewBottomConstraint.constant = 0
     }
-    
-    //MARK: -
+
+    // MARK: -
 
     public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
-        
-        if (message.name == "DirectEditingMobileInterface") {
-            
+
+        if message.name == "DirectEditingMobileInterface" {
+
             if message.body as? String == "close" {
-                
+
                 if #available(iOS 13.0, *) {
                     self.presentationController?.delegate?.presentationControllerWillDismiss?(self.presentationController!)
                 }
-                
+
                 dismiss(animated: true) {
                     NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView, userInfo: nil)
                 }
             }
-            
+
             if message.body as? String == "share" {
-                if (metadata != nil) {
-                    NCFunctionCenter.shared.openShare(ViewController: self, metadata: metadata!, indexPage: .sharing)
+                if metadata != nil {
+                    NCFunctionCenter.shared.openShare(viewController: self, metadata: metadata!, indexPage: .sharing)
                 }
             }
-            
+
             if message.body as? String == "loading" {
                 print("loading")
             }
-            
+
             if message.body as? String == "loaded" {
                 print("loaded")
             }
-            
+
             if message.body as? String == "paste" {
                 self.paste(self)
             }
         }
     }
-        
-    //MARK: -
+
+    // MARK: -
 
     public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
         if let serverTrust = challenge.protectionSpace.serverTrust {
             completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
         } else {
-            completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil);
+            completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
         }
     }
-    
+
     public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
-        print("didStartProvisionalNavigation");
+        print("didStartProvisionalNavigation")
     }
-    
+
     public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
-        print("didReceiveServerRedirectForProvisionalNavigation");
+        print("didReceiveServerRedirectForProvisionalNavigation")
     }
-    
+
     public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
-        print("didFinish");
+        print("didFinish")
     }
 }

+ 1 - 1
iOSClient/ScanDocument/ScanCell.swift

@@ -24,7 +24,7 @@
 import UIKit
 
 class ScanCell: UICollectionViewCell {
-    
+
     @IBOutlet weak var customImageView: UIImageView!
     @IBOutlet weak var customLabel: UILabel!
     @IBOutlet weak var delete: UIButton!

+ 177 - 181
iOSClient/ScanDocument/ScanCollectionView.swift

@@ -25,17 +25,17 @@ import UIKit
 
 @available(iOS 13.0, *)
 class DragDropViewController: UIViewController {
-    
-    //Data Source for collectionViewSource
+
+    // Data Source for collectionViewSource
     private var itemsSource: [String] = []
-    
-    //Data Source for collectionViewDestination
+
+    // Data Source for collectionViewDestination
     private var imagesDestination: [UIImage] = []
     private var itemsDestination: [String] = []
-    
+
     private let appDelegate = UIApplication.shared.delegate as! AppDelegate
 
-    //MARK: Outlets
+    // MARK: Outlets
     @IBOutlet weak var collectionViewSource: UICollectionView!
     @IBOutlet weak var collectionViewDestination: UICollectionView!
     @IBOutlet weak var cancel: UIBarButtonItem!
@@ -52,14 +52,14 @@ class DragDropViewController: UIViewController {
         case bn
     }
     private var filter: typeFilter = typeFilter.original
-    
+
     override var canBecomeFirstResponder: Bool { return true }
-    
+
     // MARK: - View Life Cycle
-    
+
     override func viewDidLoad() {
         super.viewDidLoad()
-        
+
         view.backgroundColor = NCBrandColor.shared.secondarySystemGroupedBackground
         navigationItem.title = NSLocalizedString("_scanned_images_", comment: "")
 
@@ -71,12 +71,12 @@ class DragDropViewController: UIViewController {
         collectionViewDestination.dragInteractionEnabled = true
         collectionViewDestination.dropDelegate = self
         collectionViewDestination.dragDelegate = self
-        collectionViewDestination.reorderingCadence = .fast //default value - .immediate
+        collectionViewDestination.reorderingCadence = .fast // default value - .immediate
         collectionViewDestination.backgroundColor = NCBrandColor.shared.secondarySystemGroupedBackground
 
         cancel.title = NSLocalizedString("_cancel_", comment: "")
         save.title = NSLocalizedString("_save_", comment: "")
-        
+
         labelTitlePDFzone.text = NSLocalizedString("_scan_label_document_zone_", comment: "")
         labelTitlePDFzone.backgroundColor = NCBrandColor.shared.systemGray6
         labelTitlePDFzone.textColor = NCBrandColor.shared.label
@@ -87,86 +87,85 @@ class DragDropViewController: UIViewController {
 
         add.setImage(UIImage(named: "plus")?.image(color: NCBrandColor.shared.label, size: 25), for: .normal)
         transferDown.setImage(UIImage(named: "transferDown")?.image(color: NCBrandColor.shared.label, size: 25), for: .normal)
-        
+
         let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(recognizer:)))
         collectionViewSource.addGestureRecognizer(longPressRecognizer)
         let longPressRecognizerPlus = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(recognizer:)))
         add.addGestureRecognizer(longPressRecognizerPlus)
-        
+
         collectionViewSource.reloadData()
         collectionViewDestination.reloadData()
-        
+
         loadImage()
     }
-    
+
     override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
         super.traitCollectionDidChange(previousTraitCollection)
-        
+
         add.setImage(UIImage(named: "plus")?.image(color: NCBrandColor.shared.label, size: 25), for: .normal)
         transferDown.setImage(UIImage(named: "transferDown")?.image(color: NCBrandColor.shared.label, size: 25), for: .normal)
     }
-    
-    //MARK: Button Action
+
+    // MARK: Button Action
 
     @IBAction func cancelAction(sender: UIBarButtonItem) {
         self.dismiss(animated: true, completion: nil)
     }
-    
+
     @IBAction func saveAction(sender: UIBarButtonItem) {
-        
+
         if imagesDestination.count > 0 {
-            
+
             var images: [UIImage] = []
             let serverUrl = appDelegate.activeServerUrl
 
             for image in imagesDestination {
                 images.append(filter(image: image)!)
             }
-            
+
 //            if let directory = CCUtility.getDirectoryScanDocuments() {
 //                serverUrl = directory
 //            }
-            
-            let formViewController = NCCreateFormUploadScanDocument.init(serverUrl: serverUrl, arrayImages: images)
+
+            let formViewController = NCCreateFormUploadScanDocument(serverUrl: serverUrl, arrayImages: images)
             self.navigationController?.pushViewController(formViewController, animated: true)
         }
     }
-    
+
     @IBAction func add(sender: UIButton) {
-        
+
         NCCreateScanDocument.shared.openScannerDocument(viewController: self)
     }
-    
+
     @IBAction func transferDown(sender: UIButton) {
-     
+
         for fileName in itemsSource {
-            
+
             if !itemsDestination.contains(fileName) {
-                
+
                 let fileNamePathAt = CCUtility.getDirectoryScan() + "/" + fileName
-                
+
                 guard let data = try? Data(contentsOf: URL(fileURLWithPath: fileNamePathAt)) else { return }
                 guard let image = UIImage(data: data) else { return }
-                
+
                 imagesDestination.append(image)
                 itemsDestination.append(fileName)
             }
         }
-        
+
         // Save button
         if imagesDestination.count == 0 {
             save.isEnabled = false
         } else {
             save.isEnabled = true
         }
-        
+
         collectionViewDestination.reloadData()
     }
-    
+
     @IBAction func indexChanged(_ sender: AnyObject) {
-        
-        switch segmentControlFilter.selectedSegmentIndex
-        {
+
+        switch segmentControlFilter.selectedSegmentIndex {
         case 0:
             filter = typeFilter.original
         case 1:
@@ -176,12 +175,12 @@ class DragDropViewController: UIViewController {
         default:
             break
         }
-        
+
         collectionViewDestination.reloadData()
     }
-    
+
     func loadImage() {
-        
+
         itemsSource.removeAll()
 
         do {
@@ -195,11 +194,11 @@ class DragDropViewController: UIViewController {
         } catch {
             print(error.localizedDescription)
         }
-        
+
         itemsSource = itemsSource.sorted()
-        
+
         collectionViewSource.reloadData()
-        
+
         // Save button
         if imagesDestination.count == 0 {
             save.isEnabled = false
@@ -207,162 +206,161 @@ class DragDropViewController: UIViewController {
             save.isEnabled = true
         }
     }
-    
-    //MARK: Private Methods
-    
+
+    // MARK: Private Methods
+
     func filter(image: UIImage) -> UIImage? {
-        
+
         var inputContrast: Double = 0
-        
+
         if filter == typeFilter.original {
             return image
         }
-        
+
         if filter == typeFilter.grayScale {
             inputContrast = 1
         }
-        
+
         if filter == typeFilter.bn {
             inputContrast = 4
         }
-        
+
         let ciImage = CIImage(image: image)!
         let imageFilter = ciImage.applyingFilter("CIColorControls", parameters: ["inputSaturation": 0, "inputContrast": inputContrast])
-        
-        let context:CIContext = CIContext.init(options: nil)
-        let cgImage:CGImage = context.createCGImage(imageFilter, from: imageFilter.extent)!
-        let image:UIImage = UIImage.init(cgImage: cgImage)
+
+        let context: CIContext = CIContext(options: nil)
+        let cgImage: CGImage = context.createCGImage(imageFilter, from: imageFilter.extent)!
+        let image: UIImage = UIImage(cgImage: cgImage)
         return image
     }
-    
+
     /// This method moves a cell from source indexPath to destination indexPath within the same collection view. It works for only 1 item. If multiple items selected, no reordering happens.
     ///
     /// - Parameters:
     ///   - coordinator: coordinator obtained from performDropWith: UICollectionViewDropDelegate method
     ///   - destinationIndexPath: indexpath of the collection view where the user drops the element
     ///   - collectionView: collectionView in which reordering needs to be done.
-    
+
     private func reorderItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView) {
-        
+
         let items = coordinator.items
-        
+
         if items.count == 1, let item = items.first, let sourceIndexPath = item.sourceIndexPath {
-            
+
             var dIndexPath = destinationIndexPath
-            
+
             if dIndexPath.row >= collectionView.numberOfItems(inSection: 0) {
                 dIndexPath.row = collectionView.numberOfItems(inSection: 0) - 1
             }
-            
+
             collectionView.performBatchUpdates({
-                
+
                 if collectionView === collectionViewDestination {
-                    
+
                     imagesDestination.remove(at: sourceIndexPath.row)
                     imagesDestination.insert(item.dragItem.localObject as! UIImage, at: dIndexPath.row)
-                    
+
                     let fileName = itemsDestination[sourceIndexPath.row]
                     itemsDestination.remove(at: sourceIndexPath.row)
                     itemsDestination.insert(fileName, at: dIndexPath.row)
-                
+
                 } else {
-                    
+
                     itemsSource.remove(at: sourceIndexPath.row)
                     itemsSource.insert(item.dragItem.localObject as! String, at: dIndexPath.row)
                 }
-                
+
                 collectionView.deleteItems(at: [sourceIndexPath])
                 collectionView.insertItems(at: [dIndexPath])
             })
-            
+
             coordinator.drop(items.first!.dragItem, toItemAt: dIndexPath)
         }
     }
-    
+
     /// This method copies a cell from source indexPath in 1st collection view to destination indexPath in 2nd collection view. It works for multiple items.
     ///
     /// - Parameters:
     ///   - coordinator: coordinator obtained from performDropWith: UICollectionViewDropDelegate method
     ///   - destinationIndexPath: indexpath of the collection view where the user drops the element
     ///   - collectionView: collectionView in which reordering needs to be done.
-    
-    private func copyItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView)
-    {
+
+    private func copyItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView) {
         collectionView.performBatchUpdates({
-            
+
             var indexPaths: [IndexPath] = []
-            
+
             for (index, item) in coordinator.items.enumerated() {
-                
+
                 let indexPath = IndexPath(row: destinationIndexPath.row + index, section: destinationIndexPath.section)
-                
+
                 if collectionView === collectionViewDestination {
-                    
+
                     let fileName = item.dragItem.localObject as! String
                     let fileNamePathAt = CCUtility.getDirectoryScan() + "/" + fileName
-                    
+
                     guard let data = try? Data(contentsOf: URL(fileURLWithPath: fileNamePathAt)) else {
                         return
                     }
                     guard let image =  UIImage(data: data) else {
                         return
                     }
-                   
+
                     imagesDestination.insert(image, at: indexPath.row)
                     itemsDestination.insert(fileName, at: indexPath.row)
-                    
+
                 } else {
-                    
+
                     // NOT PERMITTED
                     return
                 }
-                
+
                 indexPaths.append(indexPath)
             }
-            
+
             collectionView.insertItems(at: indexPaths)
         })
     }
-    
+
     // MARK: - UIGestureRecognizerv - Paste
-    
+
     @objc func handleLongPressGesture(recognizer: UIGestureRecognizer) {
-        
+
         if recognizer.state == UIGestureRecognizer.State.began {
-        
+
             self.becomeFirstResponder()
-            
+
             let pasteboard = UIPasteboard.general
-            
+
             if let recognizerView = recognizer.view, let recognizerSuperView = recognizerView.superview, pasteboard.hasImages {
-                
+
                 UIMenuController.shared.menuItems = [UIMenuItem(title: "Paste", action: #selector(pasteImage))]
                 UIMenuController.shared.setTargetRect(recognizerView.frame, in: recognizerSuperView)
-                UIMenuController.shared.setMenuVisible(true, animated:true)
+                UIMenuController.shared.setMenuVisible(true, animated: true)
             }
         }
     }
-    
+
     override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
         if action == #selector(pasteImage) {
             return true
         }
         return false
     }
-    
+
     @objc func pasteImage() {
-        
+
         let pasteboard = UIPasteboard.general
-        
+
         if pasteboard.hasImages {
-            
+
             let fileName = CCUtility.createFileName("scan.png", fileDate: Date(), fileType: PHAssetMediaType.image, keyFileName: NCGlobal.shared.keyFileNameMask, keyFileNameType: NCGlobal.shared.keyFileNameType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal, forcedNewFileName: true)!
             let fileNamePath = CCUtility.getDirectoryScan() + "/" + fileName
-            
+
             guard let image = pasteboard.image?.fixedOrientation() else {
                 return
             }
-            
+
             do {
                 try image.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath), options: .atomic)
             } catch {
@@ -377,79 +375,79 @@ class DragDropViewController: UIViewController {
 // MARK: - UICollectionViewDataSource Methods
 
 @available(iOS 13.0, *)
-extension DragDropViewController : UICollectionViewDataSource {
-    
+extension DragDropViewController: UICollectionViewDataSource {
+
     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
-        
+
         return collectionView == collectionViewSource ? itemsSource.count : imagesDestination.count
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
-        
+
         if collectionView == collectionViewSource {
-            
+
             let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath) as! ScanCell
-            
+
             let fileNamePath = CCUtility.getDirectoryScan() + "/" + itemsSource[indexPath.row]
-            
+
             guard let data = try? Data(contentsOf: URL(fileURLWithPath: fileNamePath)) else {
                 return cell
             }
-            
+
             guard var image = UIImage(data: data) else {
                 return cell
             }
-            
+
             let imageWidthInPixels = image.size.width * image.scale
             let imageHeightInPixels = image.size.height * image.scale
-            
+
             // 72 DPI
-            if imageWidthInPixels > 595 || imageHeightInPixels > 842  {
+            if imageWidthInPixels > 595 || imageHeightInPixels > 842 {
                 image = image.resizeImage(size: CGSize(width: 595, height: 842), isAspectRation: true) ?? image
             }
-            
+
             cell.customImageView?.image = image
             cell.delete.action(for: .touchUpInside) { sender in
-                
-                let buttonPosition:CGPoint = (sender as! UIButton).convert(.zero, to: self.collectionViewSource)
+
+                let buttonPosition: CGPoint = (sender as! UIButton).convert(.zero, to: self.collectionViewSource)
                 if let indexPath = self.collectionViewSource.indexPathForItem(at: buttonPosition) {
-                
+
                     let fileNameAtPath = CCUtility.getDirectoryScan() + "/" + self.itemsSource[indexPath.row]
                     CCUtility.removeFile(atPath: fileNameAtPath)
                     self.itemsSource.remove(at: indexPath.row)
-                    
+
                     self.collectionViewSource.reloadData()
                 }
             }
 
             return cell
-            
+
         } else {
-            
+
             let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell2", for: indexPath) as! ScanCell
-            
+
             var image = imagesDestination[indexPath.row]
-            
+
             let imageWidthInPixels = image.size.width * image.scale
             let imageHeightInPixels = image.size.height * image.scale
-            
+
             // 72 DPI 
-            if imageWidthInPixels > 595 || imageHeightInPixels > 842  {
+            if imageWidthInPixels > 595 || imageHeightInPixels > 842 {
                 image = image.resizeImage(size: CGSize(width: 595, height: 842), isAspectRation: true) ?? image
             }
-            
+
             cell.customImageView?.image = self.filter(image: image)
             cell.customLabel.text = NSLocalizedString("_scan_document_pdf_page_", comment: "") + " " + "\(indexPath.row+1)"
             cell.delete.action(for: .touchUpInside) { sender in
-                
-                let buttonPosition:CGPoint = (sender as! UIButton).convert(.zero, to: self.collectionViewDestination)
+
+                let buttonPosition: CGPoint = (sender as! UIButton).convert(.zero, to: self.collectionViewDestination)
                 if let indexPath = self.collectionViewDestination.indexPathForItem(at: buttonPosition) {
-                
+
                     self.imagesDestination.remove(at: indexPath.row)
                     self.itemsDestination.remove(at: indexPath.row)
-                    
+
                     self.collectionViewDestination.reloadData()
-                    
+
                     // Save button
                     if self.imagesDestination.count == 0 {
                         self.save.isEnabled = false
@@ -459,17 +457,17 @@ extension DragDropViewController : UICollectionViewDataSource {
                 }
             }
             cell.rotate.action(for: .touchUpInside) { sender in
-                
-                let buttonPosition:CGPoint = (sender as! UIButton).convert(.zero, to: self.collectionViewDestination)
+
+                let buttonPosition: CGPoint = (sender as! UIButton).convert(.zero, to: self.collectionViewDestination)
                 if let indexPath = self.collectionViewDestination.indexPathForItem(at: buttonPosition) {
-                
+
                     let image = self.imagesDestination[indexPath.row]
                     self.imagesDestination[indexPath.row] = image.rotate(radians: .pi/2)!
-                    
+
                     self.collectionViewDestination.reloadData()
                 }
             }
-            
+
             return cell
         }
     }
@@ -481,20 +479,20 @@ extension UIImage {
         // Trim off the extremely small float value to prevent core graphics from rounding it up
         newSize.width = floor(newSize.width)
         newSize.height = floor(newSize.height)
-        
+
         UIGraphicsBeginImageContextWithOptions(newSize, true, self.scale)
         let context = UIGraphicsGetCurrentContext()!
-        
+
         // Move origin to middle
         context.translateBy(x: newSize.width/2, y: newSize.height/2)
         // Rotate around middle
         context.rotate(by: CGFloat(radians))
         // Draw the image at its center
         self.draw(in: CGRect(x: -self.size.width/2, y: -self.size.height/2, width: self.size.width, height: self.size.height))
-        
+
         let newImage = UIGraphicsGetImageFromCurrentImageContext()
         UIGraphicsEndImageContext()
-        
+
         return newImage
     }
 }
@@ -502,10 +500,9 @@ extension UIImage {
 // MARK: - UICollectionViewDragDelegate Methods
 
 @available(iOS 13.0, *)
-extension DragDropViewController : UICollectionViewDragDelegate
-{
+extension DragDropViewController: UICollectionViewDragDelegate {
     func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
-        
+
         if collectionView == collectionViewSource {
             let item = itemsSource[indexPath.row]
             let itemProvider = NSItemProvider(object: item as NSString)
@@ -521,42 +518,42 @@ extension DragDropViewController : UICollectionViewDragDelegate
             let dragItem = UIDragItem(itemProvider: itemProvider)
 
             dragItem.localObject = item
-            
+
             return [dragItem]
         }
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, itemsForAddingTo session: UIDragSession, at indexPath: IndexPath, point: CGPoint) -> [UIDragItem] {
-        
+
         if collectionView == collectionViewSource {
             let item = itemsSource[indexPath.row]
             let itemProvider = NSItemProvider(object: item as NSString)
             let dragItem = UIDragItem(itemProvider: itemProvider)
-            
+
             dragItem.localObject = item
-            
+
             return [dragItem]
-            
+
         } else {
             let item = imagesDestination[indexPath.row]
             let itemProvider = NSItemProvider(object: item as UIImage)
             let dragItem = UIDragItem(itemProvider: itemProvider)
-            
+
             dragItem.localObject = item
-            
+
             return [dragItem]
         }
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) -> UIDragPreviewParameters? {
-        
+
         let previewParameters = UIDragPreviewParameters()
         if collectionView == collectionViewSource {
             previewParameters.visiblePath = UIBezierPath(rect: CGRect(x: 20, y: 20, width: 100, height: 100))
         } else {
             previewParameters.visiblePath = UIBezierPath(rect: CGRect(x: 20, y: 20, width: 80, height: 80))
         }
-         
+
         return previewParameters
     }
 }
@@ -564,25 +561,25 @@ extension DragDropViewController : UICollectionViewDragDelegate
 // MARK: - UICollectionViewDropDelegate Methods
 
 @available(iOS 13.0, *)
-extension DragDropViewController : UICollectionViewDropDelegate {
-    
+extension DragDropViewController: UICollectionViewDropDelegate {
+
     func collectionView(_ collectionView: UICollectionView, canHandle session: UIDropSession) -> Bool {
-        
-        return true //session.canLoadObjects(ofClass: NSString.self)
+
+        return true // session.canLoadObjects(ofClass: NSString.self)
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
-        
+
         if collectionView == collectionViewSource {
-            
+
             if collectionView.hasActiveDrag {
                 return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
             } else {
                 return UICollectionViewDropProposal(operation: .forbidden)
             }
-            
+
         } else {
-            
+
             if collectionView.hasActiveDrag {
                 return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
             } else {
@@ -590,51 +587,51 @@ extension DragDropViewController : UICollectionViewDropDelegate {
             }
         }
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
-        
+
         let destinationIndexPath: IndexPath
-        
+
         switch coordinator.proposal.operation {
-            
+
         case .move:
-            
+
             if let indexPath = coordinator.destinationIndexPath {
-                
+
                 destinationIndexPath = indexPath
-                
+
             } else {
-                
+
                 // Get last index path of table view.
                 let section = collectionView.numberOfSections - 1
                 let row = collectionView.numberOfItems(inSection: section)
-                
+
                 destinationIndexPath = IndexPath(row: row, section: section)
             }
             self.reorderItems(coordinator: coordinator, destinationIndexPath: destinationIndexPath, collectionView: collectionView)
-            
+
             break
-            
+
         case .copy:
-            
+
             // Get last index path of table view.
             let section = collectionView.numberOfSections - 1
             let row = collectionView.numberOfItems(inSection: section)
-            
+
             destinationIndexPath = IndexPath(row: row, section: section)
             self.copyItems(coordinator: coordinator, destinationIndexPath: destinationIndexPath, collectionView: collectionView)
-            
+
             break
-            
+
         default:
             return
         }
     }
-    
+
     func collectionView(_ collectionView: UICollectionView, dropSessionDidEnd session: UIDropSession) {
-        
+
         collectionViewDestination.reloadData()
-        
+
         // Save button
         if imagesDestination.count == 0 {
             save.isEnabled = false
@@ -643,4 +640,3 @@ extension DragDropViewController : UICollectionViewDropDelegate {
         }
     }
 }
-

+ 67 - 67
iOSClient/Security/NCEndToEndMetadata.swift

@@ -24,37 +24,37 @@
 import UIKit
 import NCCommunication
 
-class NCEndToEndMetadata : NSObject  {
+class NCEndToEndMetadata: NSObject {
 
     struct e2eMetadata: Codable {
-        
+
         struct metadataKeyCodable: Codable {
-            
+
             let metadataKeys: [String: String]
             let version: Int
         }
-        
+
         struct sharingCodable: Codable {
-            
+
             let recipient: [String: String]
         }
-        
+
         struct encryptedFileAttributes: Codable {
-            
+
             let key: String
             let filename: String
             let mimetype: String
             let version: Int
         }
-        
+
         struct filesCodable: Codable {
-            
+
             let initializationVector: String
             let authenticationTag: String?
             let metadataKey: Int                // Number of metadataKey
             let encrypted: String               // encryptedFileAttributes
         }
-        
+
         let files: [String: filesCodable]
         let metadata: metadataKeyCodable
         let sharing: sharingCodable?
@@ -64,137 +64,137 @@ class NCEndToEndMetadata : NSObject  {
         let instance = NCEndToEndMetadata()
         return instance
     }()
-    
+
     // --------------------------------------------------------------------------------------------
     // MARK: Encode / Decode JSON Metadata
     // --------------------------------------------------------------------------------------------
-    
+
     @objc func encoderMetadata(_ recordsE2eEncryption: [tableE2eEncryption], privateKey: String, serverUrl: String) -> String? {
-        
-        let jsonEncoder = JSONEncoder.init()
+
+        let jsonEncoder = JSONEncoder()
         var files: [String: e2eMetadata.filesCodable] = [:]
         var version = 1
         var metadataKeysDictionary: [String: String] = [:]
-        
+
         for recordE2eEncryption in recordsE2eEncryption {
-            
+
             // *** metadataKey ***
-            
+
             // Encode64 for Android compatibility
             let metadatakey = (recordE2eEncryption.metadataKey.data(using: .utf8)?.base64EncodedString())!
-            
+
             guard let metadataKeyEncryptedData = NCEndToEndEncryption.sharedManager().encryptAsymmetricString(metadatakey, publicKey: nil, privateKey: privateKey) else {
                 return nil
             }
-            
+
             let metadataKeyEncryptedBase64 = metadataKeyEncryptedData.base64EncodedString()
-            
+
             metadataKeysDictionary["\(recordE2eEncryption.metadataKeyIndex)"] = metadataKeyEncryptedBase64
-            
+
             // *** File ***
-            
+
             let encrypted = e2eMetadata.encryptedFileAttributes(key: recordE2eEncryption.key, filename: recordE2eEncryption.fileName, mimetype: recordE2eEncryption.mimeType, version: recordE2eEncryption.version)
-            
+
             do {
-                
+
                 // Create "encrypted"
                 let encryptedJsonData = try jsonEncoder.encode(encrypted)
                 let encryptedJsonString = String(data: encryptedJsonData, encoding: .utf8)
-                
+
                 guard let encryptedEncryptedJson = NCEndToEndEncryption.sharedManager().encryptEncryptedJson(encryptedJsonString, key: recordE2eEncryption.metadataKey) else {
                     print("Serious internal error in encoding metadata")
                     return nil
                 }
-                
+
                 let e2eMetadataFilesKey = e2eMetadata.filesCodable(initializationVector: recordE2eEncryption.initializationVector, authenticationTag: recordE2eEncryption.authenticationTag, metadataKey: 0, encrypted: encryptedEncryptedJson)
-                
+
                 files.updateValue(e2eMetadataFilesKey, forKey: recordE2eEncryption.fileNameIdentifier)
-                
+
             } catch let error {
                 print("Serious internal error in encoding metadata ("+error.localizedDescription+")")
                 return nil
             }
-            
+
             version = recordE2eEncryption.version
         }
 
         // Create Json metadataKeys
-        //e2eMetadataKey = e2eMetadata.metadataKeyCodable(metadataKeys: ["0":metadataKeyEncryptedBase64], version: version)
+        // e2eMetadataKey = e2eMetadata.metadataKeyCodable(metadataKeys: ["0":metadataKeyEncryptedBase64], version: version)
         let e2eMetadataKey = e2eMetadata.metadataKeyCodable(metadataKeys: metadataKeysDictionary, version: version)
-        
+
         // Create final Json e2emetadata
         let e2emetadata = e2eMetadata(files: files, metadata: e2eMetadataKey, sharing: nil)
-        
+
         do {
-            
+
             let jsonData = try jsonEncoder.encode(e2emetadata)
             let jsonString = String(data: jsonData, encoding: .utf8)
             print("JSON String : " + jsonString!)
-                        
+
             return jsonString
-            
+
         } catch let error {
             print("Serious internal error in encoding metadata ("+error.localizedDescription+")")
             return nil
         }
     }
-    
+
     @discardableResult
     @objc func decoderMetadata(_ e2eMetaDataJSON: String, privateKey: String, serverUrl: String, account: String, urlBase: String) -> Bool {
-        
-        let jsonDecoder = JSONDecoder.init()
+
+        let jsonDecoder = JSONDecoder()
         let data = e2eMetaDataJSON.data(using: .utf8)
-        //let dataQuickLook = (data as! NSData)
-                
+        // let dataQuickLook = (data as! NSData)
+
         do {
-            
+
             // *** metadataKey ***
-            
+
             let decode = try jsonDecoder.decode(e2eMetadata.self, from: data!)
-            
+
             let files = decode.files
             let metadata = decode.metadata
-            //let sharing = decode.sharing ---> V 2.0
+            // let sharing = decode.sharing ---> V 2.0
             var metadataKeysDictionary: [String: String] = [:]
-            
+
             for metadataKeyDictionaryEncrypted in metadata.metadataKeys {
-                
-                guard let metadataKeyEncryptedData : NSData = NSData(base64Encoded: metadataKeyDictionaryEncrypted.value, options: NSData.Base64DecodingOptions(rawValue: 0)) else {
+
+                guard let metadataKeyEncryptedData: NSData = NSData(base64Encoded: metadataKeyDictionaryEncrypted.value, options: NSData.Base64DecodingOptions(rawValue: 0)) else {
                     return false
                 }
-                
+
                 guard let metadataKeyBase64 = NCEndToEndEncryption.sharedManager().decryptAsymmetricData(metadataKeyEncryptedData as Data?, privateKey: privateKey) else {
                     return false
                 }
-                
+
                 // Initialize a `Data` from a Base-64 encoded String
                 let metadataKeyBase64Data = Data(base64Encoded: metadataKeyBase64, options: NSData.Base64DecodingOptions(rawValue: 0))!
                 let metadataKey = String(data: metadataKeyBase64Data, encoding: .utf8)
-                
+
                 metadataKeysDictionary[metadataKeyDictionaryEncrypted.key] = metadataKey
             }
-            
+
             // *** File ***
-            
+
             for file in files {
-                
+
                 let fileNameIdentifier = file.key
                 let filesCodable = file.value as e2eMetadata.filesCodable
-                
+
                 let encrypted = filesCodable.encrypted
                 let metadataKey = metadataKeysDictionary["\(filesCodable.metadataKey)"]
-                
+
                 guard let encryptedFileAttributesJson = NCEndToEndEncryption.sharedManager().decryptEncryptedJson(encrypted, key: metadataKey) else {
                     return false
                 }
-                
+
                 do {
                     let encryptedFileAttributes = try jsonDecoder.decode(e2eMetadata.encryptedFileAttributes.self, from: encryptedFileAttributesJson.data(using: .utf8)!)
                     if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND fileName == %@", account, fileNameIdentifier)) {
                         let metadata = tableMetadata.init(value: metadata)
-                    
+
                         let object = tableE2eEncryption()
-                    
+
                         object.account = account
                         object.authenticationTag = filesCodable.authenticationTag ?? ""
                         object.fileName = encryptedFileAttributes.filename
@@ -207,37 +207,37 @@ class NCEndToEndMetadata : NSObject  {
                         object.mimeType = encryptedFileAttributes.mimetype
                         object.serverUrl = serverUrl
                         object.version = encryptedFileAttributes.version
-                    
+
                         // If exists remove records
                         NCManageDatabase.shared.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNamePath == %@", object.account, object.fileNamePath))
                         NCManageDatabase.shared.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", object.account, object.fileNameIdentifier))
-                        
+
                         // Write file parameter for decrypted on DB
                         NCManageDatabase.shared.addE2eEncryption(object)
-                        
+
                         // Update metadata on tableMetadata
                         metadata.fileNameView = encryptedFileAttributes.filename
                         metadata.fileNameWithoutExt = (encryptedFileAttributes.filename as NSString).deletingPathExtension
-                        
+
                         let results = NCCommunicationCommon.shared.getInternalType(fileName: encryptedFileAttributes.filename, mimeType: metadata.contentType, directory: metadata.directory)
-                        
+
                         metadata.contentType = results.mimeType
                         metadata.iconName = results.iconName
                         metadata.classFile = results.classFile
-                                                
+
                         NCManageDatabase.shared.addMetadata(metadata)
                     }
-                    
+
                 } catch let error {
                     print("Serious internal error in decoding metadata ("+error.localizedDescription+")")
                 }
             }
-            
+
         } catch let error {
             print("Serious internal error in decoding metadata ("+error.localizedDescription+")")
             return false
         }
-        
+
         return true
     }
 }

+ 9 - 9
iOSClient/Security/NCViewCertificateDetails.swift

@@ -32,7 +32,7 @@ public extension NCViewCertificateDetailsDelegate {
     func viewCertificateDetailsDismiss(host: String) {}
 }
 
-class NCViewCertificateDetails: UIViewController  {
+class NCViewCertificateDetails: UIViewController {
 
     @IBOutlet weak var buttonCancel: UIBarButtonItem!
     @IBOutlet weak var scrollView: UIScrollView!
@@ -49,13 +49,13 @@ class NCViewCertificateDetails: UIViewController  {
 
         self.navigationItem.title = NSLocalizedString("_certificate_details_", comment: "")
         buttonCancel.title = NSLocalizedString("_close_", comment: "")
-        
+
         let certNamePathTXT = directoryCertificate + "/" + host + ".txt"
         if FileManager.default.fileExists(atPath: certNamePathTXT) {
             do {
                 let text = try String(contentsOfFile: certNamePathTXT, encoding: .utf8)
                 let font = UIFont.systemFont(ofSize: 13)
-                let attributes = [NSAttributedString.Key.font: font] as [NSAttributedString.Key : Any]
+                let attributes = [NSAttributedString.Key.font: font] as [NSAttributedString.Key: Any]
                 var contentRect = NSString(string: text).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: 0), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil)
                 contentRect = CGRect(x: contentRect.origin.x, y: contentRect.origin.y, width: ceil(contentRect.size.width), height: ceil(contentRect.size.height))
                 var contentWidth = contentRect.size.width
@@ -66,14 +66,14 @@ class NCViewCertificateDetails: UIViewController  {
                 if contentHeight < view.frame.size.height {
                     contentHeight = view.frame.size.width
                 }
-                
+
                 textView.frame = CGRect(x: 0, y: 0, width: contentWidth, height: contentHeight)
                 textView.font = font
                 textView.text = text
-                
+
                 scrollView.contentSize = contentRect.size
                 scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 50, right: 0)
-                
+
             } catch {
                 print("error")
             }
@@ -83,15 +83,15 @@ class NCViewCertificateDetails: UIViewController  {
             }
         }
     }
-    
+
     override func viewWillDisappear(_ animated: Bool) {
         super.viewWillDisappear(animated)
         
         self.delegate?.viewCertificateDetailsDismiss(host: host)
     }
-    
+
     // MARK: ACTION
-    
+
     @IBAction func actionCancel(_ sender: UIBarButtonItem) {
         self.dismiss(animated: true, completion: nil)
     }

Některé soubory nejsou zobrazeny, neboť je v těchto rozdílových datech změněno mnoho souborů