RemoteSettingsView.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. if viewModel.areTeamIdsDifferent {
  227. Section(header: Text("Return Notification Settings"), footer: Text("Because LoopFollow and the target app were built with different Team IDs, you must provide the APNS credentials for LoopFollow below.").font(.caption)) {
  228. HStack {
  229. Text("Return APNS Key ID")
  230. TogglableSecureInput(
  231. placeholder: "Enter Key ID for LoopFollow",
  232. text: $viewModel.returnKeyId,
  233. style: .singleLine
  234. )
  235. }
  236. VStack(alignment: .leading) {
  237. Text("Return APNS Key")
  238. TogglableSecureInput(
  239. placeholder: "Paste APNS Key for LoopFollow",
  240. text: $viewModel.returnApnsKey,
  241. style: .multiLine
  242. )
  243. .frame(minHeight: 110)
  244. }
  245. }
  246. }
  247. }
  248. }
  249. .alert(isPresented: $showAlert) {
  250. switch alertType {
  251. case .validation:
  252. return Alert(
  253. title: Text("Validation Error"),
  254. message: Text(alertMessage ?? "Invalid input."),
  255. dismissButton: .default(Text("OK"))
  256. )
  257. case .qrCodeError:
  258. return Alert(
  259. title: Text("QR Code Error"),
  260. message: Text(alertMessage ?? "An error occurred while processing the QR code."),
  261. dismissButton: .default(Text("OK"))
  262. )
  263. case .urlTokenValidation:
  264. return Alert(
  265. title: Text("URL/Token Validation"),
  266. message: Text(viewModel.validationMessage),
  267. dismissButton: .default(Text("OK")) {
  268. viewModel.showURLTokenValidation = false
  269. }
  270. )
  271. case .urlTokenUpdate:
  272. return Alert(
  273. title: Text("URL/Token Update"),
  274. message: Text(viewModel.validationMessage),
  275. dismissButton: .default(Text("OK")) {
  276. viewModel.showURLTokenValidation = false
  277. }
  278. )
  279. case .none:
  280. return Alert(title: Text("Unknown Alert"))
  281. }
  282. }
  283. .sheet(isPresented: $viewModel.isShowingLoopAPNSScanner) {
  284. SimpleQRCodeScannerView { result in
  285. viewModel.handleLoopAPNSQRCodeScanResult(result)
  286. }
  287. }
  288. .sheet(isPresented: $viewModel.isShowingQRCodeScanner) {
  289. SimpleQRCodeScannerView { result in
  290. viewModel.handleRemoteCommandQRCodeScanResult(result)
  291. }
  292. }
  293. .sheet(isPresented: $viewModel.isShowingQRCodeDisplay) {
  294. NavigationView {
  295. VStack {
  296. if let qrCodeString = viewModel.generateQRCodeForCurrentSettings() {
  297. QRCodeDisplayView(qrCodeString: qrCodeString)
  298. .padding()
  299. } else {
  300. Text("Failed to generate QR code")
  301. .foregroundColor(.red)
  302. .padding()
  303. }
  304. }
  305. .navigationTitle("Share Remote Settings")
  306. .navigationBarTitleDisplayMode(.inline)
  307. .navigationBarItems(trailing: Button("Done") {
  308. viewModel.isShowingQRCodeDisplay = false
  309. })
  310. }
  311. }
  312. .sheet(isPresented: $viewModel.showURLTokenValidation) {
  313. NavigationView {
  314. URLTokenValidationView(
  315. settings: viewModel.pendingSettings!,
  316. shouldPromptForURL: viewModel.shouldPromptForURL,
  317. shouldPromptForToken: viewModel.shouldPromptForToken,
  318. message: viewModel.validationMessage,
  319. onConfirm: { confirmedSettings in
  320. confirmedSettings.applyToStorage()
  321. viewModel.updateViewModelFromStorage()
  322. viewModel.showURLTokenValidation = false
  323. viewModel.pendingSettings = nil
  324. LogManager.shared.log(category: .remote, message: "Remote command settings imported from QR code with URL/token updates")
  325. },
  326. onCancel: {
  327. viewModel.showURLTokenValidation = false
  328. viewModel.pendingSettings = nil
  329. }
  330. )
  331. }
  332. }
  333. .onAppear {
  334. // Reset timer state so it shows '-' until first tick
  335. otpTimeRemaining = nil
  336. // Update view model from storage to ensure UI is current
  337. viewModel.updateViewModelFromStorage()
  338. }
  339. .onReceive(otpTimer) { _ in
  340. let now = Date().timeIntervalSince1970
  341. otpTimeRemaining = Int(otpPeriod - (now.truncatingRemainder(dividingBy: otpPeriod)))
  342. }
  343. .onReceive(viewModel.$qrCodeErrorMessage) { errorMessage in
  344. if let errorMessage = errorMessage, !errorMessage.isEmpty {
  345. handleQRCodeError(errorMessage)
  346. // Clear the error message after showing the alert
  347. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  348. viewModel.qrCodeErrorMessage = nil
  349. }
  350. }
  351. }
  352. .onReceive(viewModel.$showURLTokenValidation) { showValidation in
  353. if showValidation {
  354. // The sheet will be shown automatically due to the binding
  355. }
  356. }
  357. .preferredColorScheme(Storage.shared.forceDarkMode.value ? .dark : nil)
  358. .navigationTitle("Remote Settings")
  359. .navigationBarTitleDisplayMode(.inline)
  360. }
  361. // MARK: - Custom Row for Remote Type Selection
  362. private func remoteTypeRow(type: RemoteType, label: String, isEnabled: Bool) -> some View {
  363. Button(action: {
  364. if isEnabled {
  365. viewModel.remoteType = type
  366. }
  367. }) {
  368. HStack {
  369. Text(label)
  370. Spacer()
  371. if viewModel.remoteType == type {
  372. Image(systemName: "checkmark")
  373. .foregroundColor(.accentColor)
  374. }
  375. }
  376. }
  377. // If isEnabled is false, user can see the row but not tap it.
  378. .disabled(!isEnabled)
  379. .foregroundColor(isEnabled ? .primary : .gray)
  380. }
  381. // MARK: - Validation Error Handler
  382. private func handleValidationError(_ message: String) {
  383. alertMessage = message
  384. alertType = .validation
  385. showAlert = true
  386. }
  387. // MARK: - QR Code Error Handler
  388. private func handleQRCodeError(_ message: String) {
  389. alertMessage = message
  390. alertType = .qrCodeError
  391. showAlert = true
  392. }
  393. private var guardrailsSection: some View {
  394. Section(header: Text("Guardrails")) {
  395. HStack {
  396. Text("Max Bolus")
  397. Spacer()
  398. TextFieldWithToolBar(
  399. quantity: $viewModel.maxBolus,
  400. maxLength: 5,
  401. unit: HKUnit.internationalUnit(),
  402. allowDecimalSeparator: true,
  403. minValue: HKQuantity(unit: .internationalUnit(), doubleValue: 0),
  404. maxValue: HKQuantity(unit: .internationalUnit(), doubleValue: 10),
  405. onValidationError: { message in
  406. handleValidationError(message)
  407. }
  408. )
  409. .frame(width: 100)
  410. Text("U")
  411. .foregroundColor(.secondary)
  412. }
  413. HStack {
  414. Text("Max Carbs")
  415. Spacer()
  416. TextFieldWithToolBar(
  417. quantity: $viewModel.maxCarbs,
  418. maxLength: 4,
  419. unit: HKUnit.gram(),
  420. allowDecimalSeparator: true,
  421. minValue: HKQuantity(unit: .gram(), doubleValue: 0),
  422. maxValue: HKQuantity(unit: .gram(), doubleValue: 100),
  423. onValidationError: { message in
  424. handleValidationError(message)
  425. }
  426. )
  427. .frame(width: 100)
  428. Text("g")
  429. .foregroundColor(.secondary)
  430. }
  431. if device.value == "Trio" {
  432. HStack {
  433. Text("Max Protein")
  434. Spacer()
  435. TextFieldWithToolBar(
  436. quantity: $viewModel.maxProtein,
  437. maxLength: 4,
  438. unit: HKUnit.gram(),
  439. allowDecimalSeparator: true,
  440. minValue: HKQuantity(unit: .gram(), doubleValue: 0),
  441. maxValue: HKQuantity(unit: .gram(), doubleValue: 100),
  442. onValidationError: { message in
  443. handleValidationError(message)
  444. }
  445. )
  446. .frame(width: 100)
  447. Text("g")
  448. .foregroundColor(.secondary)
  449. }
  450. HStack {
  451. Text("Max Fat")
  452. Spacer()
  453. TextFieldWithToolBar(
  454. quantity: $viewModel.maxFat,
  455. maxLength: 4,
  456. unit: HKUnit.gram(),
  457. allowDecimalSeparator: true,
  458. minValue: HKQuantity(unit: .gram(), doubleValue: 0),
  459. maxValue: HKQuantity(unit: .gram(), doubleValue: 100),
  460. onValidationError: { message in
  461. handleValidationError(message)
  462. }
  463. )
  464. .frame(width: 100)
  465. Text("g")
  466. .foregroundColor(.secondary)
  467. }
  468. }
  469. }
  470. }
  471. }