Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions Sources/NextcloudKit/NKCommon.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ public protocol NextcloudKitDelegate: AnyObject, Sendable {

func downloadComplete(fileName: String, serverUrl: String, etag: String?, date: Date?, dateLastModified: Date?, length: Int64, task: URLSessionTask, error: NKError)
func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: Date?, size: Int64, task: URLSessionTask, error: NKError)

func request<Value>(_ request: DataRequest, didParseResponse response: AFDataResponse<Value>)
}

public struct NKCommon: Sendable {
Expand Down
100 changes: 33 additions & 67 deletions Sources/NextcloudKit/NKMonitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
self.nkCommonInstance.writeLog("Network request started: \(request)")
if self.nkCommonInstance.levelLog > 1 {
let allHeaders = request.request.flatMap { $0.allHTTPHeaderFields.map { $0.description } } ?? "None"
let body = request.request.flatMap { $0.httpBody.map { String(decoding: $0, as: UTF8.self) } } ?? "None"

Check warning on line 20 in Sources/NextcloudKit/NKMonitor.swift

View workflow job for this annotation

GitHub Actions / Lint

Optional Data -> String Conversion Violation: Prefer failable `String(bytes:encoding:)` initializer when converting `Data` to `String` (optional_data_string_conversion)

self.nkCommonInstance.writeLog("Network request headers: \(allHeaders)")
self.nkCommonInstance.writeLog("Network request body: \(body)")
Expand All @@ -26,33 +26,42 @@
}

func request<Value>(_ request: DataRequest, didParseResponse response: AFDataResponse<Value>) {
self.nkCommonInstance.delegate?.request(request, didParseResponse: response)
let groupDefaults = UserDefaults(suiteName: NextcloudKit.shared.nkCommonInstance.groupIdentifier)

//
// Error 401, append the account in groupDefaults Unauthorized array
//
if let statusCode = response.response?.statusCode {
if statusCode == 401,
let headerValue = request.request?.allHTTPHeaderFields?["X-NC-CheckUnauthorized"],
headerValue.lowercased() == "true",
let account = request.request?.allHTTPHeaderFields?["X-NC-Account"] as? String,
let session = nkCommonInstance.getSession(account: account) {
let serverUrlFileName = session.urlBase + "/remote.php/dav/files/" + session.userId
self.readFile(serverUrlFileName: serverUrlFileName, account: account) { account, error in
/*
var unauthorizedArray = groupDefaults?.array(forKey: "Unauthorized") as? [String] ?? []
if !unauthorizedArray.contains(account) {
unauthorizedArray.append(account)
groupDefaults?.set(unauthorizedArray, forKey: "Unauthorized")

self.nkCommonInstance.writeLog("Unauthorized set for account: \(account)")
}
*/
}
} else if statusCode == 503 {
print("503 Service Unavailable")
}

//
// Error 401, append the account in groupDefaults Unauthorized array
//

if statusCode == 401,
let headerValue = request.request?.allHTTPHeaderFields?["X-NC-CheckUnauthorized"],
headerValue.lowercased() == "true",
let account = request.request?.allHTTPHeaderFields?["X-NC-Account"] as? String {

var unauthorizedArray = groupDefaults?.array(forKey: "Unauthorized") as? [String] ?? []
if !unauthorizedArray.contains(account) {
unauthorizedArray.append(account)
groupDefaults?.set(unauthorizedArray, forKey: "Unauthorized")

self.nkCommonInstance.writeLog("Unauthorized set for account: \(account)")
}


Check warning on line 50 in Sources/NextcloudKit/NKMonitor.swift

View workflow job for this annotation

GitHub Actions / Lint

Vertical Whitespace Violation: Limit vertical whitespace to a single empty line; currently 2 (vertical_whitespace)
//
// Error 503, append the account in groupDefaults Unavailable array
//
} else if statusCode == 503,
let account = request.request?.allHTTPHeaderFields?["X-NC-Account"] as? String {

var unauthorizedArray = groupDefaults?.array(forKey: "Unavailable") as? [String] ?? []
if !unauthorizedArray.contains(account) {
unauthorizedArray.append(account)
groupDefaults?.set(unauthorizedArray, forKey: "Unavailable")

self.nkCommonInstance.writeLog("Unavailable set for account: \(account)")
}
}
}

//
Expand All @@ -77,47 +86,4 @@
}
}
}

func readFile(serverUrlFileName: String,
account: String,
options: NKRequestOptions = NKRequestOptions(),
taskHandler: @escaping (_ task: URLSessionTask) -> Void = { _ in },
completion: @escaping (_ account: String, _ error: NKError) -> Void) {
///
options.contentType = "application/xml"
///
guard let nkSession = nkCommonInstance.getSession(account: account),
let url = serverUrlFileName.encodedToUrl,
var headers = nkCommonInstance.getStandardHeaders(account: account, checkUnauthorized: true, options: options) else {
return options.queue.async { completion(account, .urlError) }
}

let method = HTTPMethod(rawValue: "PROPFIND")
headers.update(name: "Depth", value: "0")
var urlRequest: URLRequest

do {
try urlRequest = URLRequest(url: url, method: method, headers: headers)
urlRequest.httpBody = NKDataFileXML(nkCommonInstance: self.nkCommonInstance).getRequestBodyFile(createProperties: options.createProperties, removeProperties: options.removeProperties).data(using: .utf8)

} catch {
return options.queue.async { completion(account, NKError(error: error)) }
}

nkSession.sessionData.request(urlRequest, interceptor: NKInterceptor()).validate(statusCode: 200..<300).onURLSessionTaskCreation { task in
task.taskDescription = options.taskDescription
taskHandler(task)
}.responseData(queue: self.nkCommonInstance.backgroundQueue) { response in
if self.nkCommonInstance.levelLog > 0 {
debugPrint(response)
}
switch response.result {
case .failure(let error):
let error = NKError(error: error, afResponse: response, responseData: response.data)
options.queue.async { completion(account, error) }
case .success:
options.queue.async { completion(account, .success) }
}
}
}
}
Loading