Parcourir la source

Fix share detail create & update shares using `TableShareable`

Signed-off-by: Henrik Storch <henrik.storch@nextcloud.com>
Henrik Storch il y a 3 ans
Parent
commit
c82e0236b9

+ 8 - 0
iOSClient/Extensions/UIAlertController+Extension.swift

@@ -80,4 +80,12 @@ extension UIAlertController {
         alertController.addAction(okAction)
         return alertController
     }
+
+    static func sharePassword(completion: @escaping (String?) -> Void) -> UIAlertController {
+        return .withTextField(titleKey: "_enforce_password_protection_", textFieldConfiguration: { textField in
+            textField.isSecureTextEntry = true
+            textField.placeholder = NSLocalizedString("_password_", comment: "")
+        }, completion: completion)
+
+    }
 }

+ 11 - 0
iOSClient/Menu/NCShare+Menu.swift

@@ -13,6 +13,17 @@ extension NCShare {
 
         var actions = [NCMenuAction]()
 
+        if share.shareType == 3 {
+            actions.append(
+                NCMenuAction(
+                    title: NSLocalizedString("_share_add_link_", comment: ""),
+                    icon: NCUtility.shared.loadImage(named: "rename").imageColor(NCBrandColor.shared.brandElement),
+                    action: { _ in
+                        self.makeNewLinkShare()
+                    }
+                )
+            )
+        }
 //        if !folder {
 //            actions.append(
 //                NCMenuAction(

+ 20 - 25
iOSClient/Share/Advanced/NCShareAdvancePermission.swift

@@ -12,8 +12,9 @@ import SVGKit
 import CloudKit
 
 protocol NCShareDetail {
-    var share: tableShare! { get }
+    var share: TableShareable! { get }
 }
+
 extension NCShareDetail where Self: UIViewController {
     func setNavigationTitle() {
         title = NSLocalizedString("_share_", comment: "") + "  – "
@@ -30,19 +31,13 @@ class NCShareAdvancePermission: UITableViewController, NCShareAdvanceFotterDeleg
         defer { navigationController?.popViewController(animated: true) }
         guard shouldSave else { return }
         if NCManageDatabase.shared.getTableShare(account: share.account, idShare: share.idShare) == nil {
-            networking?.createShare(shareWith: share.shareWith, shareType: share.shareType, password: share.password, metadata: metadata)
+            networking?.createShare(option: share, metadata: metadata)
         } else {
-            var expirationDate: String?
-            if let date = share.expirationDate {
-                let dateFormatter = DateFormatter()
-                dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
-                expirationDate = dateFormatter.string(from: date as Date)
-            }
-            networking?.updateShare(idShare: share.idShare, password: share.password, permissions: share.permissions, note: share.note, label: share.label, expirationDate: expirationDate, hideDownload: share.hideDownload)
+            networking?.updateShare(option: share)
         }
     }
 
-    var share: tableShare!
+    var share: TableShareable!
     var metadata: tableMetadata!
     var shareConfig: ShareConfig!
     var networking: NCShareNetworking?
@@ -160,21 +155,21 @@ class NCShareAdvancePermission: UITableViewController, NCShareAdvanceFotterDeleg
 
 protocol ShareCellConfig {
     var title: String { get }
-    func getCell(for share: tableShare) -> UITableViewCell
-    func didSelect(for share: tableShare)
+    func getCell(for share: TableShareable) -> UITableViewCell
+    func didSelect(for share: TableShareable)
 }
 
 protocol ToggleCellConfig: ShareCellConfig {
-    func isOn(for share: tableShare) -> Bool
-    func didChange(_ share: tableShare, to newValue: Bool)
+    func isOn(for share: TableShareable) -> Bool
+    func didChange(_ share: TableShareable, to newValue: Bool)
 }
 
 extension ToggleCellConfig {
-    func getCell(for share: tableShare) -> UITableViewCell {
+    func getCell(for share: TableShareable) -> UITableViewCell {
         return ToggleCell(isOn: isOn(for: share))
     }
 
-    func didSelect(for share: tableShare) {
+    func didSelect(for share: TableShareable) {
         didChange(share, to: !isOn(for: share))
     }
 }
@@ -194,11 +189,11 @@ enum UserPermission: CaseIterable, Permission {
         }
     }
 
-    func didChange(_ share: tableShare, to newValue: Bool) {
+    func didChange(_ share: TableShareable, to newValue: Bool) {
         share.permissions ^= permissionBitFlag
     }
 
-    func isOn(for share: tableShare) -> Bool {
+    func isOn(for share: TableShareable) -> Bool {
         return (share.permissions & permissionBitFlag) != 0
     }
 
@@ -217,7 +212,7 @@ enum UserPermission: CaseIterable, Permission {
 }
 
 enum LinkPermission: Permission {
-    func didChange(_ share: tableShare, to newValue: Bool) {
+    func didChange(_ share: TableShareable, to newValue: Bool) {
         guard self != .allowEdit else {
             // file
             share.permissions = CCUtility.getPermissionsValue(
@@ -254,7 +249,7 @@ enum LinkPermission: Permission {
         }
     }
 
-    func isOn(for share: tableShare) -> Bool {
+    func isOn(for share: TableShareable) -> Bool {
         switch self {
         case .allowEdit: return CCUtility.isAnyPermission(toEdit: share.permissions)
         case .viewOnly: return !CCUtility.isAnyPermission(toEdit: share.permissions) && share.permissions != NCGlobal.shared.permissionCreateShare
@@ -278,7 +273,7 @@ enum LinkPermission: Permission {
 }
 
 enum Advanced: CaseIterable, ShareCellConfig {
-    func didSelect(for share: tableShare) {
+    func didSelect(for share: TableShareable) {
         switch self {
         case .hideDownload: share.hideDownload.toggle()
         case .expirationDate: return
@@ -288,7 +283,7 @@ enum Advanced: CaseIterable, ShareCellConfig {
         }
     }
 
-    func getCell(for share: tableShare) -> UITableViewCell {
+    func getCell(for share: TableShareable) -> UITableViewCell {
         switch self {
         case .hideDownload:
             return ToggleCell(isOn: share.hideDownload)
@@ -326,9 +321,9 @@ struct ShareConfig {
 
     let permissions: [Permission]
     let advanced: [Advanced]
-    let share: tableShare
+    let share: TableShareable
 
-    init(isDirectory: Bool, share: tableShare) {
+    init(isDirectory: Bool, share: TableShareable) {
         self.share = share
         let type: Permission.Type = share.shareType == 3 ? LinkPermission.self : UserPermission.self
         self.permissions = isDirectory ? type.forDirectory : type.forFile
@@ -389,7 +384,7 @@ open class DatePickerTableViewCell: UITableViewCell {
 
     var onReload: (() -> Void)?
 
-    init(share: tableShare) {
+    init(share: TableShareable) {
         super.init(style: .value1, reuseIdentifier: "shareExpDate")
         picker.datePickerMode = .date
         picker.minimumDate = Date()

+ 1 - 1
iOSClient/Share/Advanced/NCShareAdvancePermissionFooter.swift

@@ -17,7 +17,7 @@ class NCShareAdvancePermissionFooter: UIView {
     @IBOutlet weak var buttonNext: UIButton!
     weak var delegate: NCShareAdvanceFotterDelegate?
     
-    func setupUI(with share: tableShare, delegate: NCShareAdvanceFotterDelegate?) {
+    func setupUI(with share: TableShareable, delegate: NCShareAdvanceFotterDelegate?) {
         self.delegate = delegate
 
         backgroundColor = .clear

+ 2 - 1
iOSClient/Share/Advanced/NCShareNewUserAddComment.swift

@@ -12,6 +12,7 @@ import NCCommunication
 import SVGKit
 
 class NCShareNewUserAddComment: UIViewController, UITextViewDelegate, NCShareDetail {
+
     @IBOutlet weak var headerContainerView: UIView!
     @IBOutlet weak var sharingLabel: UILabel!
     @IBOutlet weak var sharingNote: UILabel!
@@ -19,7 +20,7 @@ class NCShareNewUserAddComment: UIViewController, UITextViewDelegate, NCShareDet
 
     var onDismiss: (() -> Void)?
 
-    public var share: tableShare!
+    public var share: TableShareable!
     public var metadata: tableMetadata!
 
     override func viewDidLoad() {

+ 1 - 19
iOSClient/Share/NCShare+NCCellDelegate.swift

@@ -34,28 +34,10 @@ extension NCShare: NCShareLinkCellDelegate, NCShareUserCellDelegate {
 
     func tapMenu(with tableShare: tableShare?, sender: Any) {
         guard let metadata = self.metadata else { return }
-        let isFilesSharingPublicPasswordEnforced = NCManageDatabase.shared.getCapabilitiesServerBool(account: metadata.account, elements: NCElementsJSON.shared.capabilitiesFileSharingPubPasswdEnforced, exists: false)
-
         if let tableShare = tableShare {
-            // open share menu
             self.toggleShareMenu(for: tableShare)
-        } else if isFilesSharingPublicPasswordEnforced {
-            // create share with pw
-            let alertController = UIAlertController(title: NSLocalizedString("_enforce_password_protection_", comment: ""), message: "", preferredStyle: .alert)
-            alertController.addTextField { textField in
-                textField.isSecureTextEntry = true
-            }
-            alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .default) { _ in })
-            let okAction = UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { _ in
-                let password = alertController.textFields?.first?.text
-                self.networking?.createShareLink(password: password ?? "")
-            }
-
-            alertController.addAction(okAction)
-            self.present(alertController, animated: true, completion: nil)
         } else {
-            // create sahre without pw
-            networking?.createShareLink(password: "")
+            self.makeNewLinkShare()
         }
     }
 

+ 85 - 18
iOSClient/Share/NCShare.swift

@@ -94,6 +94,19 @@ class NCShare: UIViewController, UIGestureRecognizerDelegate, NCShareNetworkingD
         changeTheming()
     }
 
+    func makeNewLinkShare() {
+        guard
+            let advancePermission = UIStoryboard(name: "NCShare", bundle: nil).instantiateViewController(withIdentifier: "NCShareAdvancePermission") as? NCShareAdvancePermission,
+            let navigationController = self.navigationController,
+            let metadata = self.metadata else { return }
+        self.checkEnforcedPassword { password in
+            advancePermission.networking = self.networking
+            advancePermission.share = TableShareOptions.shareLink(metadata: metadata, password: password)
+            advancePermission.metadata = self.metadata
+            navigationController.pushViewController(advancePermission, animated: true)
+        }
+    }
+
     // Shared with you by ...
     func checkSharedWithYou() {
         guard let appDelegate = self.appDelegate, let metadata = metadata, !metadata.ownerId.isEmpty, metadata.ownerId != appDelegate.userId else { return }
@@ -157,7 +170,6 @@ class NCShare: UIViewController, UIGestureRecognizerDelegate, NCShareNetworkingD
     }
 
     @objc func changePermissions(_ notification: NSNotification) {
-
         if let userInfo = notification.userInfo as NSDictionary? {
             if let idShare = userInfo["idShare"] as? Int, let permissions = userInfo["permissions"] as? Int, let hideDownload = userInfo["hideDownload"] as? Bool {
                 networking?.updateShare(idShare: idShare, password: nil, permissions: permissions, note: nil, label: nil, expirationDate: nil, hideDownload: hideDownload)
@@ -186,19 +198,7 @@ class NCShare: UIViewController, UIGestureRecognizerDelegate, NCShareNetworkingD
               NCManageDatabase.shared.getCapabilitiesServerBool(account: metadata.account, elements: NCElementsJSON.shared.capabilitiesFileSharingPubPasswdEnforced, exists: false)
         else { return callback(nil) }
 
-        let alertController = UIAlertController(title: NSLocalizedString("_enforce_password_protection_", comment: ""), message: "", preferredStyle: .alert)
-        alertController.addTextField { textField in
-            textField.isSecureTextEntry = true
-        }
-        alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .default) { _ in })
-        let okAction = UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { _ in
-            let password = alertController.textFields?.first?.text
-            callback(password)
-        }
-
-        alertController.addAction(okAction)
-
-        self.present(alertController, animated: true, completion: nil)
+        self.present(UIAlertController.sharePassword(completion: callback), animated: true)
     }
 
     func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
@@ -259,10 +259,15 @@ class NCShare: UIViewController, UIGestureRecognizerDelegate, NCShareNetworkingD
 
         dropDown.selectionAction = { index, _ in
             let sharee = sharees[index]
-            self.checkEnforcedPassword { password in
-                guard let metadata = self.metadata else { return }
-                self.networking?.createShare(shareWith: sharee.shareWith, shareType: sharee.shareType, password: password, metadata: metadata)
-            }
+            guard
+                let advancePermission = UIStoryboard(name: "NCShare", bundle: nil).instantiateViewController(withIdentifier: "NCShareAdvancePermission") as? NCShareAdvancePermission,
+                let navigationController = self.navigationController,
+                let metadata = self.metadata else { return }
+            let shareOptions = TableShareOptions(sharee: sharee, metadata: metadata)
+            advancePermission.share = shareOptions
+            advancePermission.networking = self.networking
+            advancePermission.metadata = metadata
+            navigationController.pushViewController(advancePermission, animated: true)
         }
 
         dropDown.show()
@@ -335,3 +340,65 @@ extension NCShare: UITableViewDataSource {
         return UITableViewCell()
     }
 }
+
+extension tableShare: TableShareable { }
+protocol TableShareable: AnyObject {
+    var shareType: Int { get set }
+    var permissions: Int { get set }
+
+    var account: String { get }
+
+    var idShare: Int { get set }
+    var shareWith: String { get set }
+//    var publicUpload: Bool? = false
+    var hideDownload: Bool { get set }
+    var password: String { get set }
+    var label: String { get set }
+    var note: String { get set }
+    var expirationDate: NSDate? { get set }
+    var shareWithDisplayname: String { get set }
+}
+
+extension TableShareable {
+    var expDateString: String? {
+        guard let date = expirationDate else { return nil }
+        let dateFormatter = DateFormatter()
+        dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
+        return dateFormatter.string(from: date as Date)
+    }
+}
+
+class TableShareOptions: TableShareable {
+    var shareType: Int
+    var permissions: Int
+
+    let account: String
+
+    var idShare: Int = 0
+    var shareWith: String = ""
+//    var publicUpload: Bool? = false
+    var hideDownload: Bool = false
+    var password: String = ""
+    var label: String = ""
+    var note: String = ""
+    var expirationDate: NSDate?
+    var shareWithDisplayname: String = ""
+
+    private init(shareType: Int, metadata: tableMetadata, password: String? = nil) {
+        self.permissions = NCManageDatabase.shared.getCapabilitiesServerInt(account: metadata.account, elements: ["ocs", "data", "capabilities", "files_sharing", "default_permissions"]) & metadata.sharePermissionsCollaborationServices
+        self.shareType = shareType
+        self.account = metadata.account
+        if let password = password {
+            self.password = password
+        }
+    }
+
+    convenience init(sharee: NCCommunicationSharee, metadata: tableMetadata) {
+        self.init(shareType: sharee.shareType, metadata: metadata)
+        self.shareWith = sharee.shareWith
+    }
+
+    static func shareLink(metadata: tableMetadata, password: String?) -> TableShareOptions {
+        return TableShareOptions(shareType: 3, metadata: metadata, password: password)
+    }
+}

+ 8 - 8
iOSClient/Share/NCShareLinkCell.xib

@@ -1,9 +1,9 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="19455" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
+<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="19529" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
     <device id="retina4_7" orientation="portrait" appearance="light"/>
     <dependencies>
         <deployment identifier="iOS"/>
-        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="19454"/>
+        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="19519"/>
         <capability name="System colors in document resources" minToolsVersion="11.0"/>
         <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
     </dependencies>
@@ -25,7 +25,7 @@
                         </constraints>
                     </imageView>
                     <stackView opaque="NO" contentMode="scaleToFill" spacing="30" translatesAutoresizingMaskIntoConstraints="NO" id="OQv-Vf-bvD">
-                        <rect key="frame" x="500" y="35" width="70" height="20"/>
+                        <rect key="frame" x="520" y="35" width="70" height="20"/>
                         <subviews>
                             <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="xaz-vY-Jzu" userLabel="ButtonCopy">
                                 <rect key="frame" x="0.0" y="0.0" width="20" height="20"/>
@@ -52,16 +52,16 @@
                         </subviews>
                     </stackView>
                     <stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="4" translatesAutoresizingMaskIntoConstraints="NO" id="Wxr-1B-Czy">
-                        <rect key="frame" x="53" y="12" width="432" height="66"/>
+                        <rect key="frame" x="53" y="12" width="452" height="66"/>
                         <subviews>
                             <label opaque="NO" userInteractionEnabled="NO" tag="101" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Share link" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="otH-mT-7Z4" userLabel="labelTitle">
-                                <rect key="frame" x="0.0" y="0.0" width="432" height="22"/>
+                                <rect key="frame" x="0.0" y="0.0" width="452" height="22"/>
                                 <fontDescription key="fontDescription" type="system" pointSize="15"/>
                                 <color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                 <nil key="highlightedColor"/>
                             </label>
                             <label opaque="NO" userInteractionEnabled="NO" contentMode="left" verticalCompressionResistancePriority="245" textAlignment="natural" lineBreakMode="tailTruncation" numberOfLines="2" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="WJj-9P-3bn">
-                                <rect key="frame" x="0.0" y="26" width="432" height="40"/>
+                                <rect key="frame" x="0.0" y="26" width="452" height="40"/>
                                 <constraints>
                                     <constraint firstAttribute="height" constant="40" id="Eo4-Rq-ETK"/>
                                 </constraints>
@@ -78,7 +78,7 @@
                     <constraint firstItem="OQv-Vf-bvD" firstAttribute="leading" secondItem="Wxr-1B-Czy" secondAttribute="trailing" constant="15" id="8QW-n0-4lO"/>
                     <constraint firstItem="qDs-UG-Mn7" firstAttribute="leading" secondItem="3Oe-gU-3Nk" secondAttribute="leading" constant="5" id="KOm-wo-CBa"/>
                     <constraint firstAttribute="bottom" secondItem="Wxr-1B-Czy" secondAttribute="bottom" constant="12" id="MM0-9i-BpF"/>
-                    <constraint firstAttribute="trailing" secondItem="OQv-Vf-bvD" secondAttribute="trailing" constant="30" id="W3b-ww-vbQ"/>
+                    <constraint firstAttribute="trailing" secondItem="OQv-Vf-bvD" secondAttribute="trailing" constant="10" id="W3b-ww-vbQ"/>
                     <constraint firstItem="qDs-UG-Mn7" firstAttribute="centerY" secondItem="3Oe-gU-3Nk" secondAttribute="centerY" id="ZrD-Aw-xkx"/>
                     <constraint firstItem="OQv-Vf-bvD" firstAttribute="centerY" secondItem="3Oe-gU-3Nk" secondAttribute="centerY" id="eLc-gk-xAr"/>
                     <constraint firstItem="Wxr-1B-Czy" firstAttribute="leading" secondItem="qDs-UG-Mn7" secondAttribute="trailing" constant="8" id="nXI-b3-EJM"/>
@@ -97,7 +97,7 @@
         </tableViewCell>
     </objects>
     <resources>
-        <image name="circle" width="300" height="300"/>
+        <image name="circle" width="210" height="156"/>
         <image name="shareCopy" width="329" height="329"/>
         <image name="shareMenu" width="329" height="329"/>
         <systemColor name="secondaryLabelColor">

+ 6 - 9
iOSClient/Share/NCShareNetworking.swift

@@ -78,15 +78,12 @@ class NCShareNetworking: NSObject {
         }
     }
     
-    func createShare(shareWith: String, shareType: Int, password: String?, metadata: tableMetadata) {
+    func createShare(option: TableShareable, metadata: tableMetadata) {
         NCUtility.shared.startActivityIndicator(backgroundView: view, blurEffect: false)
         let filenamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: urlBase, account: metadata.account)!
-        var permission: Int = NCManageDatabase.shared.getCapabilitiesServerInt(account: metadata.account, elements: ["ocs", "data", "capabilities", "files_sharing", "default_permissions"])
-        if permission <= 0 {
-            permission = metadata.directory ? NCGlobal.shared.permissionMaxFolderShare : NCGlobal.shared.permissionMaxFileShare
-        }
+        let permission = max(1, metadata.sharePermissionsCollaborationServices & option.permissions)
 
-        NCCommunication.shared.createShare(path: filenamePath, shareType: shareType, shareWith: shareWith, password: password, permissions: permission) { (account, share, errorCode, errorDescription) in
+        NCCommunication.shared.createShare(path: filenamePath, shareType: option.shareType, shareWith: option.shareWith, password: option.password, permissions: permission) { (account, share, errorCode, errorDescription) in
             NCUtility.shared.stopActivityIndicator()
             if errorCode == 0 && share != nil {
                 NCManageDatabase.shared.addShare(urlBase: self.urlBase, account: self.metadata.account, shares: [share!])
@@ -111,9 +108,9 @@ class NCShareNetworking: NSObject {
         }
     }
 
-    func updateShare(idShare: Int, password: String?, permissions: Int, note: String?, label: String?, expirationDate: String?, hideDownload: Bool) {
+    func updateShare(option: TableShareable) {
         NCUtility.shared.startActivityIndicator(backgroundView: view, blurEffect: false)
-        NCCommunication.shared.updateShare(idShare: idShare, password: password, expireDate: expirationDate, permissions: permissions, note: note, label: label, hideDownload: hideDownload) { account, share, errorCode, errorDescription in
+        NCCommunication.shared.updateShare(idShare: option.idShare, password: option.password, expireDate: option.expDateString, permissions: option.permissions, note: option.note, label: option.label, hideDownload: option.hideDownload) { account, share, errorCode, errorDescription in
             NCUtility.shared.stopActivityIndicator()
             if errorCode == 0 && share != nil {
                 NCManageDatabase.shared.addShare(urlBase: self.urlBase, account: self.metadata.account, shares: [share!])
@@ -121,7 +118,7 @@ class NCShareNetworking: NSObject {
                 self.delegate?.readShareCompleted()
             } else {
                 NCContentPresenter.shared.messageNotification("_share_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError)
-                self.delegate?.updateShareWithError(idShare: idShare)
+                self.delegate?.updateShareWithError(idShare: option.idShare)
             }
         }
     }