RemoteSettingsView.swift 19 KB

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