LiveActivityBridge.swift 9.5 KB

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