RemoteSettingsView.swift 18 KB

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