-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathConnectionsSynchronizer.swift
288 lines (242 loc) · 11.8 KB
/
ConnectionsSynchronizer.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
//
// ConnectionsSynchronizer.swift
// IFTTT SDK
//
// Copyright © 2020 IFTTT. All rights reserved.
//
import Foundation
import UIKit
#if canImport(BackgroundTasks)
import BackgroundTasks
#endif
/// Controls current running state
enum RunState: String {
/// Currently stopped
case stopped = "stopped"
/// Currently running
case running = "running"
/// Unknown state
case unknown = "unknown"
}
public typealias BoolClosure = (Bool) -> Void
/// A set of application lifecycle events that are used to determine whether or not a synchronization should occur for that application lifecycle event.
public struct ApplicationLifecycleSynchronizationOptions: OptionSet, CustomStringConvertible {
public let rawValue: Int
/// Option for the UIApplication.didEnterBackground lifecycle event
public static let applicationDidEnterBackground = ApplicationLifecycleSynchronizationOptions(rawValue: 1 << 0)
/// Option for the UIApplication.didBecomeActive lifecycle event
public static let applicationDidBecomeActive = ApplicationLifecycleSynchronizationOptions(rawValue: 1 << 1)
/// Describes all supported lifecycle events
public static let all: ApplicationLifecycleSynchronizationOptions = [.applicationDidEnterBackground, .applicationDidBecomeActive]
/// Describes none of the application lifecycle events.
public static let none: ApplicationLifecycleSynchronizationOptions = []
public init(rawValue: Int) {
self.rawValue = rawValue
}
public var description: String {
var strings = [String]()
if self.contains(.applicationDidBecomeActive) {
strings.append("ApplicationDidBecomeActive")
}
if self.contains(.applicationDidEnterBackground) {
strings.append("ApplicationDidEnterBackground")
}
return strings.joined(separator: ", ")
}
}
/**
Handles synchronizing events from the SDK to the backend.
Uses the following mechanisms to do so:
- Background processing
- App lifecycle events
- App going to background
- App transitions to active state
- Other events specified by `SynchronizationSource`
*/
final class ConnectionsSynchronizer {
private let eventPublisher: EventPublisher<SynchronizationTriggerEvent>
private let location: LocationService
private let registry: ConnectionsRegistry
private let connectionsMonitor: ConnectionsMonitor
private let nativeServicesCoordinator: NativeServicesCoordinator
private let subscribers: [SynchronizationSubscriber]
private var scheduler: SynchronizationScheduler
private let permissionsRequestor: PermissionsRequestor
private let locationEventReporter: LocationEventReporter
private var state: RunState = .unknown
/// Private shared instance of connections synchronizer to use in starting/stopping synchronization
private static var _shared: ConnectionsSynchronizer!
/// Internal method to use in grabbing synchronizer instance.
static var shared: ConnectionsSynchronizer = {
if _shared == nil {
_shared = ConnectionsSynchronizer()
}
return _shared
}()
/// Creates an instance of the `ConnectionsSynchronizer`.
private init() {
let regionEventsRegistry = RegionEventsRegistry()
let connectionsRegistry = ConnectionsRegistry()
let permissionsRequestor = PermissionsRequestor(registry: connectionsRegistry)
let eventPublisher = EventPublisher<SynchronizationTriggerEvent>()
let regionsMonitor = RegionsMonitor(allowsBackgroundLocationUpdates: Bundle.main.backgroundLocationEnabled)
let locationSessionManager = RegionEventsSessionManager(networkController: .init(urlSession: .regionEventsURLSession),
regionEventsRegistry: regionEventsRegistry)
let locationEventReporter = LocationEventReporter(eventStore: .init())
let location = LocationService(
regionsMonitor: regionsMonitor,
regionEventsRegistry: regionEventsRegistry,
connectionsRegistry: connectionsRegistry,
sessionManager: locationSessionManager,
eventPublisher: eventPublisher,
eventReporter: locationEventReporter
)
let connectionsMonitor = ConnectionsMonitor(connectionsRegistry: connectionsRegistry)
let nativeServicesCoordinator = NativeServicesCoordinator(locationService: location,
permissionsRequestor: permissionsRequestor)
self.subscribers = [
connectionsMonitor,
location
]
self.registry = connectionsRegistry
self.nativeServicesCoordinator = nativeServicesCoordinator
self.eventPublisher = eventPublisher
self.location = location
self.connectionsMonitor = connectionsMonitor
self.permissionsRequestor = permissionsRequestor
self.locationEventReporter = locationEventReporter
let manager = SynchronizationManager(subscribers: subscribers)
self.scheduler = SynchronizationScheduler(manager: manager,
triggers: eventPublisher)
self.scheduler.onAuthenticationFailure = { [weak self] in
self?.deactivate()
ConnectButtonController.authenticationFailureHandler?()
}
setupRegistryNotifications()
location.start()
}
/// Can be used to force a synchronization.
///
/// - Parameters:
/// - isActivation: Is this forced synchronization due to connections being activated?
func update(isActivation: Bool = false) {
let source: SynchronizationSource = isActivation ? .connectionActivation: .forceUpdate
let event = SynchronizationTriggerEvent(source: source, completionHandler: nil)
eventPublisher.onNext(event)
}
/// Used to start the synchronization.
///
/// - Parameters:
/// - connections: An optional list of connections to start monitoring.
/// - lifecycleSynchronizationOptions: The app lifecycle synchronization options to use with the scheduler
func activate(connections ids: [String]? = nil, lifecycleSynchronizationOptions: ApplicationLifecycleSynchronizationOptions) {
start(lifecycleSynchronizationOptions: lifecycleSynchronizationOptions)
update(isActivation: true)
if let ids = ids {
registry.addConnections(with: ids, shouldNotify: false)
ConnectButtonController.synchronizationLog("Activated synchronization with connection ids: \(ids)")
} else {
ConnectButtonController.synchronizationLog("Activated synchronization")
}
}
/// Used to deactivate and stop synchronization.
func deactivate() {
ConnectButtonController.synchronizationLog("Deactivating synchronization...")
stop()
ConnectButtonController.synchronizationLog("Synchronization deactivated")
}
/// Call this to start the synchronization. Safe to be called multiple times.
private func start(lifecycleSynchronizationOptions: ApplicationLifecycleSynchronizationOptions) {
if state == .running { return }
performPreflightChecks()
Keychain.resetIfNecessary(force: false)
scheduler.start(lifecycleSynchronizationOptions: lifecycleSynchronizationOptions)
state = .running
}
/// Call this to stop the synchronization completely. Safe to be called multiple times.
private func stop() {
Keychain.resetIfNecessary(force: true)
scheduler.stop()
state = .stopped
}
/// Runs checks to see what capabilities the target currently has and prints messages to the console as required.
private func performPreflightChecks() {
if !Bundle.main.backgroundLocationEnabled {
ConnectButtonController.synchronizationLog("Background location not enabled for this target! Enable background location to allow location updates to be delivered to the app in the background.")
}
}
private func setupRegistryNotifications() {
NotificationCenter.default.addObserver(forName: .UpdateConnectionsName,
object: nil,
queue: nil) { [weak self] (notification) in
guard let userInfo = notification.userInfo,
let connectionUpdates = userInfo[ConnectionsRegistryNotification.UpdateConnectionsSetKey] as? [JSON] else { return }
let connectionsSet = Set(connectionUpdates
.compactMap { Connection.ConnectionStorage(json: $0) })
self?.nativeServicesCoordinator.processConnectionUpdate(connectionsSet)
}
}
/// Hook to be called when the application enters the background.
@objc private func applicationDidEnterBackground() {
scheduler.applicationDidEnterBackground()
}
/// Call this to setup background processes. Must be called before the application finishes launching.
func setupBackgroundProcess() {
scheduler.setupBackgroundProcess()
}
/// Call this to tear down background processes.
func teardownBackgroundProcess() {
scheduler.tearDownBackgroundProcess()
}
/// Call this to control whether or not the SDK should show permissions prompts.
func setShowPermissionsPrompts(_ showPermissionsPrompts: Bool) {
permissionsRequestor.showPermissionsPrompts = showPermissionsPrompts
}
func performFetchWithCompletionHandler(backgroundFetchCompletion: ((UIBackgroundFetchResult) -> Void)?) {
let event = SynchronizationTriggerEvent(source: .backgroundFetch) { (result, _) in
backgroundFetchCompletion?(result)
}
eventPublisher.onNext(event)
}
func didReceiveSilentRemoteNotification(backgroundFetchCompletion: ((UIBackgroundFetchResult) -> Void)?) {
let event = SynchronizationTriggerEvent(source: .silentPushNotification) { (result, _) in
backgroundFetchCompletion?(result)
}
eventPublisher.onNext(event)
}
func startBackgroundProcess(success: @escaping BoolClosure) {
let event = SynchronizationTriggerEvent(source: .externalBackgroundProcess) { (result, _) in
success(result != .failed)
}
eventPublisher.onNext(event)
}
func stopCurrentSynchronization() {
scheduler.stopCurrentSynchronization()
}
func setGeofencesEnabled(_ enabled: Bool, for connectionId: String) {
registry.updateConnectionGeofencesEnabled(enabled, connectionId: connectionId)
}
func geofencesEnabled(for connectionId: String) -> Bool {
return registry.geofencesEnabled(connectionId: connectionId)
}
func setDeveloperBackgroundProcessClosures(launchHandler: VoidClosure?, expirationHandler: VoidClosure?) {
scheduler.developerBackgroundProcessLaunchClosure = launchHandler
scheduler.developerBackgroundProcessExpirationClosure = expirationHandler
}
func setLocationEventReportedClosure(closure: LocationEventsClosure?) {
locationEventReporter.closure = closure
}
}
/// Handles coordination of native services with a set of connections
private class NativeServicesCoordinator {
private let locationService: LocationService
private let permissionsRequestor: PermissionsRequestor
init(locationService: LocationService, permissionsRequestor: PermissionsRequestor) {
self.locationService = locationService
self.permissionsRequestor = permissionsRequestor
}
func processConnectionUpdate(_ updates: Set<Connection.ConnectionStorage>) {
permissionsRequestor.processUpdate(with: updates)
locationService.updateRegions(from: updates)
}
}