Meshtastic-Apple/Meshtastic/Extensions/Url.swift

67 lines
1.7 KiB
Swift
Raw Normal View History

2023-05-05 17:13:35 -07:00
//
// Url.swift
// Meshtastic
//
// Copyright(c) Garth Vander Houwen 5/5/23.
//
import Foundation
2024-06-23 16:11:02 -07:00
import OSLog
2023-05-05 17:13:35 -07:00
extension URL {
func regularFileAllocatedSize() throws -> UInt64 {
let resourceValues = try self.resourceValues(forKeys: allocatedSizeResourceKeys)
guard resourceValues.isRegularFile ?? false else {
return 0
}
return UInt64(resourceValues.totalFileAllocatedSize ?? resourceValues.fileAllocatedSize ?? 0)
}
subscript(queryParam: String) -> String? {
guard let url = URLComponents(string: self.absoluteString) else { return nil }
if let parameters = url.queryItems {
return parameters.first(where: { $0.name == queryParam })?.value
} else if let paramPairs = url.fragment?.components(separatedBy: "?").last?.components(separatedBy: "&") {
for pair in paramPairs where pair.contains(queryParam) {
return pair.components(separatedBy: "=").last
}
return nil
} else {
return nil
}
2023-05-05 17:13:35 -07:00
}
var queryParameters: [String: String]? {
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true),
let queryItems = components.queryItems else {
return nil
}
var parameters = [String: String]()
for item in queryItems {
parameters[item.name] = item.value
}
return parameters
}
2024-06-23 13:00:20 -07:00
var attributes: [FileAttributeKey: Any]? {
do {
return try FileManager.default.attributesOfItem(atPath: path)
} catch let error as NSError {
2024-06-23 16:11:02 -07:00
Logger.services.error("FileAttribute error: \(error, privacy: . public)")
2024-06-23 13:00:20 -07:00
}
return nil
}
var fileSize: UInt64 {
return attributes?[.size] as? UInt64 ?? UInt64(0)
}
var fileSizeString: String {
return ByteCountFormatter.string(fromByteCount: Int64(fileSize), countStyle: .file)
}
var creationDate: Date? {
return attributes?[.creationDate] as? Date
}
2023-05-05 17:13:35 -07:00
}