RemoteSettingsView.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. // LoopFollow
  2. // RemoteSettingsView.swift
  3. import HealthKit
  4. import SwiftUI
  5. struct RemoteSettingsView: View {
  6. @ObservedObject var viewModel: RemoteSettingsViewModel
  7. @ObservedObject private var device = Storage.shared.device
  8. @State private var showAlert: Bool = false
  9. @State private var alertType: AlertType? = nil
  10. @State private var alertMessage: String? = nil
  11. @State private var otpTimeRemaining: Int? = nil
  12. private let otpPeriod: TimeInterval = 30
  13. private var otpTimer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
  14. enum AlertType {
  15. case validation
  16. }
  17. init(viewModel: RemoteSettingsViewModel) {
  18. self.viewModel = viewModel
  19. }
  20. var body: some View {
  21. Form {
  22. // MARK: - Remote Type Section (Custom Rows)
  23. Section {
  24. remoteTypeRow(
  25. type: .none,
  26. label: "None",
  27. isEnabled: true
  28. )
  29. remoteTypeRow(
  30. type: .loopAPNS,
  31. label: "Loop Remote Control",
  32. isEnabled: viewModel.isLoopDevice
  33. )
  34. remoteTypeRow(
  35. type: .trc,
  36. label: "Trio Remote Control",
  37. isEnabled: viewModel.isTrioDevice
  38. )
  39. remoteTypeRow(
  40. type: .nightscout,
  41. label: "Nightscout",
  42. isEnabled: viewModel.isTrioDevice
  43. )
  44. Text("Nightscout should be used for Trio 0.2.x.")
  45. .font(.footnote)
  46. .foregroundColor(.secondary)
  47. }
  48. // MARK: - Meal Section (for TRC only)
  49. if viewModel.remoteType == .trc {
  50. Section(header: Text("Meal Settings")) {
  51. Toggle("Meal with Bolus", isOn: $viewModel.mealWithBolus)
  52. .toggleStyle(SwitchToggleStyle())
  53. Toggle("Meal with Fat/Protein", isOn: $viewModel.mealWithFatProtein)
  54. .toggleStyle(SwitchToggleStyle())
  55. }
  56. }
  57. // MARK: - Guardrails Section (shown for both TRC and Loop)
  58. if viewModel.remoteType == .trc || viewModel.remoteType == .loopAPNS {
  59. guardrailsSection
  60. }
  61. // MARK: - User Information Section
  62. if viewModel.remoteType != .none && viewModel.remoteType != .loopAPNS {
  63. Section(header: Text("User Information")) {
  64. HStack {
  65. Text("User")
  66. TextField("Enter User", text: $viewModel.user)
  67. .autocapitalization(.none)
  68. .disableAutocorrection(true)
  69. .multilineTextAlignment(.trailing)
  70. }
  71. }
  72. }
  73. // MARK: - Trio Remote Control Settings
  74. if viewModel.remoteType == .trc {
  75. Section(header: Text("Trio Remote Control Settings")) {
  76. HStack {
  77. Text("Shared Secret")
  78. TogglableSecureInput(
  79. placeholder: "Enter Shared Secret",
  80. text: $viewModel.sharedSecret,
  81. style: .singleLine
  82. )
  83. }
  84. HStack {
  85. Text("APNS Key ID")
  86. TogglableSecureInput(
  87. placeholder: "Enter APNS Key ID",
  88. text: $viewModel.keyId,
  89. style: .singleLine
  90. )
  91. }
  92. VStack(alignment: .leading) {
  93. Text("APNS Key")
  94. TogglableSecureInput(
  95. placeholder: "Paste APNS Key",
  96. text: $viewModel.apnsKey,
  97. style: .multiLine
  98. )
  99. .frame(minHeight: 110)
  100. }
  101. }
  102. // MARK: - Debug / Info
  103. Section(header: Text("Debug / Info")) {
  104. Text("Device Token: \(Storage.shared.deviceToken.value)")
  105. Text("Production Env.: \(Storage.shared.productionEnvironment.value ? "True" : "False")")
  106. Text("Team ID: \(Storage.shared.teamId.value ?? "")")
  107. Text("Bundle ID: \(Storage.shared.bundleId.value)")
  108. }
  109. }
  110. // MARK: - Loop APNS Settings
  111. if viewModel.remoteType == .loopAPNS {
  112. Section(header: Text("Loop APNS Configuration")) {
  113. HStack {
  114. Text("Developer Team ID")
  115. TogglableSecureInput(
  116. placeholder: "Enter Team ID",
  117. text: $viewModel.loopDeveloperTeamId,
  118. style: .singleLine
  119. )
  120. }
  121. HStack {
  122. Text("APNS Key ID")
  123. TogglableSecureInput(
  124. placeholder: "Enter APNS Key ID",
  125. text: $viewModel.keyId,
  126. style: .singleLine
  127. )
  128. }
  129. VStack(alignment: .leading) {
  130. Text("APNS Key")
  131. TogglableSecureInput(
  132. placeholder: "Paste APNS Key",
  133. text: $viewModel.apnsKey,
  134. style: .multiLine
  135. )
  136. .frame(minHeight: 110)
  137. }
  138. HStack {
  139. Text("QR Code URL")
  140. TextField("Enter QR code URL or scan from Loop app", text: $viewModel.loopAPNSQrCodeURL)
  141. .textFieldStyle(RoundedBorderTextFieldStyle())
  142. .autocapitalization(.none)
  143. .disableAutocorrection(true)
  144. }
  145. Button(action: {
  146. viewModel.isShowingLoopAPNSScanner = true
  147. }) {
  148. HStack {
  149. Image(systemName: "qrcode.viewfinder")
  150. Text("Scan QR Code from Loop App")
  151. }
  152. }
  153. .buttonStyle(.borderedProminent)
  154. .frame(maxWidth: .infinity)
  155. .padding(.vertical, 10)
  156. HStack {
  157. Text("Environment")
  158. Spacer()
  159. Toggle("Production", isOn: $viewModel.productionEnvironment)
  160. .toggleStyle(SwitchToggleStyle())
  161. }
  162. Text("Production is used for browser builders and should be switched off for Xcode builders")
  163. .font(.caption)
  164. .foregroundColor(.secondary)
  165. }
  166. if let errorMessage = viewModel.loopAPNSErrorMessage, !errorMessage.isEmpty {
  167. Section {
  168. Text(errorMessage)
  169. .foregroundColor(.red)
  170. .font(.caption)
  171. }
  172. }
  173. Section(header: Text("Debug / Info")) {
  174. Text("Device Token: \(Storage.shared.deviceToken.value)")
  175. Text("Bundle ID: \(Storage.shared.bundleId.value)")
  176. if let otpCode = TOTPGenerator.extractOTPFromURL(Storage.shared.loopAPNSQrCodeURL.value) {
  177. HStack {
  178. Text("Current TOTP Code:")
  179. Text(otpCode)
  180. .font(.system(.body, design: .monospaced))
  181. .foregroundColor(.green)
  182. .padding(.vertical, 2)
  183. .padding(.horizontal, 6)
  184. .background(Color.green.opacity(0.1))
  185. .cornerRadius(4)
  186. Text("(" + (otpTimeRemaining.map { "\($0)s left" } ?? "-") + ")")
  187. .font(.caption)
  188. .foregroundColor(.secondary)
  189. }
  190. } else {
  191. Text("TOTP Code: Invalid QR code URL")
  192. .foregroundColor(.red)
  193. }
  194. }
  195. }
  196. }
  197. .alert(isPresented: $showAlert) {
  198. switch alertType {
  199. case .validation:
  200. return Alert(
  201. title: Text("Validation Error"),
  202. message: Text(alertMessage ?? "Invalid input."),
  203. dismissButton: .default(Text("OK"))
  204. )
  205. case .none:
  206. return Alert(title: Text("Unknown Alert"))
  207. }
  208. }
  209. .sheet(isPresented: $viewModel.isShowingLoopAPNSScanner) {
  210. SimpleQRCodeScannerView { result in
  211. viewModel.handleLoopAPNSQRCodeScanResult(result)
  212. }
  213. }
  214. .onAppear {
  215. // Reset timer state so it shows '-' until first tick
  216. otpTimeRemaining = nil
  217. }
  218. .onReceive(otpTimer) { _ in
  219. let now = Date().timeIntervalSince1970
  220. otpTimeRemaining = Int(otpPeriod - (now.truncatingRemainder(dividingBy: otpPeriod)))
  221. }
  222. .preferredColorScheme(Storage.shared.forceDarkMode.value ? .dark : nil)
  223. .navigationTitle("Remote Settings")
  224. .navigationBarTitleDisplayMode(.inline)
  225. }
  226. // MARK: - Custom Row for Remote Type Selection
  227. private func remoteTypeRow(type: RemoteType, label: String, isEnabled: Bool) -> some View {
  228. Button(action: {
  229. if isEnabled {
  230. viewModel.remoteType = type
  231. }
  232. }) {
  233. HStack {
  234. Text(label)
  235. Spacer()
  236. if viewModel.remoteType == type {
  237. Image(systemName: "checkmark")
  238. .foregroundColor(.accentColor)
  239. }
  240. }
  241. }
  242. // If isEnabled is false, user can see the row but not tap it.
  243. .disabled(!isEnabled)
  244. .foregroundColor(isEnabled ? .primary : .gray)
  245. }
  246. // MARK: - Validation Error Handler
  247. private func handleValidationError(_ message: String) {
  248. alertMessage = message
  249. alertType = .validation
  250. showAlert = true
  251. }
  252. private var guardrailsSection: some View {
  253. Section(header: Text("Guardrails")) {
  254. HStack {
  255. Text("Max Bolus")
  256. Spacer()
  257. TextFieldWithToolBar(
  258. quantity: $viewModel.maxBolus,
  259. maxLength: 5,
  260. unit: HKUnit.internationalUnit(),
  261. allowDecimalSeparator: true,
  262. minValue: HKQuantity(unit: .internationalUnit(), doubleValue: 0),
  263. maxValue: HKQuantity(unit: .internationalUnit(), doubleValue: 10),
  264. onValidationError: { message in
  265. handleValidationError(message)
  266. }
  267. )
  268. .frame(width: 100)
  269. Text("U")
  270. .foregroundColor(.secondary)
  271. }
  272. HStack {
  273. Text("Max Carbs")
  274. Spacer()
  275. TextFieldWithToolBar(
  276. quantity: $viewModel.maxCarbs,
  277. maxLength: 4,
  278. unit: HKUnit.gram(),
  279. allowDecimalSeparator: true,
  280. minValue: HKQuantity(unit: .gram(), doubleValue: 0),
  281. maxValue: HKQuantity(unit: .gram(), doubleValue: 100),
  282. onValidationError: { message in
  283. handleValidationError(message)
  284. }
  285. )
  286. .frame(width: 100)
  287. Text("g")
  288. .foregroundColor(.secondary)
  289. }
  290. if device.value == "Trio" {
  291. HStack {
  292. Text("Max Protein")
  293. Spacer()
  294. TextFieldWithToolBar(
  295. quantity: $viewModel.maxProtein,
  296. maxLength: 4,
  297. unit: HKUnit.gram(),
  298. allowDecimalSeparator: true,
  299. minValue: HKQuantity(unit: .gram(), doubleValue: 0),
  300. maxValue: HKQuantity(unit: .gram(), doubleValue: 100),
  301. onValidationError: { message in
  302. handleValidationError(message)
  303. }
  304. )
  305. .frame(width: 100)
  306. Text("g")
  307. .foregroundColor(.secondary)
  308. }
  309. HStack {
  310. Text("Max Fat")
  311. Spacer()
  312. TextFieldWithToolBar(
  313. quantity: $viewModel.maxFat,
  314. maxLength: 4,
  315. unit: HKUnit.gram(),
  316. allowDecimalSeparator: true,
  317. minValue: HKQuantity(unit: .gram(), doubleValue: 0),
  318. maxValue: HKQuantity(unit: .gram(), doubleValue: 100),
  319. onValidationError: { message in
  320. handleValidationError(message)
  321. }
  322. )
  323. .frame(width: 100)
  324. Text("g")
  325. .foregroundColor(.secondary)
  326. }
  327. }
  328. }
  329. }
  330. }