LiveActivityBridge.swift 12 KB

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