/
ORViewController.swift
363 lines (331 loc) · 18.9 KB
/
ORViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/*
* Copyright 2017, OpenRemote Inc.
*
* See the CONTRIBUTORS.txt file in the distribution for a
* full listing of individual contributors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import UIKit
import WebKit
open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHandler, WKUIDelegate, WKNavigationDelegate {
public var data : Data?
public var myWebView : WKWebView?
public var defaults : UserDefaults?
public var webCfg : WKWebViewConfiguration?
public var isLoading = false
var geofenceProvider: GeofenceProvider?
var pushProvider: PushNotificationProvider?
var storageProvider: StorageProvider?
open override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.configureAccess()
}
open func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
let jsonDictionnary = message.body as? [String : Any]
if let type = jsonDictionnary?["type"] as? String {
switch (type) {
case "provider":
if let postMessageDict = jsonDictionnary?[DefaultsKey.dataKey] as? [String: Any] {
if let action = postMessageDict[DefaultsKey.actionKey] as? String {
if let provider = postMessageDict[DefaultsKey.providerKey] as? String {
switch (provider) {
case Providers.push:
switch(action) {
case Actions.providerInit:
pushProvider = PushNotificationProvider()
pushProvider!.initialize(callback: { initalizeData in
self.sendData(data: initalizeData)
})
case Actions.providerEnable:
if let consoleId = postMessageDict[GeofenceProvider.consoleIdKey] as? String {
pushProvider?.enable(consoleId: consoleId, callback: { enableData in
self.sendData(data: enableData)
})
}
case Actions.providerDisable:
if let disableData = pushProvider?.disable() {
sendData(data: disableData)
}
default:
print("Wrong action \(action) for \(provider)")
}
case Providers.geofence:
switch(action) {
case Actions.providerInit:
geofenceProvider = GeofenceProvider()
let initializeData = geofenceProvider!.initialize()
sendData(data: initializeData)
case Actions.providerEnable:
if let consoleId = postMessageDict[GeofenceProvider.consoleIdKey] as? String {
geofenceProvider?.enable(baseUrl: "\(ORServer.baseUrl)api/\(ORServer.realm)", consoleId: consoleId, callback: { enableData in
self.sendData(data: enableData)
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) {
self.geofenceProvider?.fetchGeofences()
}
})
}
case Actions.providerDisable:
if let disableData = geofenceProvider?.disable() {
sendData(data: disableData)
}
case Actions.geofenceRefresh:
geofenceProvider?.refreshGeofences()
case Actions.getLocation:
geofenceProvider?.getLocation(callback: { locationData in
if locationData.isEmpty {
let alertController = UIAlertController(title: "Location Services disabled", message: "Please enable Location Services for this app", preferredStyle: .alert)
if let settingsUrl = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(settingsUrl) {
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { alertAction in
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
print("Settings opened: \(success)") // Prints true
})
}
}))
alertController.addAction(UIAlertAction(title: "Not now", style: .cancel, handler: nil))
} else {
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
}
self.present(alertController, animated: true, completion: nil)
}
self.sendData(data: locationData)
})
default:
print("Wrong action \(action) for \(provider)")
}
case Providers.storage:
switch(action) {
case Actions.providerInit:
storageProvider = StorageProvider()
let initializeData = storageProvider!.initialize()
sendData(data: initializeData)
case Actions.providerEnable:
if let enableData = storageProvider?.enable() {
sendData(data: enableData)
}
case Actions.providerDisable:
if let disableData = storageProvider?.disable() {
sendData(data: disableData)
}
case Actions.store:
if let key = postMessageDict["key"] as? String {
storageProvider?.store(key: key, data: postMessageDict["value"] as? String)
}
case Actions.retrieve:
if let key = postMessageDict["key"] as? String {
if let retrieveData = storageProvider?.retrieve(key: key) {
sendData(data: retrieveData)
}
}
default:
print("Wrong action \(action) for \(provider)")
}
default:
print("Unknown provider type: \(provider )")
}
}
}
}
default:
print("Unknown message type: \(type )")
}
}
}
open func sendData(data: [String: Any?]) {
if let theJSONData = try? JSONSerialization.data(
withJSONObject: data,
options: []) {
let theJSONText = String(data: theJSONData,
encoding: .utf8)
let returnMessage = "OpenRemoteConsole._handleProviderResponse('\(theJSONText ?? "null")')"
DispatchQueue.main.async {
self.myWebView?.evaluateJavaScript("\(returnMessage)", completionHandler: { (any, error) in
print("JSON string = \(theJSONText!)")
})
}
}
}
open func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
NSLog("error %@", message)
TokenManager.sharedInstance.resetTokenAndAuthenticate()
self.dismiss(animated: true, completion: nil)
completionHandler()
}
open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if (navigationAction.request.url?.absoluteString.contains("logout"))! {
TokenManager.sharedInstance.logout()
decisionHandler(.cancel)
self.dismiss(animated: false, completion: nil)
} else {
let app = UIApplication.shared
if navigationAction.targetFrame == nil, let url = navigationAction.request.url{
if app.canOpenURL(url) {
app.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)
decisionHandler(.cancel)
}
} else {
decisionHandler(.allow)
}
}
isLoading = false
}
open func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
if let response = navigationResponse.response as? HTTPURLResponse {
if response.statusCode != 200 && response.statusCode != 204 {
decisionHandler(.cancel)
if response.url?.lastPathComponent == "token" && response.statusCode == 400 {
TokenManager.sharedInstance.resetToken()
}
isLoading = false
handleError(errorCode: response.statusCode, description: "Error in request", failingUrl: response.url?.absoluteString ?? "", isForMainFrame: true)
return
}
}
isLoading = false
decisionHandler(.allow)
}
open func login() {
guard let request = URL(string: String(format:"\(ORServer.scheme)://%@/%@", ORServer.hostURL, ORServer.initialPath)) else { return }
UIApplication.shared.isNetworkActivityIndicatorVisible = true
_ = self.myWebView?.load(URLRequest(url: request))
isLoading = true
}
open func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
NSLog("error %@", error.localizedDescription)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if let err = error as? URLError {
let httpCode: Int
switch(err.code) {
case .cannotFindHost:
httpCode = 404
default:
httpCode = 500
}
handleError(errorCode: httpCode, description: err.localizedDescription, failingUrl: err.failureURLString ?? "", isForMainFrame: true)
} else {
handleError(errorCode: 0, description: error.localizedDescription, failingUrl: webView.url?.absoluteString ?? "", isForMainFrame: true)
}
}
open func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
if challenge.protectionSpace.host == ORServer.hostURL {
completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
} else {
completionHandler(.performDefaultHandling, nil)
}
}
}
open func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
open func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
if challenge.protectionSpace.host == ORServer.hostURL {
completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
} else {
completionHandler(.performDefaultHandling, nil)
}
}
}
open func configureAccess() {
let webCfg:WKWebViewConfiguration = WKWebViewConfiguration()
let userController:WKUserContentController = WKUserContentController()
userController.add(self, name: "int")
let exec_template : String? = ""
let userScript:WKUserScript = WKUserScript(source: exec_template!, injectionTime: .atDocumentStart, forMainFrameOnly: true)
userController.addUserScript(userScript)
webCfg.userContentController = userController;
let sbHeight: CGFloat
if #available(iOS 11.0, *) {
sbHeight = UIApplication.shared.keyWindow?.safeAreaInsets.top ?? UIApplication.shared.statusBarFrame.height
} else {
sbHeight = UIApplication.shared.statusBarFrame.height
}
webCfg.setURLSchemeHandler(ORSchemeHandler(), forURLScheme: ORSchemeHandler.browserScheme)
let webFrame = CGRect(x : 0,y : sbHeight,width : view.frame.size.width,height : view.frame.size.height - sbHeight)
myWebView = WKWebView(frame: webFrame, configuration: webCfg)
myWebView?.autoresizingMask = [.flexibleWidth, .flexibleHeight];
myWebView?.uiDelegate = self;
myWebView?.navigationDelegate = self;
view.addSubview(myWebView!)
}
open func loadURL(url : URL) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
_ = self.myWebView?.load(URLRequest(url:url))
isLoading = true
}
internal func handleError(errorCode: Int, description: String, failingUrl: String, isForMainFrame: Bool) {
NSLog("%@", "Error requesting '\(failingUrl)': \(errorCode) (\(description))")
// This will be the URL loaded into the webview itself (false for images etc. of the main page)
if isForMainFrame {
// Check page load error URL
let errorUrl = ORServer.errorUrl
if let errorURL = URL(string: errorUrl), ORServer.errorUrl != failingUrl {
NSLog("%@", "Loading error URL: \(errorUrl)")
loadURL(url: errorURL)
}
} else {
if ORServer.ignorePageErrors {
return;
}
let error = NSError(domain: "", code: 0, userInfo: [
NSLocalizedDescriptionKey : NSLocalizedString("HTTPErrorReturned", value: "Connection Error", comment: "Error requesting '\(failingUrl)': \(errorCode) (\(description))")
])
if let vc = self.presentingViewController as? ORLoginViewController {
vc.isInError = true
}
self.dismiss(animated: true) {
ErrorManager.showError(error:error)
}
}
}
open func updateAssetAttribute(assetId : String, attributeName : String, rawJson : String) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
TokenManager.sharedInstance.getAccessToken { (accessTokenResult) in
switch accessTokenResult {
case .Failure(let error) :
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.handleError(errorCode: 0, description: error!.localizedDescription, failingUrl: "", isForMainFrame: false)
case .Success(let accessToken) :
guard let urlRequest = URL(string: String(String(format: "\(ORServer.scheme)://%@/%@/asset/%@/attribute/%@", ORServer.hostURL, ORServer.realm, assetId, attributeName))) else { return }
let request = NSMutableURLRequest(url: urlRequest)
request.httpMethod = "PUT"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = rawJson.data(using: .utf8)
request.addValue(String(format:"Bearer %@", accessToken!), forHTTPHeaderField: "Authorization")
let sessionConfiguration = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue : nil)
let reqDataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if (error != nil) {
self.handleError(errorCode: 0, description: error!.localizedDescription, failingUrl: "", isForMainFrame: false)
}
}
})
reqDataTask.resume()
}
}
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)})
}