-
Notifications
You must be signed in to change notification settings - Fork 430
Expand file tree
/
Copy pathMagicItem.swift
More file actions
440 lines (407 loc) · 14.9 KB
/
MagicItem.swift
File metadata and controls
440 lines (407 loc) · 14.9 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
429
430
431
432
433
434
435
436
437
438
439
440
import Foundation
import GRDB
import HAKit
import PromiseKit
/// Object that represents iOS item that can be displayed in Watch, Widgets, CarPlay and perform different action types
public struct MagicItem: Codable, Equatable, Hashable {
/// Identity-based equality for use in sets/dictionaries and caching.
/// Compares only stable identity fields, not mutable content.
public static func == (lhs: MagicItem, rhs: MagicItem) -> Bool {
lhs.id == rhs.id
&& lhs.serverId == rhs.serverId
&& lhs.type == rhs.type
}
/// Identity-based hashing consistent with `==`.
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(serverId)
hasher.combine(type)
}
/// Content-based equality for UI/change detection.
/// Unlike `==`, this includes mutable fields.
public func contentEquals(_ other: MagicItem) -> Bool {
id == other.id
&& serverId == other.serverId
&& type == other.type
&& customization == other.customization
&& action == other.action
&& displayText == other.displayText
&& items == other.items
}
/// Id match it's type Id, e.g. "script.open_gate"
public let id: String
public var serverId: String
public let type: ItemType
public var customization: Customization?
public var action: ItemAction?
public var displayText: String?
public var items: [MagicItem]? /// Only for folder type, represents items inside the folder
/// Server unique ID - e.g. "EB1364-script.open_gate"
public var serverUniqueId: String {
"\(serverId)-\(id)"
}
/// A hash value that includes mutable content fields, for use as a SwiftUI animation/change detection value.
public var contentHash: Int {
var hasher = Hasher()
hasher.combine(id)
hasher.combine(serverId)
hasher.combine(type)
hasher.combine(customization)
hasher.combine(action)
hasher.combine(displayText)
hasher.combine(items?.map(\.contentHash))
return hasher.finalize()
}
/// Domain retrieved from id when item is entity else nil
public var domain: Domain? {
if let domainString = id.split(separator: ".").first, let domain = Domain(rawValue: String(domainString)) {
return domain
} else {
return nil
}
}
public init(
id: String,
serverId: String,
type: ItemType,
customization: Customization? = .init(),
action: ItemAction? = .default,
displayText: String? = nil,
items: [MagicItem]? = nil
) {
self.id = id
self.serverId = serverId
self.type = type
self.customization = customization
self.action = action
self.displayText = displayText
self.items = items
}
public enum ItemType: String, Codable {
/// aka iOS legacy Action
case action
case script
case scene
case entity
case folder
}
public struct Customization: Codable, Equatable, Hashable {
public var iconColor: String?
public var textColor: String?
public var backgroundColor: String?
/// If true, execution will request confirmation before running
public var requiresConfirmation: Bool
/// Override icon, MaterialDesignIcons name
public var icon: String?
/// True only when the user explicitly picked a custom icon via the icon picker
public var iconIsCustomized: Bool?
public var useCustomColors: Bool {
textColor != nil || backgroundColor != nil
}
public init(
iconColor: String? = nil,
textColor: String? = nil,
backgroundColor: String? = nil,
requiresConfirmation: Bool = false,
icon: String? = nil,
iconIsCustomized: Bool = false
) {
self.iconColor = iconColor
self.textColor = textColor
self.backgroundColor = backgroundColor
self.requiresConfirmation = requiresConfirmation
self.icon = icon
self.iconIsCustomized = iconIsCustomized
}
}
public struct Info: WatchCodable, Equatable {
/// Server unique ID - "\(serverId)-(entityId)"
public let id: String
public let name: String
public let iconName: String
public let customization: Customization?
public init(id: String, name: String, iconName: String, customization: Customization? = nil) {
self.id = id
self.name = name
self.iconName = iconName
self.customization = customization
}
}
/// Icon for given magic item type
public func icon(info: Info) -> MaterialDesignIcons {
var icon: MaterialDesignIcons
if let icon = customization?.icon {
return MaterialDesignIcons(named: icon, fallback: .dotsGridIcon)
} else {
switch type {
case .action, .scene:
icon = MaterialDesignIcons(named: info.iconName, fallback: .scriptTextOutlineIcon)
case .script, .entity:
icon = MaterialDesignIcons(
serversideValueNamed: info.iconName,
fallback: .dotsGridIcon
)
case .folder:
icon = .folderIcon
}
}
return icon
}
/// Name to be visible when rendegin item, priority: displayText -> info.name
public func name(info: Info) -> String {
displayText ?? info.name
}
public var widgetInteractionType: WidgetInteractionType {
let magicItem = self
guard let domain = magicItem.domain else { return .appIntent(.refresh) }
var interactionType: WidgetInteractionType = .appIntent(.refresh)
if let magicItemAction = magicItem.action, magicItemAction != .default {
switch magicItemAction {
case .default:
// This block of code should not be reached, default should not be handled here
// Returning something to avoid compiler error
interactionType = .appIntent(.refresh)
case .moreInfoDialog:
interactionType = navigateIntent(url: AppConstants.openEntityDeeplinkURL(
entityId: magicItem.id,
serverId: magicItem.serverId
))
case .nothing:
interactionType = .appIntent(.refresh)
case let .navigate(path):
interactionType = navigateIntent(path: path)
case let .runScript(serverId, scriptId):
interactionType = .appIntent(.activate(
entityId: scriptId,
domain: Domain.script.rawValue,
serverId: serverId
))
case let .assist(serverId, pipelineId, startListening):
interactionType = assistIntent(
serverId: serverId,
pipelineId: pipelineId,
startListening: startListening
)
}
} else {
switch domain {
case .button, .inputButton:
interactionType = .appIntent(.press(
entityId: magicItem.id,
domain: domain.rawValue,
serverId: magicItem.serverId
))
case .cover, .inputBoolean, .light, .switch:
interactionType = .appIntent(.toggle(
entityId: magicItem.id,
domain: domain.rawValue,
serverId: magicItem.serverId
))
case .lock:
interactionType = navigateIntent(url: AppConstants.openEntityDeeplinkURL(
entityId: magicItem.id,
serverId: magicItem.serverId
))
case .climate:
interactionType = navigateIntent(url: AppConstants.openEntityDeeplinkURL(
entityId: magicItem.id,
serverId: magicItem.serverId
))
case .scene, .script:
interactionType = .appIntent(.activate(
entityId: magicItem.id,
domain: domain.rawValue,
serverId: magicItem.serverId
))
default:
interactionType = navigateIntent(url: AppConstants.openEntityDeeplinkURL(
entityId: magicItem.id,
serverId: magicItem.serverId
))
}
}
return interactionType
}
private func navigateIntent(path: String) -> WidgetInteractionType {
let magicItem = self
var path = path
if path.hasPrefix("/") {
path.removeFirst()
}
if let url = AppConstants.navigateDeeplinkURL(
path: path,
serverId: magicItem.serverId,
avoidUnecessaryReload: true
) {
return .widgetURL(url)
} else {
return .appIntent(.refresh)
}
}
private func navigateIntent(url: URL?) -> WidgetInteractionType {
guard let url else {
return .appIntent(.refresh)
}
return .widgetURL(url)
}
private func assistIntent(serverId: String, pipelineId: String, startListening: Bool) -> WidgetInteractionType {
if let url = AppConstants.assistDeeplinkURL(
serverId: serverId,
pipelineId: pipelineId,
startListening: startListening
) {
return .widgetURL(url)
} else {
return .appIntent(.refresh)
}
}
}
public enum MagicItemError: Error {
case unknownDomain
}
public enum ItemAction: Codable, CaseIterable, Equatable, Hashable {
public static var allCases: [ItemAction] = [
.default,
.moreInfoDialog,
.navigate(""),
.runScript("", ""),
.assist("", "", false),
.nothing,
]
case `default`
case moreInfoDialog
case navigate(_ navigationPath: String)
case runScript(_ serverId: String, _ scriptId: String)
case assist(_ serverId: String, _ pipelineId: String, _ startListening: Bool)
case nothing
public var id: String {
switch self {
case .default:
return "default"
case .moreInfoDialog:
return "moreInfoDialog"
case .navigate:
return "navigate"
case .runScript:
return "runScript"
case .assist:
return "assist"
case .nothing:
return "nothing"
}
}
public var name: String {
switch self {
case .default:
return L10n.Widgets.Action.Name.default
case .moreInfoDialog:
return L10n.Widgets.Action.Name.moreInfoDialog
case .navigate:
return L10n.Widgets.Action.Name.navigate
case .runScript:
return L10n.Widgets.Action.Name.runScript
case .assist:
return L10n.Widgets.Action.Name.assist
case .nothing:
return L10n.Widgets.Action.Name.nothing
}
}
}
public extension MagicItem {
// currentItemState is used only for lock domain since it can't be toggled
func execute(
on server: Server,
source: AppTriggerSource,
currentItemState: String = "",
completion: @escaping (Bool) -> Void
) {
do {
if let request: Promise<Void> = try {
switch type {
case .script:
let domain = Domain.script.rawValue
let service = id.replacingOccurrences(of: "\(domain).", with: "")
return Current.api(for: server)?.CallService(
domain: domain,
service: service,
serviceData: [:],
triggerSource: source,
shouldLog: true
)
case .action:
return Current.api(for: server)?
.HandleAction(actionID: id, source: source)
case .scene:
let domain = Domain.scene.rawValue
return Current.api(for: server)?.CallService(
domain: domain,
service: Service.turnOn.rawValue,
serviceData: [
"entity_id": id,
],
triggerSource: source,
shouldLog: true
)
case .entity:
guard let domain else {
throw MagicItemError.unknownDomain
}
return executeActionForDomainType(
server: server,
domain: domain,
entityId: id,
state: currentItemState
)
case .folder:
// Folders don't execute actions
return nil
}
}() {
request.pipe(to: { result in
switch result {
case .fulfilled:
Current.Log.verbose("Success executing magic item \(id)")
completion(true)
case let .rejected(error):
Current.Log.error("Error while executing magic item \(id): \(error.localizedDescription)")
completion(false)
}
})
} else {
Current.Log.error("No request available while executing magic item \(id)")
}
} catch {
Current.Log.error("Error while executing magic item (2): \(error.localizedDescription)")
completion(false)
}
}
private func executeActionForDomainType(
server: Server,
domain: Domain,
entityId: String,
state: String
) -> Promise<Void> {
var request: HATypedRequest<HAResponseVoid>?
// Lock requires state-aware action
if domain == .lock {
guard let state = Domain.State(rawValue: state) else { return .value }
switch state {
case .unlocking, .unlocked, .opening:
request = .lockLock(entityId: entityId)
case .locked, .locking:
request = .unlockLock(entityId: entityId)
default:
break
}
} else {
// Use domain's main action for all other domains
request = .executeMainAction(domain: domain, entityId: entityId)
}
if let request, let connection = Current.api(for: server)?.connection {
return connection.send(request).promise
.map { _ in () }
} else {
return .value
}
}
}