| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522 |
- import Combine
- import CommonCrypto
- import Foundation
- import JavaScriptCore
- import Swinject
- class NightscoutAPI {
- init(url: URL, secret: String? = nil) {
- self.url = url
- self.secret = secret?.nonEmpty
- }
- private enum Config {
- static let entriesPath = "/api/v1/entries/sgv.json"
- static let uploadEntriesPath = "/api/v1/entries.json"
- static let treatmentsPath = "/api/v1/treatments.json"
- static let statusPath = "/api/v1/devicestatus.json"
- static let profilePath = "/api/v1/profile.json"
- static let retryCount = 1
- static let timeout: TimeInterval = 60
- }
- enum Error: LocalizedError {
- case badStatusCode
- case missingURL
- }
- let url: URL
- let secret: String?
- private let service = NetworkService()
- @Injected() private var settingsManager: SettingsManager!
- }
- extension NightscoutAPI {
- func checkConnection() -> AnyPublisher<Void, Swift.Error> {
- struct Check: Codable, Equatable {
- var eventType = "Note"
- var enteredBy = "iAPS"
- var notes = "iAPS connected"
- }
- let check = Check()
- var request = URLRequest(url: url.appendingPathComponent(Config.treatmentsPath))
- if let secret = secret {
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
- request.httpMethod = "POST"
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- request.httpBody = try! JSONCoding.encoder.encode(check)
- } else {
- request.httpMethod = "GET"
- }
- return service.run(request)
- .map { _ in () }
- .eraseToAnyPublisher()
- }
- func fetchLastGlucose(sinceDate: Date? = nil) -> AnyPublisher<[BloodGlucose], Swift.Error> {
- var components = URLComponents()
- components.scheme = url.scheme
- components.host = url.host
- components.port = url.port
- components.path = Config.entriesPath
- components.queryItems = [URLQueryItem(name: "count", value: "\(1600)")]
- if let date = sinceDate {
- let dateItem = URLQueryItem(
- name: "find[dateString][$gte]",
- value: Formatter.iso8601withFractionalSeconds.string(from: date)
- )
- components.queryItems?.append(dateItem)
- }
- var request = URLRequest(url: components.url!)
- request.allowsConstrainedNetworkAccess = false
- request.timeoutInterval = Config.timeout
- if let secret = secret {
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- }
- return service.run(request)
- .retry(Config.retryCount)
- .decode(type: [BloodGlucose].self, decoder: JSONCoding.decoder)
- .catch { error -> AnyPublisher<[BloodGlucose], Swift.Error> in
- warning(.nightscout, "Glucose fetching error: \(error.localizedDescription)")
- return Just([]).setFailureType(to: Swift.Error.self).eraseToAnyPublisher()
- }
- .map { glucose in
- glucose
- .map {
- var reading = $0
- reading.glucose = $0.sgv
- return reading
- }
- }
- .eraseToAnyPublisher()
- }
- func fetchCarbs(sinceDate: Date? = nil) -> AnyPublisher<[CarbsEntry], Swift.Error> {
- var components = URLComponents()
- components.scheme = url.scheme
- components.host = url.host
- components.port = url.port
- components.path = Config.treatmentsPath
- components.queryItems = [
- URLQueryItem(name: "find[carbs][$exists]", value: "true"),
- URLQueryItem(
- name: "find[enteredBy][$ne]",
- value: CarbsEntry.manual.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
- ),
- URLQueryItem(
- name: "find[enteredBy][$ne]",
- value: NigtscoutTreatment.local.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
- )
- ]
- if let date = sinceDate {
- let dateItem = URLQueryItem(
- name: "find[created_at][$gt]",
- value: Formatter.iso8601withFractionalSeconds.string(from: date)
- )
- components.queryItems?.append(dateItem)
- }
- var request = URLRequest(url: components.url!)
- request.allowsConstrainedNetworkAccess = false
- request.timeoutInterval = Config.timeout
- if let secret = secret {
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- }
- return service.run(request)
- .retry(Config.retryCount)
- .decode(type: [CarbsEntry].self, decoder: JSONCoding.decoder)
- .catch { error -> AnyPublisher<[CarbsEntry], Swift.Error> in
- warning(.nightscout, "Carbs fetching error: \(error.localizedDescription)")
- return Just([]).setFailureType(to: Swift.Error.self).eraseToAnyPublisher()
- }
- .eraseToAnyPublisher()
- }
- func deleteCarbs(_ treatement: DataTable.Treatment) -> AnyPublisher<Void, Swift.Error> {
- var components = URLComponents()
- components.scheme = url.scheme
- components.host = url.host
- components.port = url.port
- components.path = Config.treatmentsPath
- var arguments = "find[id][$eq]"
- if treatement.isFPU ?? false {
- arguments = "find[fpuID][$eq]"
- }
- let value = !(treatement.isFPU ?? false) ? treatement.id : (treatement.fpuID ?? "")
- components.queryItems = [
- // Removed below because it prevented all futire entries to be deleted. Don't know why?
- /* URLQueryItem(name: "find[carbs][$exists]", value: "true"), */
- URLQueryItem(
- name: arguments,
- value: value
- )
- ]
- var request = URLRequest(url: components.url!)
- request.allowsConstrainedNetworkAccess = false
- request.timeoutInterval = Config.timeout
- request.httpMethod = "DELETE"
- if let secret = secret {
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- }
- return service.run(request)
- .retry(Config.retryCount)
- .map { _ in () }
- .eraseToAnyPublisher()
- }
- func deleteManualGlucose(at date: Date) -> AnyPublisher<Void, Swift.Error> {
- var components = URLComponents()
- components.scheme = url.scheme
- components.host = url.host
- components.port = url.port
- components.path = Config.treatmentsPath
- components.queryItems = [
- URLQueryItem(name: "find[glucose][$exists]", value: "true"),
- URLQueryItem(
- name: "find[created_at][$eq]",
- value: Formatter.iso8601withFractionalSeconds.string(from: date)
- )
- ]
- var request = URLRequest(url: components.url!)
- request.allowsConstrainedNetworkAccess = false
- request.timeoutInterval = Config.timeout
- request.httpMethod = "DELETE"
- if let secret = secret {
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- }
- return service.run(request)
- .retry(Config.retryCount)
- .map { _ in () }
- .eraseToAnyPublisher()
- }
- func deleteInsulin(at date: Date) -> AnyPublisher<Void, Swift.Error> {
- var components = URLComponents()
- components.scheme = url.scheme
- components.host = url.host
- components.port = url.port
- components.path = Config.treatmentsPath
- components.queryItems = [
- URLQueryItem(name: "find[bolus][$exists]", value: "true"),
- URLQueryItem(
- name: "find[created_at][$eq]",
- value: Formatter.iso8601withFractionalSeconds.string(from: date)
- )
- ]
- var request = URLRequest(url: components.url!)
- request.allowsConstrainedNetworkAccess = false
- request.timeoutInterval = Config.timeout
- request.httpMethod = "DELETE"
- if let secret = secret {
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- }
- return service.run(request)
- .retry(Config.retryCount)
- .map { _ in () }
- .eraseToAnyPublisher()
- }
- func fetchTempTargets(sinceDate: Date? = nil) -> AnyPublisher<[TempTarget], Swift.Error> {
- var components = URLComponents()
- components.scheme = url.scheme
- components.host = url.host
- components.port = url.port
- components.path = Config.treatmentsPath
- components.queryItems = [
- URLQueryItem(name: "find[eventType]", value: "Temporary+Target"),
- URLQueryItem(
- name: "find[enteredBy][$ne]",
- value: TempTarget.manual.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
- ),
- URLQueryItem(
- name: "find[enteredBy][$ne]",
- value: NigtscoutTreatment.local.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
- ),
- URLQueryItem(name: "find[duration][$exists]", value: "true")
- ]
- if let date = sinceDate {
- let dateItem = URLQueryItem(
- name: "find[created_at][$gt]",
- value: Formatter.iso8601withFractionalSeconds.string(from: date)
- )
- components.queryItems?.append(dateItem)
- }
- var request = URLRequest(url: components.url!)
- request.allowsConstrainedNetworkAccess = false
- request.timeoutInterval = Config.timeout
- if let secret = secret {
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- }
- return service.run(request)
- .retry(Config.retryCount)
- .decode(type: [TempTarget].self, decoder: JSONCoding.decoder)
- .catch { error -> AnyPublisher<[TempTarget], Swift.Error> in
- warning(.nightscout, "TempTarget fetching error: \(error.localizedDescription)")
- return Just([]).setFailureType(to: Swift.Error.self).eraseToAnyPublisher()
- }
- .eraseToAnyPublisher()
- }
- func fetchAnnouncement(sinceDate: Date? = nil) -> AnyPublisher<[Announcement], Swift.Error> {
- var components = URLComponents()
- components.scheme = url.scheme
- components.host = url.host
- components.port = url.port
- components.path = Config.treatmentsPath
- components.queryItems = [
- URLQueryItem(name: "find[eventType]", value: "Announcement"),
- URLQueryItem(
- name: "find[enteredBy]",
- value: Announcement.remote.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
- )
- ]
- if let date = sinceDate {
- let dateItem = URLQueryItem(
- name: "find[created_at][$gte]",
- value: Formatter.iso8601withFractionalSeconds.string(from: date)
- )
- components.queryItems?.append(dateItem)
- }
- var request = URLRequest(url: components.url!)
- request.allowsConstrainedNetworkAccess = false
- request.timeoutInterval = Config.timeout
- if let secret = secret {
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- }
- return service.run(request)
- .retry(Config.retryCount)
- .decode(type: [Announcement].self, decoder: JSONCoding.decoder)
- .eraseToAnyPublisher()
- }
- func uploadTreatments(_ treatments: [NigtscoutTreatment]) -> AnyPublisher<Void, Swift.Error> {
- var components = URLComponents()
- components.scheme = url.scheme
- components.host = url.host
- components.port = url.port
- components.path = Config.treatmentsPath
- var request = URLRequest(url: components.url!)
- request.allowsConstrainedNetworkAccess = false
- request.timeoutInterval = Config.timeout
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
- if let secret = secret {
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- }
- request.httpBody = try? JSONCoding.encoder.encode(treatments)
- request.httpMethod = "POST"
- return service.run(request)
- .retry(Config.retryCount)
- .map { _ in () }
- .eraseToAnyPublisher()
- }
- func uploadGlucose(_ glucose: [BloodGlucose]) -> AnyPublisher<Void, Swift.Error> {
- var components = URLComponents()
- components.scheme = url.scheme
- components.host = url.host
- components.port = url.port
- components.path = Config.uploadEntriesPath
- var request = URLRequest(url: components.url!)
- request.allowsConstrainedNetworkAccess = false
- request.timeoutInterval = Config.timeout
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
- if let secret = secret {
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- }
- request.httpBody = try! JSONCoding.encoder.encode(glucose)
- request.httpMethod = "POST"
- return service.run(request)
- .retry(Config.retryCount)
- .map { _ in () }
- .eraseToAnyPublisher()
- }
- func uploadStats(_ stats: NightscoutStatistics) -> AnyPublisher<Void, Swift.Error> {
- var components = URLComponents()
- components.scheme = url.scheme
- components.host = url.host
- components.port = url.port
- components.path = Config.statusPath
- var request = URLRequest(url: components.url!)
- request.allowsConstrainedNetworkAccess = false
- request.timeoutInterval = Config.timeout
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
- if let secret = secret {
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- }
- request.httpBody = try! JSONCoding.encoder.encode(stats)
- request.httpMethod = "POST"
- return service.run(request)
- .retry(Config.retryCount)
- .map { _ in () }
- .eraseToAnyPublisher()
- }
- func uploadStatus(_ status: NightscoutStatus) -> AnyPublisher<Void, Swift.Error> {
- var components = URLComponents()
- components.scheme = url.scheme
- components.host = url.host
- components.port = url.port
- components.path = Config.statusPath
- var request = URLRequest(url: components.url!)
- request.allowsConstrainedNetworkAccess = false
- request.timeoutInterval = Config.timeout
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
- if let secret = secret {
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- }
- request.httpBody = try! JSONCoding.encoder.encode(status)
- request.httpMethod = "POST"
- return service.run(request)
- .retry(Config.retryCount)
- .map { _ in () }
- .eraseToAnyPublisher()
- }
- func uploadPrefs(_ prefs: NightscoutPreferences) -> AnyPublisher<Void, Swift.Error> {
- var components = URLComponents()
- components.scheme = url.scheme
- components.host = url.host
- components.port = url.port
- components.path = Config.statusPath
- var request = URLRequest(url: components.url!)
- request.allowsConstrainedNetworkAccess = false
- request.timeoutInterval = Config.timeout
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
- if let secret = secret {
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- }
- request.httpBody = try! JSONCoding.encoder.encode(prefs)
- request.httpMethod = "POST"
- return service.run(request)
- .retry(Config.retryCount)
- .map { _ in () }
- .eraseToAnyPublisher()
- }
- func uploadSettings(_ settings: NightscoutSettings) -> AnyPublisher<Void, Swift.Error> {
- var components = URLComponents()
- components.scheme = url.scheme
- components.host = url.host
- components.port = url.port
- components.path = Config.statusPath
- var request = URLRequest(url: components.url!)
- request.allowsConstrainedNetworkAccess = false
- request.timeoutInterval = Config.timeout
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
- if let secret = secret {
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- }
- request.httpBody = try! JSONCoding.encoder.encode(settings)
- request.httpMethod = "POST"
- return service.run(request)
- .retry(Config.retryCount)
- .map { _ in () }
- .eraseToAnyPublisher()
- }
- func uploadProfile(_ profile: NightscoutProfileStore) -> AnyPublisher<Void, Swift.Error> {
- var components = URLComponents()
- components.scheme = url.scheme
- components.host = url.host
- components.port = url.port
- components.path = Config.profilePath
- var request = URLRequest(url: components.url!)
- request.allowsConstrainedNetworkAccess = false
- request.timeoutInterval = Config.timeout
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
- if let secret = secret {
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- }
- request.httpBody = try! JSONCoding.encoder.encode(profile)
- request.httpMethod = "POST"
- return service.run(request)
- .retry(Config.retryCount)
- .map { _ in () }
- .eraseToAnyPublisher()
- }
- func uploadPreferences(_ preferences: Preferences) -> AnyPublisher<Void, Swift.Error> {
- var components = URLComponents()
- components.scheme = url.scheme
- components.host = url.host
- components.port = url.port
- components.path = Config.profilePath
- var request = URLRequest(url: components.url!)
- request.allowsConstrainedNetworkAccess = false
- request.timeoutInterval = Config.timeout
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
- if let secret = secret {
- request.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
- }
- request.httpBody = try! JSONCoding.encoder.encode(preferences)
- request.httpMethod = "POST"
- return service.run(request)
- .retry(Config.retryCount)
- .map { _ in () }
- .eraseToAnyPublisher()
- }
- }
- private extension String {
- func sha1() -> String {
- let data = Data(utf8)
- var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
- data.withUnsafeBytes {
- _ = CC_SHA1($0.baseAddress, CC_LONG(data.count), &digest)
- }
- let hexBytes = digest.map { String(format: "%02hhx", $0) }
- return hexBytes.joined()
- }
- }
|