LiveActivityBridge.swift 11 KB

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