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
14 changes: 10 additions & 4 deletions Sources/NextcloudKit/NKCommon.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,12 @@ public struct NKCommon: Sendable {

public let notificationCenterChunkedFileStop = NSNotification.Name(rawValue: "NextcloudKit.chunkedFile.stop")

public let headerAccount = "X-NC-Account"
public let headerCheckInterceptor = "X-NC-CheckInterceptor"
public let groupDefaultsUnauthorized = "Unauthorized"
public let groupDefaultsUnavailable = "Unavailable"
public let groupDefaultsToS = "ToS"

public enum TypeReachability: Int {
case unknown = 0
case notReachable = 1
Expand Down Expand Up @@ -444,7 +450,7 @@ public struct NKCommon: Sendable {
return session
}

public func getStandardHeaders(account: String, checkUnauthorized: Bool? = nil, options: NKRequestOptions? = nil) -> HTTPHeaders? {
public func getStandardHeaders(account: String, options: NKRequestOptions? = nil) -> HTTPHeaders? {
guard let session = nksessions.filter({ $0.account == account }).first else { return nil}
var headers: HTTPHeaders = []

Expand All @@ -465,9 +471,9 @@ public struct NKCommon: Sendable {
for (key, value) in options?.customHeader ?? [:] {
headers.update(name: key, value: value)
}
headers.update(name: "X-NC-Account", value: account)
if let checkUnauthorized {
headers.update(name: "X-NC-CheckUnauthorized", value: checkUnauthorized.description)
headers.update(name: headerAccount, value: account)
if let checkInterceptor = options?.checkInterceptor {
headers.update(name: headerCheckInterceptor, value: checkInterceptor.description)
}
// Paginate
if let options {
Expand Down
3 changes: 3 additions & 0 deletions Sources/NextcloudKit/NKError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@
public static let xmlError = NKError(errorCode: NSURLErrorBadServerResponse, errorDescription: NSLocalizedString("_error_decode_xml_", value: "Invalid response, error decoding XML", comment: ""))
public static let invalidDate = NKError(errorCode: NSURLErrorBadServerResponse, errorDescription: NSLocalizedString("_invalid_date_format_", value: "Invalid date format", comment: ""))
public static let invalidData = NKError(errorCode: NSURLErrorCannotDecodeContentData, errorDescription: NSLocalizedString("_invalid_data_format_", value: "Invalid data format", comment: ""))
public static let unauthorizedError = NKError(errorCode: 401, errorDescription: NSLocalizedString("_unauthorized_", value: "Unauthorized", comment: ""))
public static let forbiddenError = NKError(errorCode: 403, errorDescription: NSLocalizedString("_forbidden_", value: "Forbidden", comment: ""))

public static let success = NKError(errorCode: 0, errorDescription: "")

public static func getErrorDescription(for code: Int) -> String? {
Expand Down Expand Up @@ -222,7 +225,7 @@

public static func == (lhs: NKError, rhs: NKError?) -> Bool {
if let rhs {
return lhs == rhs;

Check warning on line 228 in Sources/NextcloudKit/NKError.swift

View workflow job for this annotation

GitHub Actions / Lint

Trailing Semicolon Violation: Lines should not have trailing semicolons (trailing_semicolon)
}
return false
}
Expand Down
34 changes: 25 additions & 9 deletions Sources/NextcloudKit/NKInterceptor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,32 @@ final class NKInterceptor: RequestInterceptor, Sendable {
debugPrint("[DEBUG] Interceptor request url: " + url)
}

if let checkUnauthorized = urlRequest.value(forHTTPHeaderField: "X-NC-CheckUnauthorized"),
checkUnauthorized == "false" {
if let checkInterceptor = urlRequest.value(forHTTPHeaderField: nkCommonInstance.headerCheckInterceptor),
checkInterceptor == "false" {
return completion(.success(urlRequest))
} else if let account = urlRequest.value(forHTTPHeaderField: "X-NC-Account"),
let groupDefaults = UserDefaults(suiteName: NextcloudKit.shared.nkCommonInstance.groupIdentifier),
let unauthorizedArray = groupDefaults.array(forKey: "Unauthorized") as? [String],
unauthorizedArray.contains(account) {
self.nkCommonInstance.writeLog("[DEBUG] Unauthorized for account: \(account)")
let error = AFError.responseValidationFailed(reason: .unacceptableStatusCode(code: 401))
return completion(.failure(error))
}

if let account = urlRequest.value(forHTTPHeaderField: nkCommonInstance.headerAccount),
let groupDefaults = UserDefaults(suiteName: nkCommonInstance.groupIdentifier) {
/// Unauthorized
if let array = groupDefaults.array(forKey: nkCommonInstance.groupDefaultsUnauthorized) as? [String],
array.contains(account) {
self.nkCommonInstance.writeLog("[DEBUG] Unauthorized for account: \(account)")
let error = AFError.responseValidationFailed(reason: .unacceptableStatusCode(code: 401))
return completion(.failure(error))
/// Unavailable
} else if let array = groupDefaults.array(forKey: nkCommonInstance.groupDefaultsUnavailable) as? [String],
array.contains(account) {
self.nkCommonInstance.writeLog("[DEBUG] Unavailable for account: \(account)")
let error = AFError.responseValidationFailed(reason: .unacceptableStatusCode(code: 503))
return completion(.failure(error))
/// ToS
} else if let array = groupDefaults.array(forKey: nkCommonInstance.groupDefaultsToS) as? [String],
array.contains(account) {
self.nkCommonInstance.writeLog("[DEBUG] ToS for account: \(account)")
let error = AFError.responseValidationFailed(reason: .unacceptableStatusCode(code: 403))
return completion(.failure(error))
}
}

completion(.success(urlRequest))
Expand Down
40 changes: 0 additions & 40 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 @@ -28,46 +28,6 @@
func request<Value>(_ request: DataRequest, didParseResponse response: AFDataResponse<Value>) {
nkCommonInstance.delegate?.request(request, didParseResponse: response)

if let statusCode = response.response?.statusCode {

//
// Unauthorized, 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,
let groupDefaults = UserDefaults(suiteName: NextcloudKit.shared.nkCommonInstance.groupIdentifier) {

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

//
// Unavailable, append the account in groupDefaults unavailable array
//
} else if statusCode == 503,
let account = request.request?.allHTTPHeaderFields?["X-NC-Account"] as? String,
let groupDefaults = UserDefaults(suiteName: NextcloudKit.shared.nkCommonInstance.groupIdentifier) {

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

if let url = request.request?.url?.absoluteString,
let account = request.request?.allHTTPHeaderFields?["X-NC-Account"] as? String,
self.nkCommonInstance.levelLog > 0 {
debugPrint("[DEBUG] Monitor request url: \(url), status code \(statusCode), account: \(account)")
}
}

//
// LOG
//
Expand Down
6 changes: 3 additions & 3 deletions Sources/NextcloudKit/NKRequestOptions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class NKRequestOptions: NSObject {
var taskDescription: String?
var createProperties: [NKProperties]?
var removeProperties: [NKProperties]
var checkUnauthorized: Bool?
var checkInterceptor: Bool
var paginate: Bool
var paginateToken: String?
var paginateOffset: Int?
Expand All @@ -33,7 +33,7 @@ public class NKRequestOptions: NSObject {
taskDescription: String? = nil,
createProperties: [NKProperties]? = nil,
removeProperties: [NKProperties] = [],
checkUnauthorized: Bool? = nil,
checkInterceptor: Bool = true,
paginate: Bool = false,
paginateToken: String? = nil,
paginateOffset: Int? = nil,
Expand All @@ -50,7 +50,7 @@ public class NKRequestOptions: NSObject {
self.taskDescription = taskDescription
self.createProperties = createProperties
self.removeProperties = removeProperties
self.checkUnauthorized = checkUnauthorized
self.checkInterceptor = checkInterceptor
self.paginate = paginate
self.paginateToken = paginateToken
self.paginateOffset = paginateOffset
Expand Down
Loading
Loading