-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathIncomingURLHandler.swift
More file actions
428 lines (383 loc) · 16.2 KB
/
IncomingURLHandler.swift
File metadata and controls
428 lines (383 loc) · 16.2 KB
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import CallbackURLKit
import Foundation
import PromiseKit
import SafariServices
import Shared
class IncomingURLHandler {
let windowController: WebViewWindowController
init(windowController: WebViewWindowController) {
self.windowController = windowController
registerCallbackURLKitHandlers()
}
@discardableResult
func handle(url: URL) -> Bool {
Current.Log.verbose("Received URL: \(url)")
var serviceData: [String: String] = [:]
if let queryItems = url.queryItems {
serviceData = queryItems
}
guard let host = url.host else { return true }
switch host.lowercased() {
case "x-callback-url":
return Manager.shared.handleOpen(url: url)
case "call_service":
callServiceURLHandler(url, serviceData)
case "fire_event":
fireEventURLHandler(url, serviceData)
case "send_location":
sendLocationURLHandler()
case "perform_action":
performActionURLHandler(url, serviceData: serviceData)
case "navigate": // homeassistant://navigate/lovelace/dashboard
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
return false
}
components.scheme = nil
components.host = nil
let isFromWidget = components.popWidgetAuthenticity()
let server = components.popWidgetServer(isFromWidget: isFromWidget)
guard let rawURL = components.url?.absoluteString else {
return false
}
if let presenting = windowController.presentedViewController,
presenting is SFSafariViewController {
// Dismiss my.* controller if it's on top - we don't get any other indication
presenting.dismiss(animated: true, completion: { [windowController] in
windowController.openSelectingServer(from: .deeplink, urlString: rawURL, skipConfirm: true)
})
} else if let server = server {
windowController.open(from: .deeplink, server: server, urlString: rawURL, skipConfirm: isFromWidget)
} else {
windowController.openSelectingServer(from: .deeplink, urlString: rawURL, skipConfirm: isFromWidget)
}
default:
Current.Log.warning("Can't route incoming URL: \(url)")
showAlert(title: L10n.errorLabel, message: L10n.UrlHandler.NoService.message(url.host!))
}
return true
}
@discardableResult
func handle(userActivity: NSUserActivity) -> Bool {
Current.Log.info(userActivity)
switch Current.tags.handle(userActivity: userActivity) {
case let .handled(type):
let (icon, text) = { () -> (MaterialDesignIcons, String) in
switch type {
case .nfc:
return (.nfcVariantIcon, L10n.Nfc.tagRead)
case .generic:
return (.qrcodeIcon, L10n.Nfc.genericTagRead)
}
}()
Current.sceneManager.showFullScreenConfirm(
icon: icon,
text: text,
onto: .value(windowController.window)
)
return true
case let .open(url):
// NFC-based URL
return handle(url: url)
case .unhandled:
// not a tag
if let url = userActivity.webpageURL, url.host?.lowercased() == "my.home-assistant.io" {
return showMy(for: url)
} else if let interaction = userActivity.interaction {
if #available(iOS 13, *) {
if let intent = interaction.intent as? OpenPageIntent,
let panel = intent.page, let path = panel.identifier {
Current.Log.info("launching from shortcuts with panel \(panel)")
let urlString = "/" + path
if let server = Current.servers.server(for: panel) {
windowController.open(
from: .deeplink,
server: server,
urlString: urlString,
skipConfirm: true
)
} else {
windowController.openSelectingServer(
from: .deeplink,
urlString: urlString,
skipConfirm: true
)
}
return true
}
}
return false
} else {
return false
}
}
}
func handle(shortcutItem: UIApplicationShortcutItem) -> Promise<Void> {
Current.backgroundTask(withName: "shortcut-item") { remaining -> Promise<Void> in
if shortcutItem.type == "sendLocation" {
return firstly {
Current.location.oneShotLocation(.AppShortcut, remaining)
}.then { location in
when(fulfilled: Current.apis.map { api in
api.SubmitLocation(updateType: .AppShortcut, location: location, zone: nil)
})
}.asVoid()
} else {
if let action = Current.realm().object(ofType: Action.self, forPrimaryKey: shortcutItem.type),
let server = Current.servers.server(for: action) {
Current.sceneManager.showFullScreenConfirm(
icon: MaterialDesignIcons(named: action.IconName),
text: action.Text,
onto: .value(windowController.window)
)
return Current.api(for: server).HandleAction(actionID: shortcutItem.type, source: .AppShortcut)
} else {
return .init(error: HomeAssistantAPI.APIError.notConfigured)
}
}
}
}
private func showAlert(title: String, message: String) {
let alert = UIAlertController(
title: title,
message: message,
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: L10n.okLabel, style: .default, handler: nil))
windowController.webViewControllerPromise.done {
$0.present(alert, animated: true, completion: nil)
}
}
private func showMy(for url: URL) -> Bool {
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
Current.Log.info("couldn't create url components out of \(url)")
return false
}
var queryItems = components.queryItems ?? []
queryItems.append(.init(name: "mobile", value: "1"))
components.queryItems = queryItems
guard let updatedURL = components.url else {
return false
}
// not animated in because it looks weird during the app launch animation
windowController.present(SFSafariViewController(url: updatedURL), animated: false, completion: nil)
return true
}
}
extension IncomingURLHandler {
enum XCallbackError: FailureCallbackError {
case generalError
case eventNameMissing
case serviceMissing
case templateMissing
var code: Int {
switch self {
case .generalError:
return 0
case .eventNameMissing:
return 1
case .serviceMissing:
return 2
case .templateMissing:
return 2
}
}
var message: String {
switch self {
case .generalError:
return L10n.UrlHandler.XCallbackUrl.Error.general
case .eventNameMissing:
return L10n.UrlHandler.XCallbackUrl.Error.eventNameMissing
case .serviceMissing:
return L10n.UrlHandler.XCallbackUrl.Error.serviceMissing
case .templateMissing:
return L10n.UrlHandler.XCallbackUrl.Error.templateMissing
}
}
}
private func registerCallbackURLKitHandlers() {
Manager.shared.callbackURLScheme = Manager.urlSchemes?.first
Manager.shared["fire_event"] = { parameters, success, failure, _ in
guard let eventName = parameters["eventName"] else {
failure(XCallbackError.eventNameMissing)
return
}
var cleanParamters = parameters
cleanParamters.removeValue(forKey: "eventName")
let eventData = cleanParamters
firstly { () -> Promise<Void> in
if let api = Current.apis.first {
return api.CreateEvent(eventType: eventName, eventData: eventData)
} else {
throw XCallbackError.generalError
}
}.done {
success(nil)
}.catch { error in
Current.Log.error("Received error from createEvent during X-Callback-URL call: \(error)")
failure(XCallbackError.generalError)
}
}
Manager.shared["call_service"] = { parameters, success, failure, _ in
guard let service = parameters["service"] else {
failure(XCallbackError.serviceMissing)
return
}
let splitService = service.components(separatedBy: ".")
let serviceDomain = splitService[0]
let serviceName = splitService[1]
var cleanParamters = parameters
cleanParamters.removeValue(forKey: "service")
let serviceData = cleanParamters
firstly { () -> Promise<Void> in
if let api = Current.apis.first {
return api.CallService(domain: serviceDomain, service: serviceName, serviceData: serviceData)
} else {
throw XCallbackError.generalError
}
}.done {
success(nil)
}.catch { error in
Current.Log.error("Received error from callService during X-Callback-URL call: \(error)")
failure(XCallbackError.generalError)
}
}
Manager.shared["send_location"] = { _, success, failure, _ in
firstly {
Current.location.oneShotLocation(.XCallbackURL, nil)
}.then { location in
when(fulfilled: Current.apis.map { api in
api.SubmitLocation(updateType: .XCallbackURL, location: location, zone: nil)
})
}.done { _ in
success(nil)
}.catch { error in
Current.Log.error("Received error from getAndSendLocation during X-Callback-URL call: \(error)")
failure(XCallbackError.generalError)
}
}
Manager.shared["render_template"] = { parameters, success, failure, _ in
guard let template = parameters["template"] else {
failure(XCallbackError.templateMissing)
return
}
var cleanParamters = parameters
cleanParamters.removeValue(forKey: "template")
let variablesDict = cleanParamters
if let api = Current.apis.first {
api.connection.subscribe(
to: .renderTemplate(template, variables: variablesDict),
initiated: { result in
if case let .failure(error) = result {
Current.Log.error("Received error from RenderTemplate during X-Callback-URL call: \(error)")
failure(XCallbackError.generalError)
}
}, handler: { token, data in
token.cancel()
success(["rendered": String(describing: data.result)])
}
)
} else {
failure(XCallbackError.generalError)
}
}
}
private func fireEventURLHandler(_ url: URL, _ serviceData: [String: String]) {
// homeassistant://fire_event/custom_event?entity_id=device_tracker.entity
firstly { () -> Promise<Void> in
if let api = Current.apis.first {
return api.CreateEvent(eventType: url.pathComponents[1], eventData: serviceData)
} else {
throw HomeAssistantAPI.APIError.notConfigured
}
}.done {
self.showAlert(
title: L10n.UrlHandler.FireEvent.Success.title,
message: L10n.UrlHandler.FireEvent.Success.message(url.pathComponents[1])
)
}.catch { error in
self.showAlert(
title: L10n.errorLabel,
message: L10n.UrlHandler.FireEvent.Error.message(
url.pathComponents[1],
error.localizedDescription
)
)
}
}
private func callServiceURLHandler(_ url: URL, _ serviceData: [String: String]) {
// homeassistant://call_service/device_tracker.see?entity_id=device_tracker.entity
let domain = url.pathComponents[1].components(separatedBy: ".")[0]
let service = url.pathComponents[1].components(separatedBy: ".")[1]
firstly { () -> Promise<Void> in
if let api = Current.apis.first {
return api.CallService(domain: domain, service: service, serviceData: serviceData)
} else {
throw HomeAssistantAPI.APIError.notConfigured
}
}.done { _ in
self.showAlert(
title: L10n.UrlHandler.CallService.Success.title,
message: L10n.UrlHandler.CallService.Success.message(url.pathComponents[1])
)
}.catch { error in
self.showAlert(
title: L10n.errorLabel,
message: L10n.UrlHandler.CallService.Error.message(
url.pathComponents[1],
error.localizedDescription
)
)
}
}
private func sendLocationURLHandler() {
// homeassistant://send_location/
firstly {
Current.location.oneShotLocation(.URLScheme, nil)
}.then { location in
when(fulfilled: Current.apis.map { api in
api.SubmitLocation(updateType: .URLScheme, location: location, zone: nil)
})
}.done { _ in
self.showAlert(
title: L10n.UrlHandler.SendLocation.Success.title,
message: L10n.UrlHandler.SendLocation.Success.message
)
}.catch { error in
self.showAlert(
title: L10n.errorLabel,
message: L10n.UrlHandler.SendLocation.Error.message(error.localizedDescription)
)
}
}
private func performActionURLHandler(_ url: URL, serviceData: [String: String]) {
let pathComponents = url.pathComponents
guard pathComponents.count > 1 else {
Current.Log.error("not enough path components for perform action handler")
return
}
let source: HomeAssistantAPI.ActionSource = {
if let sourceString = serviceData["source"],
let source = HomeAssistantAPI.ActionSource(rawValue: sourceString) {
return source
} else {
return .URLHandler
}
}()
let actionID = url.pathComponents[1]
guard let action = Current.realm().object(ofType: Action.self, forPrimaryKey: actionID),
let server = Current.servers.server(for: action) else {
Current.sceneManager.showFullScreenConfirm(
icon: .alertCircleIcon,
text: L10n.UrlHandler.Error.actionNotFound,
onto: .value(windowController.window)
)
return
}
Current.sceneManager.showFullScreenConfirm(
icon: MaterialDesignIcons(named: action.IconName),
text: action.Text,
onto: .value(windowController.window)
)
Current.api(for: server).HandleAction(actionID: actionID, source: source).cauterize()
}
}