-
Notifications
You must be signed in to change notification settings - Fork 265
Expand file tree
/
Copy pathOneSignalLiveActivitiesManagerImpl.swift
More file actions
300 lines (257 loc) · 14.7 KB
/
Copy pathOneSignalLiveActivitiesManagerImpl.swift
File metadata and controls
300 lines (257 loc) · 14.7 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
/*
Modified MIT License
Copyright 2024 OneSignal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
2. All copies of substantial portions of the Software may only be used in connection
with services provided by OneSignal.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// Effectively blanks out this file for Mac Catalyst
#if targetEnvironment(macCatalyst)
#else
import OneSignalCore
import OneSignalOSCore
import ActivityKit
enum LiveActivitiesError: Error {
case invalidActivityType(String)
}
@objc(OneSignalLiveActivitiesManagerImpl)
public class OneSignalLiveActivitiesManagerImpl: NSObject, OSLiveActivities {
private static let _executor: OSLiveActivitiesExecutor = OSLiveActivitiesExecutor(requestDispatch: DispatchQueue(label: "OneSignal.LiveActivities"))
@objc
public static func liveActivities() -> AnyClass {
return OneSignalLiveActivitiesManagerImpl.self
}
@objc
public static func start() {
_executor.start()
}
@objc
public static func enter(_ activityId: String, withToken: String) {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignal.LiveActivities enter called with activityId: \(activityId) token: \(withToken)")
_executor.append(OSRequestSetUpdateToken(key: activityId, token: withToken))
}
@objc
public static func exit(_ activityId: String) {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignal.LiveActivities leave called with activityId: \(activityId)")
_executor.append(OSRequestRemoveUpdateToken(key: activityId))
}
@objc
@available(iOS 17.2, *)
public static func setPushToStartToken(_ activityType: String, withToken: String) throws {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignal.LiveActivities setStartToken called with activityType: \(activityType) token: \(withToken)")
guard let activityType = activityType.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlUserAllowed) else {
throw LiveActivitiesError.invalidActivityType("Cannot translate activity type to url encoded string.")
}
_executor.append(OSRequestSetStartToken(key: activityType, token: withToken))
}
@objc
@available(iOS 17.2, *)
public static func removePushToStartToken(_ activityType: String) throws {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignal.LiveActivities removeStartToken called with activityType: \(activityType)")
guard let activityType = activityType.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlUserAllowed) else {
throw LiveActivitiesError.invalidActivityType("Cannot translate activity type to url encoded string.")
}
_executor.append(OSRequestRemoveStartToken(key: "\(activityType)"))
}
@available(iOS 17.2, *)
public static func setPushToStartToken<T>(_ activityType: T.Type, withToken: String) where T: ActivityAttributes {
do {
try OneSignalLiveActivitiesManagerImpl.setPushToStartToken("\(activityType)", withToken: withToken)
} catch LiveActivitiesError.invalidActivityType(let message) {
// This should never happen, because a struct name should always be URL encodable.
OneSignalLog.onesignalLog(.LL_ERROR, message: message)
} catch {
// This should never happen.
OneSignalLog.onesignalLog(.LL_ERROR, message: "Could not set push to start token")
}
}
@available(iOS 17.2, *)
public static func removePushToStartToken<T>(_ activityType: T.Type) where T: ActivityAttributes {
do {
try OneSignalLiveActivitiesManagerImpl.removePushToStartToken("\(activityType)")
} catch LiveActivitiesError.invalidActivityType(let message) {
// This should never happen, because a struct name should always be URL encodable.
OneSignalLog.onesignalLog(.LL_ERROR, message: message)
} catch {
// This should never happen.
OneSignalLog.onesignalLog(.LL_ERROR, message: "Could not set push to start token")
}
}
@objc
public static func enter(_ activityId: String, withToken: String, withSuccess: OSResultSuccessBlock?, withFailure: OSFailureBlock?) {
enter(activityId, withToken: withToken)
if withSuccess != nil {
DispatchQueue.main.async {
withSuccess!([AnyHashable: Any]())
}
}
}
@objc
public static func exit(_ activityId: String, withSuccess: OSResultSuccessBlock?, withFailure: OSFailureBlock?) {
exit(activityId)
if withSuccess != nil {
DispatchQueue.main.async {
withSuccess!([AnyHashable: Any]())
}
}
}
@available(iOS 16.1, *)
public static func setup<Attributes: OneSignalLiveActivityAttributes>(_ activityType: Attributes.Type, options: LiveActivitySetupOptions? = nil) {
if #available(iOS 17.2, *) {
listenForPushToStart(activityType, options: options)
}
listenForActivity(activityType, options: options)
}
@objc
@available(iOS 16.1, *)
public static func setupDefault(options: LiveActivitySetupOptions? = nil) {
setup(DefaultLiveActivityAttributes.self, options: options)
}
@objc
@available(iOS 16.1, *)
public static func startDefault(_ activityId: String, attributes: [String: Any], content: [String: Any]) {
let oneSignalAttribute = OneSignalLiveActivityAttributeData.create(activityId: activityId)
var attributeData = [String: AnyCodable]()
for attribute in attributes {
attributeData.updateValue(AnyCodable(attribute.value), forKey: attribute.key)
}
var contentData = [String: AnyCodable]()
for contentItem in content {
contentData.updateValue(AnyCodable(contentItem.value), forKey: contentItem.key)
}
let attributes = DefaultLiveActivityAttributes(data: attributeData, onesignal: oneSignalAttribute)
let contentState = DefaultLiveActivityAttributes.ContentState(data: contentData)
do {
_ = try Activity<DefaultLiveActivityAttributes>.request(
attributes: attributes,
contentState: contentState,
pushType: .token)
} catch let error {
OneSignalLog.onesignalLog(.LL_DEBUG, message: "Cannot start default live activity: " + error.localizedDescription)
}
}
@available(iOS 17.2, *)
private static func listenForPushToStart<Attributes: OneSignalLiveActivityAttributes>(_ activityType: Attributes.Type, options: LiveActivitySetupOptions? = nil) {
if options == nil || options!.enablePushToStart {
Task {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignal.LiveActivities listening for pushToStart on: \(activityType)")
for try await data in Activity<Attributes>.pushToStartTokenUpdates {
let token = data.map {String(format: "%02x", $0)}.joined()
OneSignalLiveActivitiesManagerImpl.setPushToStartToken(Attributes.self, withToken: token)
}
}
}
}
@available(iOS 16.1, *)
private static func listenForActivity<Attributes: OneSignalLiveActivityAttributes>(_ activityType: Attributes.Type, options: LiveActivitySetupOptions? = nil) {
/*
Apple has confirmed that when using push-to-start, it is best to check both `Activity<...>.activities` in addition
`Activity<...>.activityUpdates` --- because your app may need to launch in the background and the launch time may end
up being slower than the new values come in. In those cases, your task on the update sequence may start listening after
the initial values were already provided.
*/
// Establish listeners for activity (if any exist)
for activity in Activity<Attributes>.activities {
listenForActivityStateUpdates(activityType, activity: activity, options: options)
listenForActivityPushToUpdate(activityType, activity: activity, options: options)
if #available(iOS 16.2, *) {
listenForContentUpdates(activityType, activity: activity)
}
}
// Establish listeners for activity updates
Task {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignal.LiveActivities listening for activity on: \(activityType)")
for await activity in Activity<Attributes>.activityUpdates {
if #available(iOS 16.2, *) {
// if there's already an activity with the same OneSignal activityId, dismiss it before
// listening for the new activity's events.
for otherActivity in Activity<Attributes>.activities {
if activity.id != otherActivity.id && otherActivity.attributes.onesignal.activityId == activity.attributes.onesignal.activityId {
OneSignalLog.onesignalLog(.LL_DEBUG, message: "OneSignal.LiveActivities dismissing other activity: \(activityType):\(otherActivity.attributes.onesignal.activityId):\(otherActivity.id)")
await otherActivity.end(nil, dismissalPolicy: ActivityUIDismissalPolicy.immediate)
}
}
}
listenForActivityStateUpdates(activityType, activity: activity, options: options)
listenForActivityPushToUpdate(activityType, activity: activity, options: options)
if #available(iOS 16.2, *) {
listenForContentUpdates(activityType, activity: activity)
}
}
}
}
@available(iOS 16.1, *)
private static func listenForActivityStateUpdates<Attributes: OneSignalLiveActivityAttributes>(_ activityType: Attributes.Type, activity: Activity<Attributes>, options: LiveActivitySetupOptions? = nil) {
// listen for activity dismisses so we can forget about the token
Task {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignal.LiveActivities listening for state update on: \(activityType):\(activity.attributes.onesignal.activityId):\(activity.id)")
for await activityState in activity.activityStateUpdates {
switch activityState {
case .dismissed:
OneSignalLiveActivitiesManagerImpl.exit(activity.attributes.onesignal.activityId)
case .active: break
case .ended: break
case .stale: break
default: break
}
}
}
}
@available(iOS 16.1, *)
private static func listenForActivityPushToUpdate<Attributes: OneSignalLiveActivityAttributes>(_ activityType: Attributes.Type, activity: Activity<Attributes>, options: LiveActivitySetupOptions? = nil) {
if options == nil || options!.enablePushToUpdate {
/*
Apple has confirmed that when using push-to-start, it is best to check both `Activity<...>.pushToken` in addition
`Activity<...>.pushTokenUpdates` --- because your app may need to launch in the background and the launch time may end
up being slower than the new values come in. In those cases, your task on the update sequence may start listening after
the initial values were already provided.
*/
// Set the initial pushToken (if one exists)
if let pushToken = activity.pushToken {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignal.LiveActivities enter with existing pushToken for: \(activityType):\(activity.attributes.onesignal.activityId):\(activity.id)")
let token = pushToken.map {String(format: "%02x", $0)}.joined()
OneSignalLiveActivitiesManagerImpl.enter(activity.attributes.onesignal.activityId, withToken: token)
}
// listen for activity update token updates so we can tell OneSignal how to update the activity
Task {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignal.LiveActivities listening for pushToUpdate on: \(activityType):\(activity.attributes.onesignal.activityId):\(activity.id)")
for await pushToken in activity.pushTokenUpdates {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignal.LiveActivities pushTokenUpdates observed for: \(activityType):\(activity.attributes.onesignal.activityId):\(activity.id)")
let token = pushToken.map {String(format: "%02x", $0)}.joined()
OneSignalLiveActivitiesManagerImpl.enter(activity.attributes.onesignal.activityId, withToken: token)
}
}
}
}
@available(iOS 16.2, *)
private static func listenForContentUpdates<Attributes: OneSignalLiveActivityAttributes>(_ activityType: Attributes.Type, activity: Activity<Attributes>) {
Task {
for await content in activity.contentUpdates {
// Don't track a live activity started / updated "in app" without a notification
if let notificationId = activity.content.state.onesignal?.notificationId {
OneSignalLiveActivitiesManagerImpl.addReceiveReceipts(notificationId: notificationId, activityType: "\(activityType)", activityId: activity.attributes.onesignal.activityId)
}
}
}
}
private static func addReceiveReceipts(notificationId: String, activityType: String, activityId: String) {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignal.LiveActivities addReceiveReceipts called with notificationId: \(notificationId), activityType: \(activityType), activityId: \(activityId)")
let req = OSRequestLiveActivityReceiveReceipts(key: notificationId, activityType: activityType, activityId: activityId)
_executor.append(req)
}
}
#endif