mirror of
https://github.com/home-assistant/iOS.git
synced 2026-04-16 20:49:48 -05:00
<!-- Thank you for submitting a Pull Request and helping to improve Home Assistant. Please complete the following sections to help the processing and review of your changes. Please do not delete anything from this template. --> ## Summary <!-- Provide a brief summary of the changes you have made and most importantly what they aim to achieve --> - `static let` plays nicely with modern Swift concurrency (async/await) - `static let` makes it impossible to mutate the values - causing undefined behavior in some cases
60 lines
1.7 KiB
Swift
60 lines
1.7 KiB
Swift
import Foundation
|
|
|
|
public extension URL {
|
|
func withWidgetAuthenticity() -> URL {
|
|
var components = URLComponents(url: self, resolvingAgainstBaseURL: false)!
|
|
components.insertWidgetAuthenticity()
|
|
return components.url!
|
|
}
|
|
}
|
|
|
|
public extension URLComponents {
|
|
private static let authenticityName = "widgetAuthenticity"
|
|
private static let serverName = "server"
|
|
|
|
mutating func insertWidgetAuthenticity() {
|
|
queryItems = (queryItems ?? []) + [
|
|
URLQueryItem(name: Self.authenticityName, value: Current.settingsStore.widgetAuthenticityToken),
|
|
]
|
|
}
|
|
|
|
mutating func insertWidgetServer(server: Server) {
|
|
queryItems = (queryItems ?? []) + [
|
|
URLQueryItem(name: Self.serverName, value: server.identifier.rawValue),
|
|
]
|
|
}
|
|
|
|
mutating func popWidgetAuthenticity() -> Bool {
|
|
guard let idx = queryItems?.firstIndex(where: {
|
|
$0.name == Self.authenticityName && $0.value == Current.settingsStore.widgetAuthenticityToken
|
|
}) else {
|
|
return false
|
|
}
|
|
|
|
queryItems?.remove(at: idx)
|
|
|
|
if queryItems?.isEmpty == true {
|
|
queryItems = nil
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
mutating func popWidgetServer(isFromWidget: Bool) -> Server? {
|
|
// param isn't necessary but prevents bad usage
|
|
guard isFromWidget, let idx = queryItems?.firstIndex(where: {
|
|
$0.name == Self.serverName
|
|
}) else {
|
|
return nil
|
|
}
|
|
|
|
let item = queryItems?.remove(at: idx)
|
|
|
|
if queryItems?.isEmpty == true {
|
|
queryItems = nil
|
|
}
|
|
|
|
return Current.servers.server(forServerIdentifier: item?.value)
|
|
}
|
|
}
|