LiveActivityBridge.swift 12 KB

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