yattee/Shared/UserAgentManager.swift

38 lines
1.2 KiB
Swift
Raw Normal View History

import Logging
2024-05-20 14:03:13 +00:00
#if !os(tvOS)
2024-05-23 09:44:58 +00:00
import WebKit
2024-05-20 14:03:13 +00:00
#endif
final class UserAgentManager {
static let shared = UserAgentManager()
private(set) var userAgent: String
2024-05-20 14:03:13 +00:00
#if !os(tvOS)
2024-05-23 09:44:58 +00:00
private var webView: WKWebView?
2024-05-20 14:03:13 +00:00
#endif
private init() {
2024-05-20 14:03:13 +00:00
/*
In case an error occurs while retrieving the actual User-Agent, and on tvOS,
we set a default User-Agent value that represents a commonly used User-Agent.
*/
2024-05-20 14:03:13 +00:00
userAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
#if !os(tvOS)
2024-05-23 09:44:58 +00:00
webView = WKWebView()
webView?.evaluateJavaScript("navigator.userAgent") { [weak self] result, _ in
if let userAgent = result as? String {
DispatchQueue.main.async {
self?.userAgent = userAgent
Logger(label: "stream.yattee.userAgentManager").info("User-Agent: \(userAgent)")
}
} else {
Logger(label: "stream.yattee.userAgentManager").warning("Failed to update User-Agent.")
}
}
2024-05-20 14:03:13 +00:00
#else
2024-05-23 09:44:58 +00:00
Logger(label: "stream.yattee.userAgentManager.tvOS").info("User-Agent: \(userAgent)")
2024-05-20 14:03:13 +00:00
#endif
}
}