JSONImporter.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import CoreData
  2. import Foundation
  3. /// Migration-specific errors that might happen during migration
  4. enum JSONImporterError: Error {
  5. case missingGlucoseValueInGlucoseEntry
  6. case missingCarbsValueInCarbEntry
  7. }
  8. // MARK: - JSONImporter Class
  9. /// Responsible for importing JSON data into Core Data.
  10. ///
  11. /// The importer handles two important states:
  12. /// - JSON files stored in the file system that contain data to import
  13. /// - Existing entries in CoreData that should not be duplicated
  14. ///
  15. /// Imports are performed when a JSON file exists. The importer checks
  16. /// CoreData for existing entries to avoid duplicating records from partial imports.
  17. class JSONImporter {
  18. private let context: NSManagedObjectContext
  19. private let coreDataStack: CoreDataStack
  20. /// Initializes the importer with a Core Data context.
  21. init(context: NSManagedObjectContext, coreDataStack: CoreDataStack) {
  22. self.context = context
  23. self.coreDataStack = coreDataStack
  24. }
  25. /// Reads and parses a JSON file from the file system.
  26. ///
  27. /// - Parameters:
  28. /// - url: The URL of the JSON file to read.
  29. /// - Returns: A decoded object of the specified type.
  30. /// - Throws: An error if the file cannot be read or decoded.
  31. private func readJsonFile<T: Decodable>(url: URL) throws -> T {
  32. let data = try Data(contentsOf: url)
  33. let decoder = JSONCoding.decoder
  34. return try decoder.decode(T.self, from: data)
  35. }
  36. /// Retrieves the set of dates for all glucose values currently stored in CoreData.
  37. ///
  38. /// - Parameters: the start and end dates to fetch glucose values, inclusive
  39. /// - Returns: A set of dates corresponding to existing glucose readings.
  40. /// - Throws: An error if the fetch operation fails.
  41. private func fetchGlucoseDates(start: Date, end: Date) async throws -> Set<Date> {
  42. let allReadings = try await coreDataStack.fetchEntitiesAsync(
  43. ofType: GlucoseStored.self,
  44. onContext: context,
  45. predicate: .predicateForDateBetween(start: start, end: end),
  46. key: "date",
  47. ascending: false
  48. ) as? [GlucoseStored] ?? []
  49. return Set(allReadings.compactMap(\.date))
  50. }
  51. /// Retrieves the set of timestamps for all carb entries currently stored in CoreData.
  52. ///
  53. /// - Parameters: the start and end dates to fetch carb entries, inclusive
  54. /// - Returns: A set of dates corresponding to existing carb entries.
  55. /// - Throws: An error if the fetch operation fails.
  56. private func fetchCarbEntryDates(start: Date, end: Date) async throws -> Set<Date> {
  57. let allCarbEntryDates = try await coreDataStack.fetchEntitiesAsync(
  58. ofType: CarbEntryStored.self,
  59. onContext: context,
  60. predicate: .predicateForDateBetween(start: start, end: end),
  61. key: "date",
  62. ascending: false
  63. ) as? [CarbEntryStored] ?? []
  64. return Set(allCarbEntryDates.compactMap(\.date))
  65. }
  66. /// Imports glucose history from a JSON file into CoreData.
  67. ///
  68. /// The function reads glucose data from the provided JSON file and stores new entries
  69. /// in CoreData, skipping entries with dates that already exist in the database.
  70. ///
  71. /// - Parameters:
  72. /// - url: The URL of the JSON file containing glucose history.
  73. /// - Throws:
  74. /// - JSONImporterError.missingGlucoseValueInGlucoseEntry if a glucose entry is missing a value.
  75. /// - An error if the file cannot be read or decoded.
  76. /// - An error if the CoreData operation fails.
  77. func importGlucoseHistory(url: URL, now: Date) async throws {
  78. let twentyFourHoursAgo = now - 24.hours.timeInterval
  79. let glucoseHistoryFull: [BloodGlucose] = try readJsonFile(url: url)
  80. let existingDates = try await fetchGlucoseDates(start: twentyFourHoursAgo, end: now)
  81. // only import glucose values from the last 24 hours that don't exist
  82. let glucoseHistory = glucoseHistoryFull
  83. .filter { $0.dateString >= twentyFourHoursAgo && $0.dateString <= now && !existingDates.contains($0.dateString) }
  84. // Create a background context for batch processing
  85. let backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  86. backgroundContext.parent = context
  87. try await backgroundContext.perform {
  88. for glucoseEntry in glucoseHistory {
  89. try glucoseEntry.store(in: backgroundContext)
  90. }
  91. try backgroundContext.save()
  92. }
  93. try await context.perform {
  94. try self.context.save()
  95. }
  96. }
  97. /// Imports carb history from a JSON file into CoreData.
  98. ///
  99. /// The function reads carb entries data from the provided JSON file and stores new entries
  100. /// in CoreData, skipping entries with dates that already exist in the database.
  101. /// We ignore all FPU entries (aka carb equivalents) when performing an import.
  102. ///
  103. /// - Parameters:
  104. /// - url: The URL of the JSON file containing glucose history.
  105. /// - now: The current datetime
  106. /// - Throws:
  107. /// - JSONImporterError.missingCarbsValueInCarbEntry if a carb entry is missing a `carbs: Decimal` value.
  108. /// - An error if the file cannot be read or decoded.
  109. /// - An error if the CoreData operation fails.
  110. func importCarbHistory(url: URL, now: Date) async throws {
  111. let twentyFourHoursAgo = now - 24.hours.timeInterval
  112. let carbHistoryFull: [CarbsEntry] = try readJsonFile(url: url)
  113. let existingDates = try await fetchCarbEntryDates(start: twentyFourHoursAgo, end: now)
  114. // Only import carb entries from the last 24 hours that do not exist yet in Core Data
  115. // Only import "true" carb entries; ignore all FPU entries (aka carb equivalents)
  116. let carbHistory = carbHistoryFull
  117. .filter {
  118. let dateToCheck = $0.actualDate ?? $0.createdAt
  119. return dateToCheck >= twentyFourHoursAgo && dateToCheck <= now && !existingDates.contains(dateToCheck) && $0
  120. .isFPU ?? false == false }
  121. // Create a background context for batch processing
  122. let backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  123. backgroundContext.parent = context
  124. try await backgroundContext.perform {
  125. for carbEntry in carbHistory {
  126. try carbEntry.store(in: backgroundContext)
  127. }
  128. try backgroundContext.save()
  129. }
  130. try await context.perform {
  131. try self.context.save()
  132. }
  133. }
  134. }
  135. // MARK: - Extension for Specific Import Functions
  136. extension BloodGlucose {
  137. /// Helper function to convert `BloodGlucose` to `GlucoseStored` while importing JSON glucose entries
  138. func store(in context: NSManagedObjectContext) throws {
  139. guard let glucoseValue = glucose ?? sgv else {
  140. throw JSONImporterError.missingGlucoseValueInGlucoseEntry
  141. }
  142. let glucoseEntry = GlucoseStored(context: context)
  143. glucoseEntry.id = _id.flatMap({ UUID(uuidString: $0) }) ?? UUID()
  144. glucoseEntry.date = dateString
  145. glucoseEntry.glucose = Int16(glucoseValue)
  146. glucoseEntry.direction = direction?.rawValue
  147. glucoseEntry.isManual = type == "Manual"
  148. glucoseEntry.isUploadedToNS = true
  149. glucoseEntry.isUploadedToHealth = true
  150. glucoseEntry.isUploadedToTidepool = true
  151. }
  152. }
  153. /// Extension to support decoding `CarbsEntry` from JSON with multiple possible key formats for entry notes.
  154. ///
  155. /// This is needed because some JSON sources (e.g., Trio v0.2.5) use the singular key `"note"`
  156. /// for the `note` field, while others (e.g., Nightscout or oref) use the plural `"notes"`.
  157. ///
  158. /// To ensure compatibility across all sources without duplicating models or requiring upstream fixes,
  159. /// this custom implementation attempts to decode the `note` field first from `"note"`, then from `"notes"`.
  160. /// Encoding will always use the canonical `"notes"` key to preserve consistency in output,
  161. /// as this is what's established throughout the backend now.
  162. extension CarbsEntry: Codable {
  163. init(from decoder: Decoder) throws {
  164. let container = try decoder.container(keyedBy: CodingKeys.self)
  165. id = try container.decodeIfPresent(String.self, forKey: .id)
  166. createdAt = try container.decode(Date.self, forKey: .createdAt)
  167. actualDate = try container.decodeIfPresent(Date.self, forKey: .actualDate)
  168. carbs = try container.decode(Decimal.self, forKey: .carbs)
  169. fat = try container.decodeIfPresent(Decimal.self, forKey: .fat)
  170. protein = try container.decodeIfPresent(Decimal.self, forKey: .protein)
  171. // Handle both `note` and `notes`
  172. if let noteValue = try? container.decodeIfPresent(String.self, forKey: .note) {
  173. note = noteValue
  174. } else if let notesValue = try? container.decodeIfPresent(String.self, forKey: .noteAlt) {
  175. note = notesValue
  176. } else {
  177. note = nil
  178. }
  179. enteredBy = try container.decodeIfPresent(String.self, forKey: .enteredBy)
  180. isFPU = try container.decodeIfPresent(Bool.self, forKey: .isFPU)
  181. fpuID = try container.decodeIfPresent(String.self, forKey: .fpuID)
  182. }
  183. func encode(to encoder: Encoder) throws {
  184. var container = encoder.container(keyedBy: CodingKeys.self)
  185. try container.encodeIfPresent(id, forKey: .id)
  186. try container.encode(createdAt, forKey: .createdAt)
  187. try container.encodeIfPresent(actualDate, forKey: .actualDate)
  188. try container.encode(carbs, forKey: .carbs)
  189. try container.encodeIfPresent(fat, forKey: .fat)
  190. try container.encodeIfPresent(protein, forKey: .protein)
  191. try container.encodeIfPresent(note, forKey: .note)
  192. try container.encodeIfPresent(enteredBy, forKey: .enteredBy)
  193. try container.encodeIfPresent(isFPU, forKey: .isFPU)
  194. try container.encodeIfPresent(fpuID, forKey: .fpuID)
  195. }
  196. private enum CodingKeys: String, CodingKey {
  197. case id = "_id"
  198. case createdAt = "created_at"
  199. case actualDate
  200. case carbs
  201. case fat
  202. case protein
  203. case note = "notes" // standard key
  204. case noteAlt = "note" // import key
  205. case enteredBy
  206. case isFPU
  207. case fpuID
  208. }
  209. /// Helper function to convert `CarbsStored` to `CarbEntryStored` while importing JSON carb entries
  210. func store(in context: NSManagedObjectContext) throws {
  211. guard carbs >= 0 else {
  212. throw JSONImporterError.missingCarbsValueInCarbEntry
  213. }
  214. // skip FPU entries for now
  215. let carbEntry = CarbEntryStored(context: context)
  216. carbEntry.id = id
  217. .flatMap({ UUID(uuidString: $0) }) ?? UUID() /// The `CodingKey` of `id` is `_id`, so this fine to use here
  218. carbEntry.date = actualDate ?? createdAt
  219. carbEntry.carbs = Double(truncating: NSDecimalNumber(decimal: carbs))
  220. carbEntry.fat = Double(truncating: NSDecimalNumber(decimal: fat ?? 0))
  221. carbEntry.protein = Double(truncating: NSDecimalNumber(decimal: protein ?? 0))
  222. carbEntry.note = note ?? ""
  223. carbEntry.isFPU = false
  224. carbEntry.isUploadedToNS = true
  225. carbEntry.isUploadedToHealth = true
  226. carbEntry.isUploadedToTidepool = true
  227. if fat != nil, protein != nil, let fpuId = fpuID {
  228. carbEntry.fpuID = UUID(uuidString: fpuId)
  229. }
  230. }
  231. }
  232. extension JSONImporter {
  233. func importGlucoseHistoryIfNeeded() async {}
  234. func importCarbHistoryIfNeeded() async {}
  235. }