FileStorage.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. do {
  24. if let value = value as? RawJSON, let data = value.data(using: .utf8) {
  25. try Disk.save(data, to: .documents, as: name)
  26. } else {
  27. try Disk.save(value, to: .documents, as: name, encoder: JSONCoding.encoder)
  28. }
  29. } catch {
  30. debug(.storage, "Failed to save file '\(name)': \(error.localizedDescription)")
  31. }
  32. }
  33. }
  34. func saveAsync<Value: JSON>(_ value: Value, as name: String) async {
  35. await withCheckedContinuation { continuation in
  36. processQueue.safeSync {
  37. do {
  38. if let value = value as? RawJSON, let data = value.data(using: .utf8) {
  39. try Disk.save(data, to: .documents, as: name)
  40. } else {
  41. try Disk.save(value, to: .documents, as: name, encoder: JSONCoding.encoder)
  42. }
  43. } catch {
  44. debug(.storage, "Failed to save file '\(name)': \(error.localizedDescription)")
  45. }
  46. continuation.resume()
  47. }
  48. }
  49. }
  50. func retrieve<Value: JSON>(_ name: String, as type: Value.Type) -> Value? {
  51. processQueue.safeSync {
  52. do {
  53. return try Disk.retrieve(name, from: .documents, as: type, decoder: JSONCoding.decoder)
  54. } catch {
  55. debug(.storage, "Failed to retrieve file '\(name)': \(error.localizedDescription)")
  56. return nil
  57. }
  58. }
  59. }
  60. func retrieveAsync<Value: JSON>(_ name: String, as type: Value.Type) async -> Value? {
  61. await withCheckedContinuation { continuation in
  62. processQueue.safeSync {
  63. do {
  64. let result = try Disk.retrieve(name, from: .documents, as: type, decoder: JSONCoding.decoder)
  65. continuation.resume(returning: result)
  66. } catch {
  67. debug(.storage, "Failed to retrieve file '\(name)': \(error.localizedDescription)")
  68. continuation.resume(returning: nil)
  69. }
  70. }
  71. }
  72. }
  73. func retrieveRaw(_ name: String) -> RawJSON? {
  74. processQueue.safeSync {
  75. do {
  76. let data = try Disk.retrieve(name, from: .documents, as: Data.self)
  77. guard let string = String(data: data, encoding: .utf8) else {
  78. debug(.storage, "Failed to decode data as UTF-8 string for file '\(name)'")
  79. return nil
  80. }
  81. return string
  82. } catch {
  83. debug(.storage, "Failed to retrieve file '\(name)': \(error.localizedDescription)")
  84. return nil
  85. }
  86. }
  87. }
  88. func retrieveRawAsync(_ name: String) async -> RawJSON? {
  89. await withCheckedContinuation { continuation in
  90. processQueue.safeSync {
  91. do {
  92. let data = try Disk.retrieve(name, from: .documents, as: Data.self)
  93. guard let string = String(data: data, encoding: .utf8) else {
  94. debug(.storage, "Failed to decode data as UTF-8 string for file '\(name)'")
  95. continuation.resume(returning: nil)
  96. return
  97. }
  98. continuation.resume(returning: string)
  99. } catch {
  100. debug(.storage, "Failed to retrieve file '\(name)': \(error.localizedDescription)")
  101. continuation.resume(returning: nil)
  102. }
  103. }
  104. }
  105. }
  106. func append<Value: JSON>(_ newValue: Value, to name: String) {
  107. processQueue.safeSync {
  108. do {
  109. try Disk.append(newValue, to: name, in: .documents, decoder: JSONCoding.decoder, encoder: JSONCoding.encoder)
  110. } catch {
  111. debug(.storage, "Failed to append to file '\(name)': \(error.localizedDescription)")
  112. }
  113. }
  114. }
  115. func append<Value: JSON>(_ newValues: [Value], to name: String) {
  116. processQueue.safeSync {
  117. do {
  118. try Disk.append(newValues, to: name, in: .documents, decoder: JSONCoding.decoder, encoder: JSONCoding.encoder)
  119. } catch {
  120. debug(.storage, "Failed to append to file '\(name)': \(error.localizedDescription)")
  121. }
  122. }
  123. }
  124. func append<Value: JSON, T: Equatable>(_ newValue: Value, to name: String, uniqBy keyPath: KeyPath<Value, T>) {
  125. if let value = retrieve(name, as: Value.self) {
  126. if value[keyPath: keyPath] != newValue[keyPath: keyPath] {
  127. append(newValue, to: name)
  128. }
  129. } else if let values = retrieve(name, as: [Value].self) {
  130. guard values.first(where: { $0[keyPath: keyPath] == newValue[keyPath: keyPath] }) == nil else {
  131. return
  132. }
  133. append(newValue, to: name)
  134. } else {
  135. save(newValue, as: name)
  136. }
  137. }
  138. func append<Value: JSON, T: Equatable>(_ newValues: [Value], to name: String, uniqBy keyPath: KeyPath<Value, T>) {
  139. if let value = retrieve(name, as: Value.self) {
  140. if newValues.firstIndex(where: { $0[keyPath: keyPath] == value[keyPath: keyPath] }) != nil {
  141. save(newValues, as: name)
  142. return
  143. }
  144. append(newValues, to: name)
  145. } else if var values = retrieve(name, as: [Value].self) {
  146. for newValue in newValues {
  147. if let index = values.firstIndex(where: { $0[keyPath: keyPath] == newValue[keyPath: keyPath] }) {
  148. values[index] = newValue
  149. } else {
  150. values.append(newValue)
  151. }
  152. save(values, as: name)
  153. }
  154. } else {
  155. save(newValues, as: name)
  156. }
  157. }
  158. func remove(_ name: String) {
  159. processQueue.safeSync {
  160. do {
  161. try Disk.remove(name, from: .documents)
  162. } catch {
  163. debug(.storage, "Failed to remove file '\(name)': \(error.localizedDescription)")
  164. }
  165. }
  166. }
  167. func rename(_ name: String, to newName: String) {
  168. processQueue.safeSync {
  169. do {
  170. try Disk.rename(name, in: .documents, to: newName)
  171. } catch {
  172. debug(.storage, "Failed to rename file '\(name)' to '\(newName)': \(error.localizedDescription)")
  173. }
  174. }
  175. }
  176. func transaction(_ exec: (FileStorage) -> Void) {
  177. processQueue.safeSync {
  178. exec(self)
  179. }
  180. }
  181. func urlFor(file: String) -> URL? {
  182. do {
  183. return try Disk.url(for: file, in: .documents)
  184. } catch {
  185. debug(.storage, "Failed to get URL for file '\(file)': \(error.localizedDescription)")
  186. return nil
  187. }
  188. }
  189. }
  190. extension FileStorage {
  191. private func correctUnitParsingOffsets(_ parsedValue: Decimal) -> Decimal {
  192. Int(parsedValue) % 2 == 0 ? parsedValue : parsedValue + 1
  193. }
  194. func parseSettingIfMmolL(value: Decimal, threshold: Decimal = 39) -> Decimal {
  195. value < threshold ? correctUnitParsingOffsets(value.asMgdL) : value
  196. }
  197. /// Parses mmol/L settings stored on file to mg/dL if necessary and updates the preferences, settings, insulin sensitivities, and glucose targets.
  198. /// - Returns: A boolean indicating whether any settings were parsed and updated.
  199. func parseOnFileSettingsToMgdL() -> Bool {
  200. debug(.businessLogic, "Check for mmol/L settings stored on file.")
  201. var wasParsed = false
  202. // Retrieve and parse preferences (Preferences struct)
  203. if var preferences = retrieve(OpenAPS.Settings.preferences, as: Preferences.self) {
  204. let initialThreshold = preferences.threshold_setting
  205. let initialSMBTarget = preferences.enableSMB_high_bg_target
  206. let initialExerciseTarget = preferences.halfBasalExerciseTarget
  207. preferences.threshold_setting = parseSettingIfMmolL(value: preferences.threshold_setting)
  208. preferences.enableSMB_high_bg_target = parseSettingIfMmolL(value: preferences.enableSMB_high_bg_target)
  209. preferences.halfBasalExerciseTarget = parseSettingIfMmolL(value: preferences.halfBasalExerciseTarget)
  210. if preferences.threshold_setting != initialThreshold ||
  211. preferences.enableSMB_high_bg_target != initialSMBTarget ||
  212. preferences.halfBasalExerciseTarget != initialExerciseTarget
  213. {
  214. debug(.businessLogic, "Preferences found in mmol/L. Parsing to mg/dL.")
  215. save(preferences, as: OpenAPS.Settings.preferences)
  216. wasParsed = true
  217. } else {
  218. debug(.businessLogic, "Preferences stored in mg/dL; no parsing required.")
  219. }
  220. }
  221. // Retrieve and parse settings (TrioSettings struct)
  222. if var settings = retrieve(OpenAPS.Settings.settings, as: TrioSettings.self) {
  223. let initialHigh = settings.high
  224. let initialLow = settings.low
  225. let initialHighGlucose = settings.highGlucose
  226. let initialLowGlucose = settings.lowGlucose
  227. settings.high = parseSettingIfMmolL(value: settings.high)
  228. settings.low = parseSettingIfMmolL(value: settings.low)
  229. settings.highGlucose = parseSettingIfMmolL(value: settings.highGlucose)
  230. settings.lowGlucose = parseSettingIfMmolL(value: settings.lowGlucose)
  231. if settings.high != initialHigh ||
  232. settings.low != initialLow ||
  233. settings.highGlucose != initialHighGlucose ||
  234. settings.lowGlucose != initialLowGlucose
  235. {
  236. debug(.businessLogic, "TrioSettings found in mmol/L. Parsing to mg/dL.")
  237. save(settings, as: OpenAPS.Settings.settings)
  238. wasParsed = true
  239. } else {
  240. debug(.businessLogic, "TrioSettings stored in mg/dL; no parsing required.")
  241. }
  242. }
  243. // Retrieve and parse insulin sensitivities
  244. if var sensitivities = retrieve(OpenAPS.Settings.insulinSensitivities, as: InsulinSensitivities.self),
  245. sensitivities.units == .mmolL || sensitivities.userPreferredUnits == .mmolL
  246. {
  247. debug(.businessLogic, "Insulin sensitivities found in mmol/L. Parsing to mg/dL.")
  248. sensitivities.sensitivities = sensitivities.sensitivities.map { isf in
  249. InsulinSensitivityEntry(
  250. sensitivity: parseSettingIfMmolL(value: isf.sensitivity),
  251. offset: isf.offset,
  252. start: isf.start
  253. )
  254. }
  255. sensitivities.units = .mgdL
  256. sensitivities.userPreferredUnits = .mgdL
  257. save(sensitivities, as: OpenAPS.Settings.insulinSensitivities)
  258. wasParsed = true
  259. } else {
  260. debug(.businessLogic, "Insulin sensitivities stored in mg/dL; no parsing required.")
  261. }
  262. // Retrieve and parse glucose targets
  263. if var glucoseTargets = retrieve(OpenAPS.Settings.bgTargets, as: BGTargets.self),
  264. glucoseTargets.units == .mmolL || glucoseTargets.userPreferredUnits == .mmolL
  265. {
  266. debug(.businessLogic, "Glucose target profile found in mmol/L. Parsing to mg/dL.")
  267. glucoseTargets.targets = glucoseTargets.targets.map { target in
  268. BGTargetEntry(
  269. low: parseSettingIfMmolL(value: target.low),
  270. high: parseSettingIfMmolL(value: target.high),
  271. start: target.start,
  272. offset: target.offset
  273. )
  274. }
  275. glucoseTargets.units = .mgdL
  276. glucoseTargets.userPreferredUnits = .mgdL
  277. save(glucoseTargets, as: OpenAPS.Settings.bgTargets)
  278. wasParsed = true
  279. } else {
  280. debug(.businessLogic, "Glucose target profile stored in mg/dL; no parsing required.")
  281. }
  282. return wasParsed
  283. }
  284. }