RemoteSettingsView.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. // LoopFollow
  2. // RemoteSettingsView.swift
  3. import AVFoundation
  4. import HealthKit
  5. import SwiftUI
  6. import UIKit
  7. struct RemoteSettingsView: View {
  8. @ObservedObject var viewModel: RemoteSettingsViewModel
  9. @ObservedObject private var device = Storage.shared.device
  10. @ObservedObject var bolusIncrement = Storage.shared.bolusIncrement
  11. @State private var showAlert: Bool = false
  12. @State private var alertType: AlertType? = nil
  13. @State private var alertMessage: String? = nil
  14. @State private var otpTimeRemaining: Int? = nil
  15. private let otpPeriod: TimeInterval = 30
  16. private var otpTimer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
  17. enum AlertType {
  18. case validation
  19. case urlTokenValidation
  20. case urlTokenUpdate
  21. }
  22. init(viewModel: RemoteSettingsViewModel) {
  23. self.viewModel = viewModel
  24. }
  25. var body: some View {
  26. Form {
  27. // MARK: - Remote Type Section (Custom Rows)
  28. Section {
  29. remoteTypeRow(
  30. type: .none,
  31. label: "None",
  32. isEnabled: true
  33. )
  34. remoteTypeRow(
  35. type: .loopAPNS,
  36. label: "Loop Remote Control",
  37. isEnabled: viewModel.isLoopDevice
  38. )
  39. remoteTypeRow(
  40. type: .trc,
  41. label: "Trio Remote Control",
  42. isEnabled: viewModel.isTrioDevice
  43. )
  44. remoteTypeRow(
  45. type: .nightscout,
  46. label: "Nightscout",
  47. isEnabled: viewModel.isTrioDevice
  48. )
  49. Text("Nightscout should be used for Trio 0.2.x.")
  50. .font(.footnote)
  51. .foregroundColor(.secondary)
  52. }
  53. // MARK: - Import/Export Settings Section
  54. Section {
  55. NavigationLink(destination: ImportExportSettingsView()) {
  56. HStack {
  57. Image(systemName: "square.and.arrow.down")
  58. .foregroundColor(.blue)
  59. Text("Import/Export Settings")
  60. }
  61. }
  62. }
  63. // MARK: - Meal Section (for TRC only)
  64. if viewModel.remoteType == .trc {
  65. Section(header: Text("Meal Settings")) {
  66. Toggle("Meal with Bolus", isOn: $viewModel.mealWithBolus)
  67. .toggleStyle(SwitchToggleStyle())
  68. Toggle("Meal with Fat/Protein", isOn: $viewModel.mealWithFatProtein)
  69. .toggleStyle(SwitchToggleStyle())
  70. }
  71. }
  72. // MARK: - Guardrails Section (shown for both TRC and Loop)
  73. if viewModel.remoteType == .trc || viewModel.remoteType == .loopAPNS {
  74. guardrailsSection
  75. }
  76. if !Storage.shared.bolusIncrementDetected.value {
  77. Section(header: Text("Bolus Increment")) {
  78. HStack {
  79. Text("Increment")
  80. Spacer()
  81. TextFieldWithToolBar(
  82. quantity: $bolusIncrement.value,
  83. maxLength: 5,
  84. unit: HKUnit.internationalUnit(),
  85. allowDecimalSeparator: true,
  86. minValue: HKQuantity(unit: .internationalUnit(), doubleValue: 0.001),
  87. maxValue: HKQuantity(unit: .internationalUnit(), doubleValue: 1),
  88. onValidationError: { message in
  89. handleValidationError(message)
  90. }
  91. )
  92. .frame(width: 100)
  93. Text("U")
  94. .foregroundColor(.secondary)
  95. }
  96. }
  97. }
  98. // MARK: - User Information Section
  99. if viewModel.remoteType != .none && viewModel.remoteType != .loopAPNS {
  100. Section(header: Text("User Information")) {
  101. HStack {
  102. Text("User")
  103. TextField("Enter User", text: $viewModel.user)
  104. .autocapitalization(.none)
  105. .disableAutocorrection(true)
  106. .multilineTextAlignment(.trailing)
  107. }
  108. }
  109. }
  110. // MARK: - Trio Remote Control Settings
  111. if viewModel.remoteType == .trc {
  112. Section(header: Text("Trio Remote Control Settings")) {
  113. HStack {
  114. Text("Shared Secret")
  115. TogglableSecureInput(
  116. placeholder: "Enter Shared Secret",
  117. text: $viewModel.sharedSecret,
  118. style: .singleLine
  119. )
  120. }
  121. if viewModel.areTeamIdsDifferent {
  122. HStack {
  123. Text("APNS Key ID")
  124. TogglableSecureInput(
  125. placeholder: "Enter APNS Key ID",
  126. text: $viewModel.remoteKeyId,
  127. style: .singleLine
  128. )
  129. }
  130. VStack(alignment: .leading) {
  131. Text("APNS Key")
  132. TogglableSecureInput(
  133. placeholder: "Paste APNS Key",
  134. text: $viewModel.remoteApnsKey,
  135. style: .multiLine
  136. )
  137. .frame(minHeight: 110)
  138. }
  139. }
  140. }
  141. // MARK: - Debug / Info
  142. Section(header: Text("Debug / Info")) {
  143. Text("Device Token: \(Storage.shared.deviceToken.value)")
  144. Text("APNS Environment: \(Storage.shared.productionEnvironment.value ? "Production" : "Development")")
  145. Text("Team ID: \(Storage.shared.teamId.value ?? "")")
  146. Text("Bundle ID: \(Storage.shared.bundleId.value)")
  147. if Storage.shared.bolusIncrementDetected.value {
  148. Text("Bolus Increment: \(Storage.shared.bolusIncrement.value.doubleValue(for: .internationalUnit()), specifier: "%.3f") U")
  149. }
  150. }
  151. }
  152. // MARK: - Loop APNS Settings
  153. if viewModel.remoteType == .loopAPNS {
  154. Section(header: Text("Loop APNS Configuration")) {
  155. HStack {
  156. Text("Developer Team ID")
  157. TogglableSecureInput(
  158. placeholder: "Enter Team ID",
  159. text: $viewModel.loopDeveloperTeamId,
  160. style: .singleLine
  161. )
  162. }
  163. if viewModel.areTeamIdsDifferent {
  164. HStack {
  165. Text("APNS Key ID")
  166. TogglableSecureInput(
  167. placeholder: "Enter APNS Key ID",
  168. text: $viewModel.remoteKeyId,
  169. style: .singleLine
  170. )
  171. }
  172. VStack(alignment: .leading) {
  173. Text("APNS Key")
  174. TogglableSecureInput(
  175. placeholder: "Paste APNS Key",
  176. text: $viewModel.remoteApnsKey,
  177. style: .multiLine
  178. )
  179. .frame(minHeight: 110)
  180. }
  181. }
  182. HStack {
  183. Text("QR Code URL")
  184. TextField("Enter QR code URL or scan from Loop app", text: $viewModel.loopAPNSQrCodeURL)
  185. .textFieldStyle(RoundedBorderTextFieldStyle())
  186. .autocapitalization(.none)
  187. .disableAutocorrection(true)
  188. }
  189. Button(action: {
  190. viewModel.isShowingLoopAPNSScanner = true
  191. }) {
  192. HStack {
  193. Image(systemName: "qrcode.viewfinder")
  194. Text("Scan QR Code from Loop App")
  195. }
  196. }
  197. .buttonStyle(.borderedProminent)
  198. .frame(maxWidth: .infinity)
  199. .padding(.vertical, 10)
  200. HStack {
  201. Text("Environment")
  202. Spacer()
  203. Toggle("Production", isOn: $viewModel.productionEnvironment)
  204. .toggleStyle(SwitchToggleStyle())
  205. }
  206. Text("Production is used for browser builders and should be switched off for Xcode builders")
  207. .font(.caption)
  208. .foregroundColor(.secondary)
  209. }
  210. if let errorMessage = viewModel.loopAPNSErrorMessage, !errorMessage.isEmpty {
  211. Section {
  212. Text(errorMessage)
  213. .foregroundColor(.red)
  214. .font(.caption)
  215. }
  216. }
  217. Section(header: Text("Debug / Info")) {
  218. Text("Device Token: \(Storage.shared.deviceToken.value)")
  219. Text("Bundle ID: \(Storage.shared.bundleId.value)")
  220. if let otpCode = TOTPGenerator.extractOTPFromURL(Storage.shared.loopAPNSQrCodeURL.value) {
  221. HStack {
  222. Text("Current TOTP Code:")
  223. Text(otpCode)
  224. .font(.system(.body, design: .monospaced))
  225. .foregroundColor(.green)
  226. .padding(.vertical, 2)
  227. .padding(.horizontal, 6)
  228. .background(Color.green.opacity(0.1))
  229. .cornerRadius(4)
  230. Text("(" + (otpTimeRemaining.map { "\($0)s left" } ?? "-") + ")")
  231. .font(.caption)
  232. .foregroundColor(.secondary)
  233. }
  234. } else {
  235. Text("TOTP Code: Invalid QR code URL")
  236. .foregroundColor(.red)
  237. }
  238. if Storage.shared.bolusIncrementDetected.value {
  239. Text("Bolus Increment: \(Storage.shared.bolusIncrement.value.doubleValue(for: .internationalUnit()), specifier: "%.3f") U")
  240. }
  241. }
  242. }
  243. }
  244. .alert(isPresented: $showAlert) {
  245. switch alertType {
  246. case .validation:
  247. return Alert(
  248. title: Text("Validation Error"),
  249. message: Text(alertMessage ?? "Invalid input."),
  250. dismissButton: .default(Text("OK"))
  251. )
  252. case .urlTokenValidation:
  253. return Alert(
  254. title: Text("URL/Token Validation"),
  255. message: Text(viewModel.validationMessage),
  256. dismissButton: .default(Text("OK")) {
  257. viewModel.showURLTokenValidation = false
  258. }
  259. )
  260. case .urlTokenUpdate:
  261. return Alert(
  262. title: Text("URL/Token Update"),
  263. message: Text(viewModel.validationMessage),
  264. dismissButton: .default(Text("OK")) {
  265. viewModel.showURLTokenValidation = false
  266. }
  267. )
  268. case .none:
  269. return Alert(title: Text("Unknown Alert"))
  270. }
  271. }
  272. .sheet(isPresented: $viewModel.isShowingLoopAPNSScanner) {
  273. SimpleQRCodeScannerView { result in
  274. viewModel.handleLoopAPNSQRCodeScanResult(result)
  275. }
  276. }
  277. .sheet(isPresented: $viewModel.showURLTokenValidation) {
  278. NavigationView {
  279. URLTokenValidationView(
  280. settings: viewModel.pendingSettings!,
  281. shouldPromptForURL: viewModel.shouldPromptForURL,
  282. shouldPromptForToken: viewModel.shouldPromptForToken,
  283. message: viewModel.validationMessage,
  284. onConfirm: { confirmedSettings in
  285. confirmedSettings.applyToStorage()
  286. viewModel.updateViewModelFromStorage()
  287. viewModel.showURLTokenValidation = false
  288. viewModel.pendingSettings = nil
  289. LogManager.shared.log(category: .remote, message: "Remote command settings imported from QR code with URL/token updates")
  290. },
  291. onCancel: {
  292. viewModel.showURLTokenValidation = false
  293. viewModel.pendingSettings = nil
  294. }
  295. )
  296. }
  297. }
  298. .onAppear {
  299. // Reset timer state so it shows '-' until first tick
  300. otpTimeRemaining = nil
  301. // Update view model from storage to ensure UI is current
  302. viewModel.updateViewModelFromStorage()
  303. }
  304. .onReceive(otpTimer) { _ in
  305. let now = Date().timeIntervalSince1970
  306. otpTimeRemaining = Int(otpPeriod - (now.truncatingRemainder(dividingBy: otpPeriod)))
  307. }
  308. .onReceive(viewModel.$showURLTokenValidation) { showValidation in
  309. if showValidation {
  310. // The sheet will be shown automatically due to the binding
  311. }
  312. }
  313. .preferredColorScheme(Storage.shared.appearanceMode.value.colorScheme)
  314. .navigationTitle("Remote Settings")
  315. .navigationBarTitleDisplayMode(.inline)
  316. }
  317. // MARK: - Custom Row for Remote Type Selection
  318. private func remoteTypeRow(type: RemoteType, label: String, isEnabled: Bool) -> some View {
  319. Button(action: {
  320. if isEnabled {
  321. viewModel.remoteType = type
  322. }
  323. }) {
  324. HStack {
  325. Text(label)
  326. Spacer()
  327. if viewModel.remoteType == type {
  328. Image(systemName: "checkmark")
  329. .foregroundColor(.accentColor)
  330. }
  331. }
  332. }
  333. // If isEnabled is false, user can see the row but not tap it.
  334. .disabled(!isEnabled)
  335. .foregroundColor(isEnabled ? .primary : .gray)
  336. }
  337. // MARK: - Validation Error Handler
  338. private func handleValidationError(_ message: String) {
  339. alertMessage = message
  340. alertType = .validation
  341. showAlert = true
  342. }
  343. private var guardrailsSection: some View {
  344. Section(header: Text("Guardrails")) {
  345. HStack {
  346. Text("Max Bolus")
  347. Spacer()
  348. TextFieldWithToolBar(
  349. quantity: $viewModel.maxBolus,
  350. maxLength: 5,
  351. unit: HKUnit.internationalUnit(),
  352. allowDecimalSeparator: true,
  353. minValue: HKQuantity(unit: .internationalUnit(), doubleValue: 0),
  354. maxValue: HKQuantity(unit: .internationalUnit(), doubleValue: 10),
  355. onValidationError: { message in
  356. handleValidationError(message)
  357. }
  358. )
  359. .frame(width: 100)
  360. Text("U")
  361. .foregroundColor(.secondary)
  362. }
  363. HStack {
  364. Text("Max Carbs")
  365. Spacer()
  366. TextFieldWithToolBar(
  367. quantity: $viewModel.maxCarbs,
  368. maxLength: 4,
  369. unit: HKUnit.gram(),
  370. allowDecimalSeparator: true,
  371. minValue: HKQuantity(unit: .gram(), doubleValue: 0),
  372. maxValue: HKQuantity(unit: .gram(), doubleValue: 100),
  373. onValidationError: { message in
  374. handleValidationError(message)
  375. }
  376. )
  377. .frame(width: 100)
  378. Text("g")
  379. .foregroundColor(.secondary)
  380. }
  381. if device.value == "Trio" {
  382. HStack {
  383. Text("Max Fat")
  384. Spacer()
  385. TextFieldWithToolBar(
  386. quantity: $viewModel.maxFat,
  387. maxLength: 4,
  388. unit: HKUnit.gram(),
  389. allowDecimalSeparator: true,
  390. minValue: HKQuantity(unit: .gram(), doubleValue: 0),
  391. maxValue: HKQuantity(unit: .gram(), doubleValue: 100),
  392. onValidationError: { message in
  393. handleValidationError(message)
  394. }
  395. )
  396. .frame(width: 100)
  397. Text("g")
  398. .foregroundColor(.secondary)
  399. }
  400. HStack {
  401. Text("Max Protein")
  402. Spacer()
  403. TextFieldWithToolBar(
  404. quantity: $viewModel.maxProtein,
  405. maxLength: 4,
  406. unit: HKUnit.gram(),
  407. allowDecimalSeparator: true,
  408. minValue: HKQuantity(unit: .gram(), doubleValue: 0),
  409. maxValue: HKQuantity(unit: .gram(), doubleValue: 100),
  410. onValidationError: { message in
  411. handleValidationError(message)
  412. }
  413. )
  414. .frame(width: 100)
  415. Text("g")
  416. .foregroundColor(.secondary)
  417. }
  418. }
  419. }
  420. }
  421. }