FileStorage.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import Foundation
  2. protocol FileStorage {
  3. func save<Value: JSON>(_ value: Value, as name: String)
  4. func saveAsync<Value: JSON>(_ value: Value, as name: String) async
  5. func retrieve<Value: JSON>(_ name: String, as type: Value.Type) -> Value?
  6. func retrieveAsync<Value: JSON>(_ name: String, as type: Value.Type) async -> Value?
  7. func retrieveRaw(_ name: String) -> RawJSON?
  8. func retrieveRawAsync(_ name: String) async -> RawJSON?
  9. func append<Value: JSON>(_ newValue: Value, to name: String)
  10. func append<Value: JSON>(_ newValues: [Value], to name: String)
  11. func append<Value: JSON, T: Equatable>(_ newValue: Value, to name: String, uniqBy keyPath: KeyPath<Value, T>)
  12. func append<Value: JSON, T: Equatable>(_ newValues: [Value], to name: String, uniqBy keyPath: KeyPath<Value, T>)
  13. func remove(_ name: String)
  14. func rename(_ name: String, to newName: String)
  15. func transaction(_ exec: (FileStorage) -> Void)
  16. func urlFor(file: String) -> URL?
  17. func parseOnFileSettingsToMgdL() -> Bool
  18. }
  19. final class BaseFileStorage: FileStorage {
  20. private let processQueue = DispatchQueue.markedQueue(label: "BaseFileStorage.processQueue", qos: .utility)
  21. func save<Value: JSON>(_ value: Value, as name: String) {
  22. processQueue.safeSync {
  23. if let value = value as? RawJSON, let data = value.data(using: .utf8) {
  24. try? Disk.save(data, to: .documents, as: name)
  25. } else {
  26. try? Disk.save(value, to: .documents, as: name, encoder: JSONCoding.encoder)
  27. }
  28. }
  29. }
  30. func saveAsync<Value: JSON>(_ value: Value, as name: String) async {
  31. await withCheckedContinuation { continuation in
  32. processQueue.safeSync {
  33. if let value = value as? RawJSON, let data = value.data(using: .utf8) {
  34. try? Disk.save(data, to: .documents, as: name)
  35. } else {
  36. try? Disk.save(value, to: .documents, as: name, encoder: JSONCoding.encoder)
  37. }
  38. continuation.resume()
  39. }
  40. }
  41. }
  42. func retrieve<Value: JSON>(_ name: String, as type: Value.Type) -> Value? {
  43. processQueue.safeSync {
  44. try? Disk.retrieve(name, from: .documents, as: type, decoder: JSONCoding.decoder)
  45. }
  46. }
  47. func retrieveAsync<Value: JSON>(_ name: String, as type: Value.Type) async -> Value? {
  48. await withCheckedContinuation { continuation in
  49. processQueue.safeSync {
  50. let result = try? Disk.retrieve(name, from: .documents, as: type, decoder: JSONCoding.decoder)
  51. continuation.resume(returning: result)
  52. }
  53. }
  54. }
  55. func retrieveRaw(_ name: String) -> RawJSON? {
  56. processQueue.safeSync {
  57. guard let data = try? Disk.retrieve(name, from: .documents, as: Data.self) else {
  58. return nil
  59. }
  60. return String(data: data, encoding: .utf8)
  61. }
  62. }
  63. func retrieveRawAsync(_ name: String) async -> RawJSON? {
  64. await withCheckedContinuation { continuation in
  65. processQueue.safeSync {
  66. guard let data = try? Disk.retrieve(name, from: .documents, as: Data.self) else {
  67. continuation.resume(returning: nil)
  68. return
  69. }
  70. continuation.resume(returning: String(data: data, encoding: .utf8))
  71. }
  72. }
  73. }
  74. func append<Value: JSON>(_ newValue: Value, to name: String) {
  75. processQueue.safeSync {
  76. try? Disk.append(newValue, to: name, in: .documents, decoder: JSONCoding.decoder, encoder: JSONCoding.encoder)
  77. }
  78. }
  79. func append<Value: JSON>(_ newValues: [Value], to name: String) {
  80. processQueue.safeSync {
  81. try? Disk.append(newValues, to: name, in: .documents, decoder: JSONCoding.decoder, encoder: JSONCoding.encoder)
  82. }
  83. }
  84. func append<Value: JSON, T: Equatable>(_ newValue: Value, to name: String, uniqBy keyPath: KeyPath<Value, T>) {
  85. if let value = retrieve(name, as: Value.self) {
  86. if value[keyPath: keyPath] != newValue[keyPath: keyPath] {
  87. append(newValue, to: name)
  88. }
  89. } else if let values = retrieve(name, as: [Value].self) {
  90. guard values.first(where: { $0[keyPath: keyPath] == newValue[keyPath: keyPath] }) == nil else {
  91. return
  92. }
  93. append(newValue, to: name)
  94. } else {
  95. save(newValue, as: name)
  96. }
  97. }
  98. func append<Value: JSON, T: Equatable>(_ newValues: [Value], to name: String, uniqBy keyPath: KeyPath<Value, T>) {
  99. if let value = retrieve(name, as: Value.self) {
  100. if newValues.firstIndex(where: { $0[keyPath: keyPath] == value[keyPath: keyPath] }) != nil {
  101. save(newValues, as: name)
  102. return
  103. }
  104. append(newValues, to: name)
  105. } else if var values = retrieve(name, as: [Value].self) {
  106. for newValue in newValues {
  107. if let index = values.firstIndex(where: { $0[keyPath: keyPath] == newValue[keyPath: keyPath] }) {
  108. values[index] = newValue
  109. } else {
  110. values.append(newValue)
  111. }
  112. save(values, as: name)
  113. }
  114. } else {
  115. save(newValues, as: name)
  116. }
  117. }
  118. func remove(_ name: String) {
  119. processQueue.safeSync {
  120. try? Disk.remove(name, from: .documents)
  121. }
  122. }
  123. func rename(_ name: String, to newName: String) {
  124. processQueue.safeSync {
  125. try? Disk.rename(name, in: .documents, to: newName)
  126. }
  127. }
  128. func transaction(_ exec: (FileStorage) -> Void) {
  129. processQueue.safeSync {
  130. exec(self)
  131. }
  132. }
  133. func urlFor(file: String) -> URL? {
  134. try? Disk.url(for: file, in: .documents)
  135. }
  136. }
  137. extension FileStorage {
  138. private func correctUnitParsingOffsets(_ parsedValue: Decimal) -> Decimal {
  139. Int(parsedValue) % 2 == 0 ? parsedValue : parsedValue + 1
  140. }
  141. func parseSettingIfMmolL(value: Decimal, threshold: Decimal = 39) -> Decimal {
  142. value < threshold ? correctUnitParsingOffsets(value.asMgdL) : value
  143. }
  144. /// Parses mmol/L settings stored on file to mg/dL if necessary and updates the preferences, settings, insulin sensitivities, and glucose targets.
  145. /// - Returns: A boolean indicating whether any settings were parsed and updated.
  146. func parseOnFileSettingsToMgdL() -> Bool {
  147. debug(.businessLogic, "Check for mmol/L settings stored on file.")
  148. var wasParsed = false
  149. // Retrieve and parse preferences (Preferences struct)
  150. if var preferences = retrieve(OpenAPS.Settings.preferences, as: Preferences.self) {
  151. let initialThreshold = preferences.threshold_setting
  152. let initialSMBTarget = preferences.enableSMB_high_bg_target
  153. let initialExerciseTarget = preferences.halfBasalExerciseTarget
  154. preferences.threshold_setting = parseSettingIfMmolL(value: preferences.threshold_setting)
  155. preferences.enableSMB_high_bg_target = parseSettingIfMmolL(value: preferences.enableSMB_high_bg_target)
  156. preferences.halfBasalExerciseTarget = parseSettingIfMmolL(value: preferences.halfBasalExerciseTarget)
  157. if preferences.threshold_setting != initialThreshold ||
  158. preferences.enableSMB_high_bg_target != initialSMBTarget ||
  159. preferences.halfBasalExerciseTarget != initialExerciseTarget
  160. {
  161. debug(.businessLogic, "Preferences found in mmol/L. Parsing to mg/dL.")
  162. save(preferences, as: OpenAPS.Settings.preferences)
  163. wasParsed = true
  164. } else {
  165. debug(.businessLogic, "Preferences stored in mg/dL; no parsing required.")
  166. }
  167. }
  168. // Retrieve and parse settings (FreeAPSSettings struct)
  169. if var settings = retrieve(OpenAPS.Settings.settings, as: FreeAPSSettings.self) {
  170. let initialHigh = settings.high
  171. let initialLow = settings.low
  172. let initialHighGlucose = settings.highGlucose
  173. let initialLowGlucose = settings.lowGlucose
  174. settings.high = parseSettingIfMmolL(value: settings.high)
  175. settings.low = parseSettingIfMmolL(value: settings.low)
  176. settings.highGlucose = parseSettingIfMmolL(value: settings.highGlucose)
  177. settings.lowGlucose = parseSettingIfMmolL(value: settings.lowGlucose)
  178. if settings.high != initialHigh ||
  179. settings.low != initialLow ||
  180. settings.highGlucose != initialHighGlucose ||
  181. settings.lowGlucose != initialLowGlucose
  182. {
  183. debug(.businessLogic, "FreeAPSSettings found in mmol/L. Parsing to mg/dL.")
  184. save(settings, as: OpenAPS.Settings.settings)
  185. wasParsed = true
  186. } else {
  187. debug(.businessLogic, "FreeAPSSettings stored in mg/dL; no parsing required.")
  188. }
  189. }
  190. // Retrieve and parse insulin sensitivities
  191. if var sensitivities = retrieve(OpenAPS.Settings.insulinSensitivities, as: InsulinSensitivities.self),
  192. sensitivities.units == .mmolL || sensitivities.userPreferredUnits == .mmolL
  193. {
  194. debug(.businessLogic, "Insulin sensitivities found in mmol/L. Parsing to mg/dL.")
  195. sensitivities.sensitivities = sensitivities.sensitivities.map { isf in
  196. InsulinSensitivityEntry(
  197. sensitivity: parseSettingIfMmolL(value: isf.sensitivity),
  198. offset: isf.offset,
  199. start: isf.start
  200. )
  201. }
  202. sensitivities.units = .mgdL
  203. sensitivities.userPreferredUnits = .mgdL
  204. save(sensitivities, as: OpenAPS.Settings.insulinSensitivities)
  205. wasParsed = true
  206. } else {
  207. debug(.businessLogic, "Insulin sensitivities stored in mg/dL; no parsing required.")
  208. }
  209. // Retrieve and parse glucose targets
  210. if var glucoseTargets = retrieve(OpenAPS.Settings.bgTargets, as: BGTargets.self),
  211. glucoseTargets.units == .mmolL || glucoseTargets.userPreferredUnits == .mmolL
  212. {
  213. debug(.businessLogic, "Glucose target profile found in mmol/L. Parsing to mg/dL.")
  214. glucoseTargets.targets = glucoseTargets.targets.map { target in
  215. BGTargetEntry(
  216. low: parseSettingIfMmolL(value: target.low),
  217. high: parseSettingIfMmolL(value: target.high),
  218. start: target.start,
  219. offset: target.offset
  220. )
  221. }
  222. glucoseTargets.units = .mgdL
  223. glucoseTargets.userPreferredUnits = .mgdL
  224. save(glucoseTargets, as: OpenAPS.Settings.bgTargets)
  225. wasParsed = true
  226. } else {
  227. debug(.businessLogic, "Glucose target profile stored in mg/dL; no parsing required.")
  228. }
  229. return wasParsed
  230. }
  231. }