LiveActivityBridge.swift 10 KB

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