Files
iOS/Sources/Shared/Common/URLComponents+WidgetAuthenticity.swift
Michal Šrůtek 7de47c6e62 static var to static let (#2642)
<!-- 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
2024-03-25 11:57:48 +01:00

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)
}
}