LiveActivityBridge.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import ActivityKit
  2. import Combine
  3. import CoreData
  4. import Foundation
  5. import Swinject
  6. import UIKit
  7. @available(iOS 16.2, *) private struct ActiveActivity {
  8. let activity: Activity<LiveActivityAttributes>
  9. let startDate: Date
  10. func needsRecreation() -> Bool {
  11. switch activity.activityState {
  12. case .dismissed,
  13. .ended,
  14. .stale:
  15. return true
  16. case .active: break
  17. @unknown default:
  18. return true
  19. }
  20. return -startDate.timeIntervalSinceNow >
  21. TimeInterval(60 * 60)
  22. }
  23. }
  24. @available(iOS 16.2, *) final class LiveActivityBridge: Injectable, ObservableObject
  25. {
  26. @Injected() private var settingsManager: SettingsManager!
  27. @Injected() private var broadcaster: Broadcaster!
  28. @Injected() private var storage: FileStorage!
  29. @Injected() private var glucoseStorage: GlucoseStorage!
  30. private let activityAuthorizationInfo = ActivityAuthorizationInfo()
  31. @Published private(set) var systemEnabled: Bool
  32. private var settings: FreeAPSSettings {
  33. settingsManager.settings
  34. }
  35. var determination: DeterminationData?
  36. private var currentActivity: ActiveActivity?
  37. private var latestGlucose: GlucoseData?
  38. var glucoseFromPersistence: [GlucoseData]?
  39. var isOverridesActive: OverrideData?
  40. let context = CoreDataStack.shared.newTaskContext()
  41. private var coreDataPublisher: AnyPublisher<Set<NSManagedObject>, Never>?
  42. private var subscriptions = Set<AnyCancellable>()
  43. init(resolver: Resolver) {
  44. coreDataPublisher =
  45. changedObjectsOnManagedObjectContextDidSavePublisher()
  46. .receive(on: DispatchQueue.global(qos: .background))
  47. .share()
  48. .eraseToAnyPublisher()
  49. systemEnabled = activityAuthorizationInfo.areActivitiesEnabled
  50. injectServices(resolver)
  51. setupNotifications()
  52. registerSubscribers()
  53. registerHandler()
  54. monitorForLiveActivityAuthorizationChanges()
  55. setupGlucoseArray()
  56. }
  57. private func setupNotifications() {
  58. let notificationCenter = Foundation.NotificationCenter.default
  59. notificationCenter.addObserver(self, selector: #selector(cobOrIobDidUpdate), name: .didUpdateCobIob, object: nil)
  60. notificationCenter
  61. .addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: nil) { [weak self] _ in
  62. self?.forceActivityUpdate()
  63. }
  64. notificationCenter
  65. .addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil) { [weak self] _ in
  66. self?.forceActivityUpdate()
  67. }
  68. }
  69. private func registerHandler() {
  70. // Since we are only using this info to show if an Override is active or not in the Live Activity it is enough to observe only the 'OverrideStored' Entity
  71. coreDataPublisher?.filterByEntityName("OverrideStored").sink { [weak self] _ in
  72. guard let self = self else { return }
  73. self.overridesDidUpdate()
  74. }.store(in: &subscriptions)
  75. }
  76. private func registerSubscribers() {
  77. glucoseStorage.updatePublisher
  78. .receive(on: DispatchQueue.global(qos: .background))
  79. .sink { [weak self] _ in
  80. guard let self = self else { return }
  81. self.setupGlucoseArray()
  82. }
  83. .store(in: &subscriptions)
  84. }
  85. @objc private func cobOrIobDidUpdate() {
  86. Task {
  87. await fetchAndMapDetermination()
  88. if let determination = determination {
  89. await self.pushDeterminationUpdate(determination)
  90. }
  91. }
  92. }
  93. @objc private func overridesDidUpdate() {
  94. Task {
  95. await fetchAndMapOverride()
  96. if let determination = determination {
  97. await self.pushDeterminationUpdate(determination)
  98. }
  99. }
  100. }
  101. private func setupGlucoseArray() {
  102. Task {
  103. // Fetch and map glucose to GlucoseData struct
  104. await fetchAndMapGlucose()
  105. // Fetch and map Determination to DeterminationData struct
  106. await fetchAndMapDetermination()
  107. // Fetch and map Override to OverrideData struct
  108. /// shows if there is an active Override
  109. await fetchAndMapOverride()
  110. // Push the update to the Live Activity
  111. glucoseDidUpdate(glucoseFromPersistence ?? [])
  112. }
  113. }
  114. private func monitorForLiveActivityAuthorizationChanges() {
  115. Task {
  116. for await activityState in activityAuthorizationInfo.activityEnablementUpdates {
  117. if activityState != systemEnabled {
  118. await MainActor.run {
  119. systemEnabled = activityState
  120. }
  121. }
  122. }
  123. }
  124. }
  125. /// creates and tries to present a new activity update from the current GlucoseStorage values if live activities are enabled in settings
  126. /// Ends existing live activities if live activities are not enabled in settings
  127. private func forceActivityUpdate() {
  128. // just before app resigns active, show a new activity
  129. // only do this if there is no current activity or the current activity is older than 1h
  130. if settings.useLiveActivity {
  131. if currentActivity?.needsRecreation() ?? true
  132. {
  133. glucoseDidUpdate(glucoseFromPersistence ?? [])
  134. }
  135. } else {
  136. Task {
  137. await self.endActivity()
  138. }
  139. }
  140. }
  141. /// attempts to present this live activity state, creating a new activity if none exists yet
  142. @MainActor private func pushUpdate(_ state: LiveActivityAttributes.ContentState) async {
  143. // // End all activities that are not the current one
  144. for unknownActivity in Activity<LiveActivityAttributes>.activities
  145. .filter({ self.currentActivity?.activity.id != $0.id })
  146. {
  147. await unknownActivity.end(nil, dismissalPolicy: .immediate)
  148. }
  149. if let currentActivity = currentActivity {
  150. if currentActivity.needsRecreation(), UIApplication.shared.applicationState == .active {
  151. await endActivity()
  152. await pushUpdate(state)
  153. } else {
  154. let content = ActivityContent(
  155. state: state,
  156. staleDate: min(state.date, Date.now).addingTimeInterval(360) // 6 minutes in seconds
  157. )
  158. await currentActivity.activity.update(content)
  159. }
  160. } else {
  161. do {
  162. // always push a non-stale content as the first update
  163. // pushing a stale content as the frst content results in the activity not being shown at all
  164. // apparently this initial state is also what is shown after the live activity expires (after 8h)
  165. let expired = ActivityContent(
  166. state: LiveActivityAttributes.ContentState(
  167. bg: "--",
  168. direction: nil,
  169. change: "--",
  170. date: Date.now,
  171. highGlucose: settings.high,
  172. lowGlucose: settings.low,
  173. glucoseColorScheme: settings.glucoseColorScheme.rawValue,
  174. detailedViewState: nil,
  175. isInitialState: true
  176. ),
  177. staleDate: Date.now.addingTimeInterval(60)
  178. )
  179. // Request a new activity
  180. let activity = try Activity.request(
  181. attributes: LiveActivityAttributes(startDate: Date.now),
  182. content: expired,
  183. pushType: nil
  184. )
  185. currentActivity = ActiveActivity(activity: activity, startDate: Date.now)
  186. // then show the actual content
  187. await pushUpdate(state)
  188. } catch {
  189. print("Activity creation error: \(error)")
  190. }
  191. }
  192. }
  193. @MainActor private func pushDeterminationUpdate(_ determination: DeterminationData) async {
  194. guard let latestGlucose = latestGlucose else { return }
  195. let content = LiveActivityAttributes.ContentState(
  196. new: latestGlucose,
  197. prev: latestGlucose,
  198. units: settings.units,
  199. chart: glucoseFromPersistence ?? [],
  200. settings: settings,
  201. determination: determination,
  202. override: isOverridesActive
  203. )
  204. if let content = content {
  205. await pushUpdate(content)
  206. }
  207. }
  208. /// ends all live activities immediateny
  209. private func endActivity() async {
  210. if let currentActivity {
  211. await currentActivity.activity.end(nil, dismissalPolicy: .immediate)
  212. self.currentActivity = nil
  213. }
  214. // end any other activities
  215. for unknownActivity in Activity<LiveActivityAttributes>.activities {
  216. await unknownActivity.end(nil, dismissalPolicy: .immediate)
  217. }
  218. }
  219. }
  220. @available(iOS 16.2, *)
  221. extension LiveActivityBridge {
  222. func glucoseDidUpdate(_ glucose: [GlucoseData]) {
  223. guard settings.useLiveActivity else {
  224. if currentActivity != nil {
  225. Task {
  226. await self.endActivity()
  227. }
  228. }
  229. return
  230. }
  231. // backfill latest glucose if contained in this update
  232. if glucose.count > 1 {
  233. latestGlucose = glucose.dropFirst().first
  234. }
  235. defer {
  236. self.latestGlucose = glucose.first
  237. }
  238. guard let bg = glucose.first else {
  239. return
  240. }
  241. if let determination = determination {
  242. let content = LiveActivityAttributes.ContentState(
  243. new: bg,
  244. prev: latestGlucose,
  245. units: settings.units,
  246. chart: glucose,
  247. settings: settings,
  248. determination: determination,
  249. override: isOverridesActive
  250. )
  251. if let content = content {
  252. Task {
  253. await self.pushUpdate(content)
  254. }
  255. }
  256. }
  257. }
  258. }