Files
NetNewsWire/Modules/RSWeb/Sources/RSWeb/CacheControlInfo.swift
2025-04-23 17:13:24 -07:00

67 lines
1.5 KiB
Swift
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// CacheControl.swift
// RSWeb
//
// Created by Brent Simmons on 11/30/24.
//
import Foundation
/// Basic Cache-Control handling  just the part we need,
/// which is to know when we got the response (dateCreated)
/// and when we can ask again (canResume).
public struct CacheControlInfo: Codable, Equatable {
let dateCreated: Date
let maxAge: TimeInterval
var resumeDate: Date {
dateCreated + maxAge
}
public var canResume: Bool {
Date() >= resumeDate
}
public init?(urlResponse: HTTPURLResponse) {
guard let cacheControlValue = urlResponse.valueForHTTPHeaderField(HTTPResponseHeader.cacheControl) else {
return nil
}
self.init(value: cacheControlValue)
}
/// Returns nil if theres no max-age or its < 1.
public init?(value: String) {
guard let maxAge = Self.parseMaxAge(value) else {
return nil
}
let d = Date()
self.dateCreated = d
self.maxAge = maxAge
}
}
private extension CacheControlInfo {
static let maxAgePrefix = "max-age="
static let maxAgePrefixCount = maxAgePrefix.count
static func parseMaxAge(_ s: String) -> TimeInterval? {
let components = s.components(separatedBy: ",")
let trimmedComponents = components.map { $0.trimmingCharacters(in: .whitespaces) }
for component in trimmedComponents {
if component.hasPrefix(Self.maxAgePrefix) {
let maxAgeStringValue = component.dropFirst(maxAgePrefixCount)
if let timeInterval = TimeInterval(maxAgeStringValue), timeInterval > 0 {
return timeInterval
}
}
}
return nil
}
}