RemoteSettingsView.swift 19 KB

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