File: ShareTableViewDataSource.swift

package info (click to toggle)
nextcloud-desktop 4.0.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 40,404 kB
  • sloc: cpp: 118,401; objc: 752; python: 606; sh: 395; ansic: 391; ruby: 174; makefile: 44; javascript: 32; xml: 6
file content (245 lines) | stat: -rw-r--r-- 9,654 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
//
//  ShareTableViewDataSource.swift
//  FileProviderUIExt
//
//  SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
//  SPDX-License-Identifier: GPL-2.0-or-later
//

import AppKit
import FileProvider
import NextcloudKit
import NextcloudFileProviderKit
import NextcloudCapabilitiesKit
import OSLog

class ShareTableViewDataSource: NSObject, NSTableViewDataSource, NSTableViewDelegate {
    private let shareItemViewIdentifier = NSUserInterfaceItemIdentifier("ShareTableItemView")
    private let shareItemViewNib = NSNib(nibNamed: "ShareTableItemView", bundle: nil)
    private let reattemptInterval: TimeInterval = 3.0

    let kit = NextcloudKit.shared
    let logger: FileProviderLogger

    var uiDelegate: ShareViewDataSourceUIDelegate?
    var sharesTableView: NSTableView? {
        didSet {
            sharesTableView?.register(shareItemViewNib, forIdentifier: shareItemViewIdentifier)
            sharesTableView?.rowHeight = 42.0  // Height of view in ShareTableItemView XIB
            sharesTableView?.dataSource = self
            sharesTableView?.delegate = self
            sharesTableView?.reloadData()
        }
    }
    var capabilities: Capabilities?

    private(set) var itemURL: URL?
    private(set) var itemServerRelativePath: String?
    private(set) var shares: [NKShare] = [] {
        didSet { Task { @MainActor in sharesTableView?.reloadData() } }
    }
    private(set) var userAgent: String = "Nextcloud-macOS/FileProviderUIExt"
    private(set) var account: Account? {
        didSet {
            guard let account = account else { return }
            kit.appendSession(
                account: account.ncKitAccount,
                urlBase: account.serverUrl,
                user: account.username,
                userId: account.username,
                password: account.password,
                userAgent: userAgent,
                groupIdentifier: ""
            )
        }
    }

    init(log: any FileProviderLogging) {
        self.logger = FileProviderLogger(category: "ShareTableViewDataSource", log: log)
    }

    func loadItem(url: URL) {
        itemServerRelativePath = nil
        itemURL = url
        Task {
            await reload()
        }
    }

    func reattempt() {
        DispatchQueue.main.async {
            Timer.scheduledTimer(withTimeInterval: self.reattemptInterval, repeats: false) { _ in
                Task { await self.reload() }
            }
        }
    }

    func reload() async {
        guard let itemURL else {
            presentError(String(localized: "No item URL, cannot reload data!"))
            return
        }
        guard let itemIdentifier = await withCheckedContinuation({
            (continuation: CheckedContinuation<NSFileProviderItemIdentifier?, Never>) -> Void in
            NSFileProviderManager.getIdentifierForUserVisibleFile(
                at: itemURL
            ) { identifier, domainIdentifier, error in
                defer { continuation.resume(returning: identifier) }
                guard error == nil else {
                    self.presentError("No item with identifier: \(error.debugDescription)")
                    return
                }
            }
        }) else {
            presentError(String(localized: "Could not get identifier for item, no shares can be acquired."))
            return
        }

        do {
            let connection = try await serviceConnection(url: itemURL, interruptionHandler: {
                self.logger.error("Service connection interrupted")
            })
            if let acquiredUserAgent = await connection.userAgent() {
                userAgent = acquiredUserAgent as String
            }
            guard let serverPath = await connection.itemServerPath(identifier: itemIdentifier),
                  let credentials = await connection.credentials() as? Dictionary<String, String>,
                  let convertedAccount = Account(dictionary: credentials),
                  !convertedAccount.password.isEmpty
            else {
                presentError(String(localized: "Failed to get details from File Provider Extension. Retrying."))
                reattempt()
                return
            }
            let serverPathString = serverPath as String
            itemServerRelativePath = serverPathString
            account = convertedAccount
            await sharesTableView?.deselectAll(self)
            capabilities = await fetchCapabilities()
            guard capabilities != nil else { return }
            guard capabilities?.filesSharing?.apiEnabled == true else {
                presentError(String(localized: "Server does not support shares."))
                return
            }
            guard let account else {
                presentError(String(localized: "Account data is unavailable, cannot reload data!"))
                return
            }
            guard let itemMetadata = await fetchItemMetadata(
                itemRelativePath: serverPathString, account: account, kit: kit
            ) else {
                presentError(String(localized: "Unable to retrieve file metadata…"))
                return
            }
            guard itemMetadata.permissions.contains("R") == true else {
                presentError(String(localized: "This file cannot be shared."))
                return
            }
            shares = await fetch(
                itemIdentifier: itemIdentifier, itemRelativePath: serverPathString
            )
            shares.append(Self.generateInternalShare(for: itemMetadata))
        } catch let error {
            presentError(String(format: String(localized: "Could not reload data: %@, will try again."), error.localizedDescription))
            reattempt()
        }
    }

    private func fetch(
        itemIdentifier: NSFileProviderItemIdentifier, itemRelativePath: String
    ) async -> [NKShare] {
        Task { @MainActor in uiDelegate?.fetchStarted() }
        defer { Task { @MainActor in uiDelegate?.fetchFinished() } }

        let rawIdentifier = itemIdentifier.rawValue
        logger.info("Fetching shares for item \(rawIdentifier)")

        guard let account else {
            self.presentError(String(localized: "NextcloudKit instance or account is unavailable, cannot fetch shares!"))
            return []
        }

        let parameter = NKShareParameter(path: itemRelativePath)

        return await withCheckedContinuation { continuation in
            kit.readShares(
                parameters: parameter, account: account.ncKitAccount
            ) { account, shares, data, error in
                let shareCount = shares?.count ?? 0
                self.logger.info("Received \(shareCount) shares")
                defer { continuation.resume(returning: shares ?? []) }
                guard error == .success else {
                    self.presentError(String(localized: "Error fetching shares: \(error.errorDescription)"))
                    return
                }
            }
        }
    }

    private static func generateInternalShare(for file: NKFile) -> NKShare {
        let internalShare = NKShare()
        internalShare.shareType = NKShare.ShareType.internalLink.rawValue
        internalShare.url = file.urlBase +  "/index.php/f/" + file.fileId
        internalShare.account = file.account
        internalShare.displaynameOwner = file.ownerDisplayName
        internalShare.displaynameFileOwner = file.ownerDisplayName
        internalShare.path = file.path
        return internalShare
    }

    private func fetchCapabilities() async -> Capabilities? {
        guard let account else {
            self.presentError(String(localized: "Could not fetch capabilities as account is invalid."))
            return nil
        }

        return await withCheckedContinuation { continuation in
            kit.getCapabilities(account: account.ncKitAccount) { account, _, data, error in
                guard error == .success, let capabilitiesJson = data?.data else {
                    self.presentError(String(localized: "Error getting server caps: \(error.errorDescription)"))
                    continuation.resume(returning: nil)
                    return
                }

                self.logger.info("Successfully retrieved server share capabilities")
                continuation.resume(returning: Capabilities(data: capabilitiesJson))
            }
        }
    }

    private func presentError(_ errorString: String) {
        logger.error("\(errorString)")
        Task { @MainActor in self.uiDelegate?.showError(errorString) }
    }

    // MARK: - NSTableViewDataSource protocol methods

    @objc func numberOfRows(in tableView: NSTableView) -> Int {
        shares.count
    }

    // MARK: - NSTableViewDelegate protocol methods

    @objc func tableView(
        _ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int
    ) -> NSView? {
        let share = shares[row]
        guard let view = tableView.makeView(
            withIdentifier: shareItemViewIdentifier, owner: self
        ) as? ShareTableItemView else {
            logger.error("Acquired item view from table is not a share item view!")
            return nil
        }
        view.share = share
        return view
    }

    @objc func tableViewSelectionDidChange(_ notification: Notification) {
        guard let selectedRow = sharesTableView?.selectedRow, selectedRow >= 0 else {
            Task { @MainActor in uiDelegate?.hideOptions(self) }
            return
        }
        let share = shares[selectedRow]
        Task { @MainActor in uiDelegate?.showOptions(share: share) }
    }
}