Skip to content

Commit

Permalink
First light in the tunnel - works in simulator
Browse files Browse the repository at this point in the history
Signed-off-by: Tim Bert <5411131+timbms@users.noreply.github.com>
  • Loading branch information
timbms committed Nov 7, 2023
2 parents 847fb36 + 0f024fe commit 52f27b7
Show file tree
Hide file tree
Showing 14 changed files with 63 additions and 28 deletions.
19 changes: 19 additions & 0 deletions OpenHABCore/Sources/OpenHABCore/Util/Comparable.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright (c) 2010-2023 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0

import Foundation

// Idea taken from https://twitter.com/alexiscreuzot/status/1635489793294454784?s=61&t=8ECwUy6QFS5UxjAFZzZ-hw
public extension Comparable {
func clamped(to limits: ClosedRange<Self>) -> Self {
min(max(self, limits.lowerBound), limits.upperBound)
}
}
2 changes: 1 addition & 1 deletion OpenHABCore/Sources/OpenHABCore/Util/Endpoint.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public extension Endpoint {
static func watchSitemap(openHABRootUrl: String, sitemapName: String) -> Endpoint {
Endpoint(
baseURL: openHABRootUrl,
path: "/rest/sitemaps/\(sitemapName)/\(sitemapName)",
path: "/rest/sitemaps/uicomponents_\(sitemapName)/uicomponents_\(sitemapName)",
queryItems: [URLQueryItem(name: "jsoncallback", value: "callback")]
)
}
Expand Down
6 changes: 2 additions & 4 deletions OpenHABCore/Sources/OpenHABCore/Util/NetworkConnection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@ import Alamofire
import Foundation
import os.log

// https://medium.com/@AladinWay/write-a-networking-layer-in-swift-4-using-alamofire-5-and-codable-part-2-perform-request-and-b5c7ee2e012d

public let onReceiveSessionTaskChallenge = { (_: URLSession, _: URLSessionTask, challenge: URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) in
public func onReceiveSessionTaskChallenge(with challenge: URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) {
os_log("onReceiveSessionTaskChallenge host:'%{PUBLIC}@'", log: .default, type: .error, challenge.protectionSpace.host)
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
Expand All @@ -34,7 +32,7 @@ public let onReceiveSessionTaskChallenge = { (_: URLSession, _: URLSessionTask,
return (disposition, credential)
}

public let onReceiveSessionChallenge = { (_: URLSession, challenge: URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) in
public func onReceiveSessionChallenge(with challenge: URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) {
os_log("onReceiveSessionChallenge host:'%{PUBLIC}@'", log: .default, type: .error, challenge.protectionSpace.host)
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public class ServerCertificateManager: ServerTrustManager, ServerTrustEvaluating
weak var delegate: ServerCertificateManagerDelegate?
// ignoreSSL is a synonym for allowInvalidCertificates, ignoreCertificates
public var ignoreSSL = false
public var trustedCertificates: [String: Any] = [:]
public var trustedCertificates: [String: Data] = [:]

// Init a ServerCertificateManager and set ignore certificates setting
public init(ignoreSSL: Bool) {
Expand Down Expand Up @@ -76,7 +76,7 @@ public class ServerCertificateManager: ServerTrustManager, ServerTrustEvaluating

public func saveTrustedCertificates() {
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: trustedCertificates, requiringSecureCoding: false)
let data = try PropertyListEncoder().encode(trustedCertificates)
try data.write(to: getPersistensePath())
} catch {
os_log("Could not save trusted certificates", log: .default)
Expand All @@ -90,18 +90,31 @@ public class ServerCertificateManager: ServerTrustManager, ServerTrustEvaluating
}

func certificateData(forDomain domain: String) -> CFData? {
guard let certificateData = trustedCertificates[domain] as? Data else { return nil }
guard let certificateData = trustedCertificates[domain] else { return nil }
return certificateData as CFData
}

func loadTrustedCertificates() {
var decodableTrustedCertificates: [String: Data] = [:]
do {
let rawdata = try Data(contentsOf: getPersistensePath())
if let unarchive = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(rawdata) as? [String: Any] {
trustedCertificates = unarchive
}
let decoder = PropertyListDecoder()
decodableTrustedCertificates = try decoder.decode([String: Data].self, from: rawdata)
trustedCertificates = decodableTrustedCertificates
} catch {
os_log("Could not load trusted certificates", log: .default)
// if Decodable fails, fall back to NSKeyedArchiver. Handling can be removed when customer base is migrated
do {
let rawdata = try Data(contentsOf: getPersistensePath())
if let unarchivedTrustedCertificates = try? NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSDictionary.self, NSString.self, NSData.self], from: rawdata) as? [String: Data] {
trustedCertificates = unarchivedTrustedCertificates
saveTrustedCertificates() // Ensure that data is written in new format to take this path only once
} else {
return
}
} catch {
os_log("Could not load trusted unarchived certificates", log: .default)
}
os_log("Could not load trusted codable certificates", log: .default)
}
}

Expand Down
6 changes: 5 additions & 1 deletion openHAB/OpenHABRootViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,11 @@ class OpenHABRootViewController: UIViewController {
if let menu = SideMenuManager.default.rightMenuNavigationController {
// don't try and push an already visible menu less you crash the app
dismiss(animated: false) {
var topMostViewController = UIApplication.shared.keyWindow?.rootViewController
var topMostViewController: UIViewController? = if #available(iOS 13, *) {
UIApplication.shared.connectedScenes.flatMap { ($0 as? UIWindowScene)?.windows ?? [] }.last { $0.isKeyWindow }?.rootViewController
} else {
UIApplication.shared.keyWindow?.rootViewController
}
while let presentedViewController = topMostViewController?.presentedViewController {
topMostViewController = presentedViewController
}
Expand Down
4 changes: 2 additions & 2 deletions openHAB/OpenHABSitemapViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -811,15 +811,15 @@ extension OpenHABSitemapViewController: AuthenticationChallengeResponsible {
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let (disposition, credential) = onReceiveSessionTaskChallenge(URLSession(configuration: .default), task, challenge)
let (disposition, credential) = onReceiveSessionTaskChallenge(with: challenge)
completionHandler(disposition, credential)
}

// sessionDelegate.onReceiveSessionChallenge
func downloader(_ downloader: ImageDownloader,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let (disposition, credential) = onReceiveSessionChallenge(URLSession(configuration: .default), challenge)
let (disposition, credential) = onReceiveSessionChallenge(with: challenge)
completionHandler(disposition, credential)
}
}
4 changes: 2 additions & 2 deletions openHAB/OpenHABWebViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -297,9 +297,9 @@ extension OpenHABWebViewController: WKNavigationDelegate {
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if challenge.protectionSpace.authenticationMethod.isAny(of: NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodDefault) {
(disposition, credential) = onReceiveSessionTaskChallenge(URLSession(configuration: .default), URLSessionDataTask(), challenge)
(disposition, credential) = onReceiveSessionTaskChallenge(with: challenge)
} else {
(disposition, credential) = onReceiveSessionChallenge(URLSession(configuration: .default), challenge)
(disposition, credential) = onReceiveSessionChallenge(with: challenge)
}
completionHandler(disposition, credential)
}
Expand Down
2 changes: 1 addition & 1 deletion openHAB/SliderUITableViewCell.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ class SliderUITableViewCell: GenericUITableViewCell {
private func adj(_ raw: Double) -> Double {
var valueAdjustedToStep = Double(floor(Float(((raw - widget.minValue))) / step) * step)
valueAdjustedToStep += widget.minValue
return min(max(valueAdjustedToStep, widget.minValue), widget.maxValue)
return valueAdjustedToStep.clamped(to: widget.minValue ... widget.maxValue)
}

private func adjustedValue() -> Double {
Expand Down
2 changes: 1 addition & 1 deletion openHAB/WebUITableViewCell.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ extension WebUITableViewCell: WKNavigationDelegate {
}

func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let (disposition, credential) = onReceiveSessionChallenge(URLSession(configuration: .default), challenge)
let (disposition, credential) = onReceiveSessionChallenge(with: challenge)
completionHandler(disposition, credential)
}
}
Expand Down
3 changes: 2 additions & 1 deletion openHABUITests/OpenHABUITests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,9 @@ class OpenHABUITests: XCTestCase {

menuStaticText?.tap()
sleep(1)

// openHAB logo in left menu
webViewsQuery.otherElements["openHAB"].children(matching: .other).element(boundBy: 0).children(matching: .link).element.children(matching: .link).element.children(matching: .image).element.tap()
webViewsQuery.links.allElementsBoundByIndex[1].tap()
sleep(2)

// right menu in webUI
Expand Down
4 changes: 2 additions & 2 deletions openHABWatch/Extension/OpenHABWatchAppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,15 @@ extension OpenHABWatchAppDelegate: AuthenticationChallengeResponsible {
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let (disposition, credential) = onReceiveSessionTaskChallenge(URLSession(configuration: .default), task, challenge)
let (disposition, credential) = onReceiveSessionTaskChallenge(with: challenge)
completionHandler(disposition, credential)
}

// sessionDelegate.onReceiveSessionChallenge
func downloader(_ downloader: ImageDownloader,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let (disposition, credential) = onReceiveSessionChallenge(URLSession(configuration: .default), challenge)
let (disposition, credential) = onReceiveSessionChallenge(with: challenge)
completionHandler(disposition, credential)
}
}
Expand Down
8 changes: 4 additions & 4 deletions openHABWatch/External/AppMessageService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ class AppMessageService: NSObject, WCSessionDelegate {
ObservableOpenHABDataObject.shared.ignoreSSL = ignoreSSL
}

// if let trustedCertificates = applicationContext["trustedCertificates"] as? [String: Any] {
// NetworkConnection.shared.serverCertificateManager.trustedCertificates = trustedCertificates
// NetworkConnection.shared.serverCertificateManager.saveTrustedCertificates()
// }
if let trustedCertificates = applicationContext["trustedCertificates"] as? [String: Data] {
NetworkConnection.shared.serverCertificateManager.trustedCertificates = trustedCertificates
NetworkConnection.shared.serverCertificateManager.saveTrustedCertificates()
}

if let alwaysSendCreds = applicationContext["alwaysSendCreds"] as? Bool {
ObservableOpenHABDataObject.shared.openHABAlwaysSendCreds = alwaysSendCreds
Expand Down
2 changes: 1 addition & 1 deletion openHABWatch/Model/ObservableOpenHABWidget.swift
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ class ObservableOpenHABWidget: NSObject, MKAnnotation, Identifiable, ObservableO
private func adj(_ raw: Double) -> Double {
var valueAdjustedToStep = floor((raw - minValue) / step) * step
valueAdjustedToStep += minValue
return min(max(valueAdjustedToStep, minValue), maxValue)
return valueAdjustedToStep.clamped(to: minValue ... maxValue)
}
}

Expand Down
2 changes: 1 addition & 1 deletion openHABWatch/Views/Utils/ColorSelection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ struct ColorSelection: View {

/// Prevent the draggable element from going over its limit
func limitDisplacement(_ value: Double, _ limit: CGFloat, _ state: CGFloat) -> CGFloat {
max(0, min(limit, CGFloat(value) * limit + state))
(CGFloat(value) * limit + state).clamped(to: 0 ... limit)
}

/// Prevent the draggable element from going beyond the circle
Expand Down

0 comments on commit 52f27b7

Please sign in to comment.