LiveActivityBridge.swift 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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
  60. .addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: nil) { [weak self] _ in
  61. self?.forceActivityUpdate()
  62. }
  63. notificationCenter
  64. .addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil) { [weak self] _ in
  65. self?.forceActivityUpdate()
  66. }
  67. }
  68. private func registerHandler() {
  69. // 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
  70. coreDataPublisher?.filterByEntityName("OverrideStored").sink { [weak self] _ in
  71. guard let self = self else { return }
  72. self.overridesDidUpdate()
  73. }.store(in: &subscriptions)
  74. coreDataPublisher?.filterByEntityName("OrefDetermination").sink { [weak self] _ in
  75. guard let self = self else { return }
  76. self.cobOrIobDidUpdate()
  77. }.store(in: &subscriptions)
  78. }
  79. private func registerSubscribers() {
  80. glucoseStorage.updatePublisher
  81. .receive(on: DispatchQueue.global(qos: .background))
  82. .sink { [weak self] _ in
  83. guard let self = self else { return }
  84. self.setupGlucoseArray()
  85. }
  86. .store(in: &subscriptions)
  87. }
  88. @objc private func cobOrIobDidUpdate() {
  89. Task {
  90. await fetchAndMapDetermination()
  91. if let determination = determination {
  92. await self.pushDeterminationUpdate(determination)
  93. }
  94. }
  95. }
  96. private func overridesDidUpdate() {
  97. Task {
  98. await fetchAndMapOverride()
  99. if let determination = determination {
  100. await self.pushDeterminationUpdate(determination)
  101. }
  102. }
  103. }
  104. private func setupGlucoseArray() {
  105. Task {
  106. // Fetch and map glucose to GlucoseData struct
  107. await fetchAndMapGlucose()
  108. // Push the update to the Live Activity
  109. glucoseDidUpdate(glucoseFromPersistence ?? [])
  110. }
  111. }
  112. private func monitorForLiveActivityAuthorizationChanges() {
  113. Task {
  114. for await activityState in activityAuthorizationInfo.activityEnablementUpdates {
  115. if activityState != systemEnabled {
  116. await MainActor.run {
  117. systemEnabled = activityState
  118. }
  119. }
  120. }
  121. }
  122. }
  123. /// creates and tries to present a new activity update from the current GlucoseStorage values if live activities are enabled in settings
  124. /// Ends existing live activities if live activities are not enabled in settings
  125. private func forceActivityUpdate() {
  126. // just before app resigns active, show a new activity
  127. // only do this if there is no current activity or the current activity is older than 1h
  128. if settings.useLiveActivity {
  129. if currentActivity?.needsRecreation() ?? true
  130. {
  131. glucoseDidUpdate(glucoseFromPersistence ?? [])
  132. }
  133. } else {
  134. Task {
  135. await self.endActivity()
  136. }
  137. }
  138. }
  139. /// attempts to present this live activity state, creating a new activity if none exists yet
  140. @MainActor private func pushUpdate(_ state: LiveActivityAttributes.ContentState) async {
  141. // // End all activities that are not the current one
  142. for unknownActivity in Activity<LiveActivityAttributes>.activities
  143. .filter({ self.currentActivity?.activity.id != $0.id })
  144. {
  145. await unknownActivity.end(nil, dismissalPolicy: .immediate)
  146. }
  147. if let currentActivity = currentActivity {
  148. if currentActivity.needsRecreation(), UIApplication.shared.applicationState == .active {
  149. await endActivity()
  150. await pushUpdate(state)
  151. } else {
  152. let content = ActivityContent(
  153. state: state,
  154. staleDate: min(state.date, Date.now).addingTimeInterval(360) // 6 minutes in seconds
  155. )
  156. await currentActivity.activity.update(content)
  157. }
  158. } else {
  159. do {
  160. // always push a non-stale content as the first update
  161. // pushing a stale content as the frst content results in the activity not being shown at all
  162. // apparently this initial state is also what is shown after the live activity expires (after 8h)
  163. let expired = ActivityContent(
  164. state: LiveActivityAttributes.ContentState(
  165. bg: "--",
  166. direction: nil,
  167. change: "--",
  168. date: Date.now,
  169. highGlucose: settings.high,
  170. lowGlucose: settings.low,
  171. glucoseColorScheme: settings.glucoseColorScheme.rawValue,
  172. detailedViewState: nil,
  173. isInitialState: true
  174. ),
  175. staleDate: Date.now.addingTimeInterval(60)
  176. )
  177. // Request a new activity
  178. let activity = try Activity.request(
  179. attributes: LiveActivityAttributes(startDate: Date.now),
  180. content: expired,
  181. pushType: nil
  182. )
  183. currentActivity = ActiveActivity(activity: activity, startDate: Date.now)
  184. // then show the actual content
  185. await pushUpdate(state)
  186. } catch {
  187. print("Activity creation error: \(error)")
  188. }
  189. }
  190. }
  191. @MainActor private func pushDeterminationUpdate(_ determination: DeterminationData) async {
  192. guard let latestGlucose = latestGlucose else { return }
  193. let content = LiveActivityAttributes.ContentState(
  194. new: latestGlucose,
  195. prev: latestGlucose,
  196. units: settings.units,
  197. chart: glucoseFromPersistence ?? [],
  198. settings: settings,
  199. determination: determination,
  200. override: isOverridesActive
  201. )
  202. if let content = content {
  203. await pushUpdate(content)
  204. }
  205. }
  206. /// ends all live activities immediateny
  207. private func endActivity() async {
  208. if let currentActivity {
  209. await currentActivity.activity.end(nil, dismissalPolicy: .immediate)
  210. self.currentActivity = nil
  211. }
  212. // end any other activities
  213. for unknownActivity in Activity<LiveActivityAttributes>.activities {
  214. await unknownActivity.end(nil, dismissalPolicy: .immediate)
  215. }
  216. }
  217. }
  218. @available(iOS 16.2, *)
  219. extension LiveActivityBridge {
  220. func glucoseDidUpdate(_ glucose: [GlucoseData]) {
  221. guard settings.useLiveActivity else {
  222. if currentActivity != nil {
  223. Task {
  224. await self.endActivity()
  225. }
  226. }
  227. return
  228. }
  229. // backfill latest glucose if contained in this update
  230. if glucose.count > 1 {
  231. latestGlucose = glucose.dropFirst().first
  232. }
  233. defer {
  234. self.latestGlucose = glucose.first
  235. }
  236. guard let bg = glucose.first else {
  237. return
  238. }
  239. if let determination = determination {
  240. let content = LiveActivityAttributes.ContentState(
  241. new: bg,
  242. prev: latestGlucose,
  243. units: settings.units,
  244. chart: glucose,
  245. settings: settings,
  246. determination: determination,
  247. override: isOverridesActive
  248. )
  249. if let content = content {
  250. Task {
  251. await self.pushUpdate(content)
  252. }
  253. }
  254. }
  255. }
  256. }