forked from home-assistant/iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExtensionDelegate.swift
337 lines (274 loc) · 13.7 KB
/
ExtensionDelegate.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
import ClockKit
import Communicator
import PromiseKit
import RealmSwift
import Shared
import UserNotifications
import WatchKit
import XCGLogger
class ExtensionDelegate: NSObject, WKExtensionDelegate {
// MARK: Fileprivate
fileprivate var watchConnectivityBackgroundPromise: Guarantee<Void>
fileprivate var watchConnectivityBackgroundSeal: (()) -> Void
fileprivate var watchConnectivityWatchdogTimer: Timer?
override init() {
(self.watchConnectivityBackgroundPromise, self.watchConnectivityBackgroundSeal) = Guarantee<Void>.pending()
super.init()
}
// MARK: - WKExtensionDelegate -
func applicationDidFinishLaunching() {
// Perform any final initialization of your application.
Current.Log.verbose("didFinishLaunching")
UNUserNotificationCenter.current().delegate = self
var opts: UNAuthorizationOptions = [.alert, .badge, .sound, .criticalAlert, .providesAppNotificationSettings]
if #available(watchOS 6.0, *) {
opts.insert(.announcement)
}
if #available(watchOSApplicationExtension 6.0, *) {
WKExtension.shared().registerForRemoteNotifications()
}
UNUserNotificationCenter.current().requestAuthorization(options: opts) { granted, error in
Current.Log.verbose("Requested notifications access \(granted), \(String(describing: error))")
}
setupWatchCommunicator()
// schedule the next background refresh
Current.backgroundRefreshScheduler.schedule().cauterize()
}
func applicationDidBecomeActive() {
// Restart any tasks that were paused (or not yet started) while the application was inactive.
// If the application was previously in the background, optionally refresh the user interface.
Current.Log.verbose("didBecomeActive")
}
func applicationWillResignActive() {
// Sent when the application is about to move from active to inactive state.
// This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message)
// or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, etc.
Current.Log.verbose("willResignActive")
Current.backgroundRefreshScheduler.schedule().cauterize()
}
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
// Sent when the system needs to launch the application in the background to process tasks.
// Tasks arrive in a set, so loop through and process each one.
for task in backgroundTasks {
// Use a switch statement to check the task type
switch task {
case let backgroundTask as WKApplicationRefreshBackgroundTask:
// Be sure to complete the background task once you’re done.
Current.Log.verbose("WKApplicationRefreshBackgroundTask received")
firstly {
when(fulfilled: Current.apis.map { $0.updateComplications(passively: true) })
}.ensureThen {
Current.backgroundRefreshScheduler.schedule()
}.ensure {
backgroundTask.setTaskCompletedWithSnapshot(false)
}.cauterize()
case let snapshotTask as WKSnapshotRefreshBackgroundTask:
// Snapshot tasks have a unique completion call, make sure to set your expiration date
snapshotTask.setTaskCompleted(
restoredDefaultState: true,
estimatedSnapshotExpiration: Date.distantFuture,
userInfo: nil
)
case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
enqueueForCompletion(connectivityTask)
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
// Be sure to complete the URL session task once you’re done.
Current.webhooks.handleBackground(for: urlSessionTask.sessionIdentifier) {
Current.backgroundRefreshScheduler.schedule().done {
urlSessionTask.setTaskCompletedWithSnapshot(false)
}
}
case let relevantShortcutTask as WKRelevantShortcutRefreshBackgroundTask:
// Be sure to complete the relevant-shortcut task once you're done.
relevantShortcutTask.setTaskCompletedWithSnapshot(false)
case let intentDidRunTask as WKIntentDidRunRefreshBackgroundTask:
// Be sure to complete the intent-did-run task once you're done.
intentDidRunTask.setTaskCompletedWithSnapshot(false)
default:
// make sure to complete unhandled task types
task.setTaskCompletedWithSnapshot(false)
}
}
}
// Triggered when a complication is tapped
func handleUserActivity(_ userInfo: [AnyHashable: Any]?) {
let complication: WatchComplication?
if #available(watchOS 7, *),
let identifier = userInfo?[CLKLaunchedComplicationIdentifierKey] as? String,
identifier != CLKDefaultComplicationIdentifier {
complication = Current.realm().object(ofType: WatchComplication.self, forPrimaryKey: identifier)
} else if let date = userInfo?[CLKLaunchedTimelineEntryDateKey] as? Date,
let clkFamily = date.complicationFamilyFromEncodedDate {
let family = ComplicationGroupMember(family: clkFamily)
complication = Current.realm().object(ofType: WatchComplication.self, forPrimaryKey: family.rawValue)
} else {
complication = nil
}
if let complication = complication {
Current.Log.info("launched for \(complication.identifier) of family \(complication.Family)")
} else {
Current.Log.verbose("unknown or no complication launched the app")
}
}
func setupWatchCommunicator() {
// This directly mutates the data structure for observations to avoid race conditions.
Communicator.State.observations.store[.init(queue: .main)] = { state in
Current.Log.verbose("Activation state changed: \(state)")
_ = HomeAssistantAPI.SyncWatchContext()
}
Reachability.observations.store[.init(queue: .main)] = { reachability in
Current.Log.verbose("Reachability changed: \(reachability)")
}
InteractiveImmediateMessage.observations.store[.init(queue: .main)] = { message in
Current.Log.verbose("Received message: \(message.identifier)")
self.endWatchConnectivityBackgroundTaskIfNecessary()
}
ImmediateMessage.observations.store[.init(queue: .main)] = { message in
Current.Log.verbose("Received message: \(message.identifier)")
self.endWatchConnectivityBackgroundTaskIfNecessary()
}
GuaranteedMessage.observations.store[.init(queue: .main)] = { message in
Current.Log.verbose("Received guaranteed message! \(message)")
self.endWatchConnectivityBackgroundTaskIfNecessary()
}
Blob.observations.store[.init(queue: .main)] = { blob in
Current.Log.verbose("Received blob: \(blob.identifier)")
self.endWatchConnectivityBackgroundTaskIfNecessary()
}
Context.observations.store[.init(queue: .main)] = { [weak self] context in
Current.Log.verbose("Received context: \(context)")
self?.updateContext(context.content)
}
ComplicationInfo.observations.store[.init(queue: .main)] = { complicationInfo in
Current.Log.verbose("Received complication info: \(complicationInfo)")
self.updateComplications()
}
_ = Communicator.shared
}
private func enqueueForCompletion(_ task: WKWatchConnectivityRefreshBackgroundTask) {
DispatchQueue.main.async { [self] in
guard Communicator.shared.hasPendingDataToBeReceived else {
// nothing else to be received
task.setTaskCompletedWithSnapshot(false)
return
}
// wait for it to send the next set of data
watchConnectivityBackgroundPromise.done {
task.setTaskCompletedWithSnapshot(false)
}
if watchConnectivityWatchdogTimer == nil || watchConnectivityWatchdogTimer?.isValid == false {
// 10s should be more than enough time, and the system timer's at 15s (last tested watchOS 7)
let timer = Timer.scheduledTimer(
withTimeInterval: 10.0,
repeats: true
) { [weak self] _ in
// we endeavor to not need this timer, but apple's api is so difficult to micromanage
// that it's just safer to guess and check every few seconds
Current.Log.info("ending background task due to our own watchdog timer")
self?.endWatchConnectivityBackgroundTaskIfNecessary()
}
watchConnectivityBackgroundPromise.done {
timer.invalidate()
}
watchConnectivityWatchdogTimer = timer
}
}
}
private func endWatchConnectivityBackgroundTaskIfNecessary() {
DispatchQueue.main.async { [self] in
guard !Communicator.shared.hasPendingDataToBeReceived else { return }
// complete the current one
watchConnectivityBackgroundSeal(())
// and set up a new one for the next chain of updates
(watchConnectivityBackgroundPromise, watchConnectivityBackgroundSeal) = Guarantee<Void>.pending()
}
}
private func updateContext(_ content: Content) {
let realm = Current.realm()
if let servers = content["servers"] as? Data {
Current.servers.restoreState(servers)
}
if let actionsDictionary = content["actions"] as? [[String: Any]] {
let actions = actionsDictionary.compactMap { try? Action(JSON: $0) }
Current.Log.verbose("Updating actions from context \(actions)")
realm.reentrantWrite {
realm.delete(realm.objects(Action.self))
realm.add(actions, update: .all)
}
}
if let complicationsDictionary = content["complications"] as? [[String: Any]] {
let complications = complicationsDictionary.compactMap { try? WatchComplication(JSON: $0) }
Current.Log.verbose("Updating complications from context \(complications)")
realm.reentrantWrite {
realm.delete(realm.objects(WatchComplication.self))
realm.add(complications, update: .all)
}
}
updateComplications()
}
private var isUpdatingComplications = false
private func updateComplications() {
// avoid double-updating due to e.g. complication info update request
guard !isUpdatingComplications else { return }
isUpdatingComplications = true
firstly {
when(fulfilled: Current.apis.map { $0.updateComplications(passively: true) })
}.ensure { [self] in
isUpdatingComplications = false
}.ensure { [self] in
endWatchConnectivityBackgroundTaskIfNecessary()
}.cauterize()
}
func didRegisterForRemoteNotifications(withDeviceToken deviceToken: Data) {
let apnsToken = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
Current.Log.verbose("Successfully registered for push notifications! APNS token: \(apnsToken)")
}
func didFailToRegisterForRemoteNotificationsWithError(_ error: Error) {
Current.Log.error("Error when trying to register for push: \(error)")
}
}
extension ExtensionDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
completionHandler([.alert, .badge, .sound])
}
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void
) {
guard let info = HomeAssistantAPI.PushActionInfo(response: response),
let server = Current.servers.server(for: response.notification.request.content) else {
completionHandler()
return
}
firstly { () -> Promise<Void> in
let (promise, seal) = Promise<Void>.pending()
if Communicator.shared.currentReachability == .immediatelyReachable {
Current.Log.info("sending via phone")
Communicator.shared.send(.init(
identifier: "PushAction",
content: ["PushActionInfo": info.toJSON(), "Server": server.identifier.rawValue],
reply: { message in
Current.Log.verbose("Received reply dictionary \(message)")
seal.fulfill(())
}
), errorHandler: { error in
Current.Log.error("Received error when sending immediate message \(error)")
seal.reject(error)
})
} else {
Current.Log.info("sending via local")
Current.api(for: server).handlePushAction(for: info)
.pipe(to: seal.resolve)
}
return promise
}.ensure {
completionHandler()
}.cauterize()
}
}