DomainDig/IntegrationsView.swift
709 lines · 29905 bytes
9 symbols in this file
1import SwiftUI
2
3struct IntegrationsSettingsView: View {
4 @State private var integrationService = IntegrationService.shared
5 @State private var editingTarget: IntegrationTarget?
6 @State private var showingCreateSheet = false
7
8 var body: some View {
9 List {
10 Section("Overview") {
11 LabeledContent("Integrations", value: "\(integrationService.targets.count)")
12 LabeledContent("Queued Deliveries", value: "\(integrationService.queue.count)")
13 LabeledContent("Recent Log Entries", value: "\(integrationService.deliveryRecords.count)")
14
15 if let statusMessage = integrationService.statusMessage {
16 Text(statusMessage)
17 .font(.caption)
18 .foregroundStyle(ThemeToken.textSecondary)
19 }
20
21 Button("Process Queue Now") {
22 integrationService.processQueueNow()
23 }
24 }
25
26 Section("Targets") {
27 if integrationService.targets.isEmpty {
28 Text("No integrations configured.")
29 .foregroundStyle(ThemeToken.textSecondary)
30 } else {
31 ForEach(integrationService.targets) { target in
32 NavigationLink {
33 IntegrationDetailView(
34 integrationID: target.id,
35 onEdit: {
36 editingTarget = target
37 }
38 )
39 } label: {
40 VStack(alignment: .leading, spacing: 4) {
41 HStack {
42 Text(target.name)
43 Spacer()
44 Text(target.type.title)
45 .foregroundStyle(ThemeToken.textSecondary)
46 }
47
48 Text(summary(for: target))
49 .font(.caption)
50 .foregroundStyle(ThemeToken.textSecondary)
51
52 if !target.isEnabled {
53 Text("Disabled")
54 .font(.caption2)
55 .foregroundStyle(ThemeToken.warning)
56 }
57 }
58 }
59 }
60 }
61
62 Button("Add Integration") {
63 showingCreateSheet = true
64 }
65 }
66 }
67 .navigationTitle("Integrations")
68 .sheet(isPresented: $showingCreateSheet) {
69 NavigationStack {
70 IntegrationEditorView(existingTarget: nil)
71 }
72 }
73 .sheet(item: $editingTarget) { target in
74 NavigationStack {
75 IntegrationEditorView(existingTarget: target)
76 }
77 }
78 .onAppear {
79 integrationService.refresh()
80 }
81 }
82
83 private func summary(for target: IntegrationTarget) -> String {
84 switch target.configuration {
85 case .webhook(let configuration):
86 return configuration.endpointDisplayHost.isEmpty ? "Webhook" : configuration.endpointDisplayHost
87 case .slack(let configuration):
88 return configuration.destinationLabel
89 case .email(let configuration):
90 return configuration.recipientAddresses.joined(separator: ", ")
91 case .s3(let configuration):
92 return configuration.bucket.isEmpty ? "S3 bucket" : configuration.bucket
93 }
94 }
95}
96
97private struct IntegrationDetailView: View {
98 @Environment(\.dismiss) private var dismiss
99 @State private var integrationService = IntegrationService.shared
100
101 let integrationID: UUID
102 let onEdit: () -> Void
103
104 private var target: IntegrationTarget? {
105 integrationService.targets.first(where: { $0.id == integrationID })
106 }
107
108 var body: some View {
109 List {
110 if let target {
111 Section("Configuration") {
112 LabeledContent("Type", value: target.type.title)
113 LabeledContent("Status", value: target.isEnabled ? "Enabled" : "Disabled")
114 LabeledContent("Destination", value: destination(for: target))
115 LabeledContent("Minimum Severity", value: target.filters.minimumSeverity.title)
116 if !target.filters.domains.isEmpty {
117 LabeledContent("Domains", value: target.filters.domains.joined(separator: ", "))
118 }
119 }
120
121 Section("Actions") {
122 Button("Edit Integration") {
123 onEdit()
124 }
125
126 Button("Send Test Event") {
127 integrationService.sendTest(for: target.id)
128 }
129
130 Button(target.isEnabled ? "Disable" : "Enable") {
131 integrationService.setEnabled(!target.isEnabled, for: target.id)
132 }
133
134 Button("Delete Integration", role: .destructive) {
135 integrationService.delete(targetID: target.id)
136 dismiss()
137 }
138 }
139
140 Section("Delivery Log") {
141 if integrationService.deliveryRecords(for: target.id).isEmpty {
142 Text("No deliveries yet.")
143 .foregroundStyle(ThemeToken.textSecondary)
144 } else {
145 ForEach(integrationService.deliveryRecords(for: target.id), id: \.id) { record in
146 VStack(alignment: .leading, spacing: 4) {
147 HStack {
148 Text(record.status.title)
149 Spacer()
150 Text(record.timestamp.formatted(date: .abbreviated, time: .shortened))
151 .font(.caption)
152 .foregroundStyle(ThemeToken.textSecondary)
153 }
154
155 Text(record.summary)
156 .font(.subheadline)
157
158 Text(record.destination)
159 .font(.caption)
160 .foregroundStyle(ThemeToken.textSecondary)
161
162 if let failureReason = record.failureReason {
163 let failureStyle = record.status == .skipped ? AnyShapeStyle(.secondary) : AnyShapeStyle(ThemeToken.critical)
164 Text(failureReason)
165 .font(.caption)
166 .foregroundStyle(failureStyle)
167 }
168 }
169 }
170 }
171 }
172 } else {
173 Text("Integration not found.")
174 .foregroundStyle(ThemeToken.textSecondary)
175 }
176 }
177 .navigationTitle(target?.name ?? "Integration")
178 }
179
180 private func destination(for target: IntegrationTarget) -> String {
181 switch target.configuration {
182 case .webhook(let configuration):
183 return configuration.endpointDisplayHost
184 case .slack(let configuration):
185 return configuration.destinationLabel
186 case .email(let configuration):
187 return configuration.recipientAddresses.joined(separator: ", ")
188 case .s3(let configuration):
189 return configuration.bucket
190 }
191 }
192}
193
194private struct IntegrationEditorView: View {
195 @Environment(\.dismiss) private var dismiss
196 @State private var integrationService = IntegrationService.shared
197
198 let existingTarget: IntegrationTarget?
199
200 @State private var type: IntegrationType = .webhook
201 @State private var name: String = ""
202 @State private var isEnabled = true
203 @State private var minimumSeverity: EventSeverity = .warning
204 @State private var selectedEventTypes: Set<MonitoringEventType> = Set(MonitoringEventType.filterable)
205 @State private var s3Endpoint = ""
206 @State private var s3Region = "us-east-1"
207 @State private var s3Bucket = ""
208 @State private var s3KeyPrefix = "domaindig"
209 @State private var s3UsesPathStyle = false
210 @State private var s3AccessKeyID = ""
211 @State private var s3SecretAccessKey = ""
212 @State private var s3Triggers: Set<S3ExportTrigger> = S3ExportTrigger.defaults
213 @State private var s3ExtraFormats: Set<DomainExportFormat> = []
214 @State private var domainsText = ""
215
216 @State private var webhookURL = ""
217 @State private var slackWebhookURL = ""
218 @State private var emailHost = ""
219 @State private var emailPort = "465"
220 @State private var emailUsername = ""
221 @State private var emailPassword = ""
222 @State private var senderAddress = ""
223 @State private var recipientAddresses = ""
224 @State private var smtpSecurity: SMTPSecurityMode = .directTLS
225
226 @State private var validationMessage: String?
227
228 var body: some View {
229 Form {
230 Section("Integration") {
231 AdaptivePicker("Type", selection: $type) {
232 ForEach(selectableTypes) { integrationType in
233 Text(integrationType.title).tag(integrationType)
234 }
235 }
236 .disabled(existingTarget != nil)
237
238 if !FeatureAccessService.hasAccess(to: .bucketExport) {
239 Text("Export to your own bucket is \(FeatureAccessService.upgradeMessage(for: .bucketExport)).")
240 .font(.caption)
241 .foregroundStyle(ThemeToken.textSecondary)
242 }
243
244 TextField("Name", text: $name)
245 Toggle("Enabled", isOn: $isEnabled)
246 }
247
248 Section("Routing Rules") {
249 AdaptivePicker("Minimum Severity", selection: $minimumSeverity) {
250 ForEach(EventSeverity.allCases) { severity in
251 Text(severity.title).tag(severity)
252 }
253 }
254
255 TextField("Domains (comma-separated)", text: $domainsText)
256 .textInputAutocapitalization(.never)
257 .autocorrectionDisabled()
258
259 ForEach(MonitoringEventType.filterable, id: \.self) { eventType in
260 Toggle(
261 eventType.title,
262 isOn: Binding(
263 get: { selectedEventTypes.contains(eventType) },
264 set: { isSelected in
265 if isSelected {
266 selectedEventTypes.insert(eventType)
267 } else {
268 selectedEventTypes.remove(eventType)
269 }
270 }
271 )
272 )
273 }
274 }
275
276 switch type {
277 case .webhook:
278 Section("Webhook") {
279 TextField("https://example.com/webhook", text: $webhookURL)
280 .textInputAutocapitalization(.never)
281 .autocorrectionDisabled()
282 .keyboardType(.URL)
283
284 if existingTarget != nil {
285 Text("Saved webhook URL remains in Keychain unless you replace it.")
286 .font(.caption)
287 .foregroundStyle(ThemeToken.textSecondary)
288 }
289 }
290 case .slack:
291 Section("Slack") {
292 TextField("https://hooks.slack.com/services/...", text: $slackWebhookURL)
293 .textInputAutocapitalization(.never)
294 .autocorrectionDisabled()
295 .keyboardType(.URL)
296
297 if existingTarget != nil {
298 Text("Saved Slack webhook remains in Keychain unless you replace it.")
299 .font(.caption)
300 .foregroundStyle(ThemeToken.textSecondary)
301 }
302 }
303 case .email:
304 Section("SMTP") {
305 TextField("SMTP Host", text: $emailHost)
306 .textInputAutocapitalization(.never)
307 .autocorrectionDisabled()
308
309 TextField("Port", text: $emailPort)
310 .keyboardType(.numberPad)
311
312 Text("Port 465 with Direct TLS is supported. Port 587 (STARTTLS) is not.")
313 .font(.caption)
314 .foregroundStyle(ThemeToken.textSecondary)
315
316 TextField("Username", text: $emailUsername)
317 .textInputAutocapitalization(.never)
318 .autocorrectionDisabled()
319
320 SecureField(existingTarget == nil ? "Password" : "Replace Password", text: $emailPassword)
321
322 TextField("Sender Address", text: $senderAddress)
323 .textInputAutocapitalization(.never)
324 .autocorrectionDisabled()
325 .keyboardType(.emailAddress)
326
327 TextField("Recipients (comma-separated)", text: $recipientAddresses)
328 .textInputAutocapitalization(.never)
329 .autocorrectionDisabled()
330 .keyboardType(.emailAddress)
331
332 AdaptivePicker("Security", selection: $smtpSecurity) {
333 ForEach(SMTPSecurityMode.allCases) { mode in
334 Text(mode.title).tag(mode)
335 }
336 }
337
338 if existingTarget != nil {
339 Text("Saved SMTP password remains in Keychain unless you replace it.")
340 .font(.caption)
341 .foregroundStyle(ThemeToken.textSecondary)
342 }
343 }
344 case .s3:
345 Section("Bucket") {
346 TextField("https://s3.eu-central-1.amazonaws.com", text: $s3Endpoint)
347 .textInputAutocapitalization(.never)
348 .autocorrectionDisabled()
349 .keyboardType(.URL)
350
351 Text("Must be https. Signing puts your access key ID on the wire, and the signature with it.")
352 .font(.caption)
353 .foregroundStyle(ThemeToken.textSecondary)
354
355 TextField("Bucket", text: $s3Bucket)
356 .textInputAutocapitalization(.never)
357 .autocorrectionDisabled()
358
359 TextField("Region", text: $s3Region)
360 .textInputAutocapitalization(.never)
361 .autocorrectionDisabled()
362
363 TextField("Key prefix", text: $s3KeyPrefix)
364 .textInputAutocapitalization(.never)
365 .autocorrectionDisabled()
366
367 Toggle("Path-style addressing", isOn: $s3UsesPathStyle)
368
369 Text("Addresses the bucket as endpoint/bucket/key. MinIO needs this, and so do R2 custom domains.")
370 .font(.caption)
371 .foregroundStyle(ThemeToken.textSecondary)
372 }
373
374 Section("Credentials") {
375 TextField("Access key ID", text: $s3AccessKeyID)
376 .textInputAutocapitalization(.never)
377 .autocorrectionDisabled()
378
379 SecureField(
380 existingTarget == nil ? "Secret access key" : "Replace secret access key",
381 text: $s3SecretAccessKey
382 )
383
384 if existingTarget != nil {
385 Text("Saved secret access key remains in Keychain unless you replace it.")
386 .font(.caption)
387 .foregroundStyle(ThemeToken.textSecondary)
388 }
389 }
390
391 Section("Upload when") {
392 ForEach(S3ExportTrigger.allCases) { trigger in
393 Toggle(
394 isOn: Binding(
395 get: { s3Triggers.contains(trigger) },
396 set: { isOn in
397 if isOn {
398 s3Triggers.insert(trigger)
399 } else {
400 s3Triggers.remove(trigger)
401 }
402 }
403 )
404 ) {
405 VStack(alignment: .leading, spacing: 2) {
406 Text(trigger.title)
407 if let detail = trigger.detail {
408 Text(detail)
409 .font(.caption)
410 .foregroundStyle(ThemeToken.textSecondary)
411 }
412 }
413 }
414 }
415 }
416
417 Section("Formats") {
418 Text("JSON always uploads. The others are renderings of it.")
419 .font(.caption)
420 .foregroundStyle(ThemeToken.textSecondary)
421
422 ForEach([DomainExportFormat.pdf, .csv]) { format in
423 Toggle(
424 format.title,
425 isOn: Binding(
426 get: { s3ExtraFormats.contains(format) },
427 set: { isOn in
428 if isOn {
429 s3ExtraFormats.insert(format)
430 } else {
431 s3ExtraFormats.remove(format)
432 }
433 }
434 )
435 )
436 }
437 }
438 }
439
440 if let validationMessage {
441 Section {
442 Text(validationMessage)
443 .font(.caption)
444 .foregroundStyle(ThemeToken.critical)
445 }
446 }
447 }
448 .navigationTitle(existingTarget == nil ? "Add Integration" : "Edit Integration")
449 .toolbar {
450 ToolbarItem(placement: .cancellationAction) {
451 Button("Cancel") {
452 dismiss()
453 }
454 }
455
456 ToolbarItem(placement: .confirmationAction) {
457 Button("Save") {
458 save()
459 }
460 }
461 }
462 .onAppear {
463 populateFromExisting()
464 }
465 }
466
467 private func populateFromExisting() {
468 guard let existingTarget else { return }
469 type = existingTarget.type
470 name = existingTarget.name
471 isEnabled = existingTarget.isEnabled
472 minimumSeverity = existingTarget.filters.minimumSeverity
473 selectedEventTypes = existingTarget.filters.eventTypes
474 domainsText = existingTarget.filters.domains.joined(separator: ", ")
475
476 switch existingTarget.configuration {
477 case .webhook:
478 break
479 case .slack:
480 break
481 case .email(let configuration):
482 emailHost = configuration.smtpHost
483 emailPort = String(configuration.port)
484 emailUsername = configuration.username
485 senderAddress = configuration.senderAddress
486 recipientAddresses = configuration.recipientAddresses.joined(separator: ", ")
487 smtpSecurity = configuration.securityMode
488 case .s3(let configuration):
489 s3Endpoint = configuration.endpoint
490 s3Region = configuration.region
491 s3Bucket = configuration.bucket
492 s3KeyPrefix = configuration.keyPrefix
493 s3UsesPathStyle = configuration.usesPathStyle
494 s3AccessKeyID = configuration.accessKeyID
495 s3Triggers = configuration.triggers
496 s3ExtraFormats = configuration.extraFormats
497 }
498 }
499
500 private func save() {
501 validationMessage = nil
502
503 let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
504 guard !trimmedName.isEmpty else {
505 validationMessage = "Name is required."
506 return
507 }
508
509 let filters = IntegrationFilterSet(
510 minimumSeverity: minimumSeverity,
511 eventTypes: selectedEventTypes,
512 domains: domainsText
513 .split(separator: ",")
514 .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
515 .filter { !$0.isEmpty }
516 )
517
518 let targetID = existingTarget?.id ?? UUID()
519
520 do {
521 switch type {
522 case .webhook:
523 let existingReference: String? = {
524 guard case .webhook(let configuration) = existingTarget?.configuration else { return nil }
525 return configuration.credentialReference
526 }()
527 if webhookURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && existingReference == nil {
528 validationMessage = "Webhook URL is required."
529 return
530 }
531
532 let target = IntegrationTarget(
533 id: targetID,
534 type: .webhook,
535 name: trimmedName,
536 isEnabled: isEnabled,
537 configuration: .webhook(
538 WebhookIntegrationConfiguration(
539 endpointDisplayHost: existingWebhookDisplayHost(),
540 timeoutSeconds: 15,
541 additionalHeaders: [:],
542 credentialReference: existingReference
543 )
544 ),
545 filters: filters
546 )
547 try integrationService.upsert(
548 target: target,
549 webhookURL: webhookURL.nilIfBlank
550 )
551 case .slack:
552 let existingReference: String? = {
553 guard case .slack(let configuration) = existingTarget?.configuration else { return nil }
554 return configuration.credentialReference
555 }()
556 if slackWebhookURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && existingReference == nil {
557 validationMessage = "Slack webhook URL is required."
558 return
559 }
560
561 let target = IntegrationTarget(
562 id: targetID,
563 type: .slack,
564 name: trimmedName,
565 isEnabled: isEnabled,
566 configuration: .slack(
567 SlackIntegrationConfiguration(
568 destinationLabel: existingSlackDestination(),
569 credentialReference: existingReference
570 )
571 ),
572 filters: filters
573 )
574 try integrationService.upsert(
575 target: target,
576 slackWebhookURL: slackWebhookURL.nilIfBlank
577 )
578 case .email:
579 guard let port = Int(emailPort) else {
580 validationMessage = "SMTP port must be a number."
581 return
582 }
583
584 let recipients = recipientAddresses
585 .split(separator: ",")
586 .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
587 .filter { !$0.isEmpty }
588
589 let existingReference: String? = {
590 guard case .email(let configuration) = existingTarget?.configuration else { return nil }
591 return configuration.credentialReference
592 }()
593 if emailPassword.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && existingReference == nil {
594 validationMessage = "SMTP password is required."
595 return
596 }
597 if smtpSecurity != .directTLS, !emailUsername.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
598 validationMessage = "A username needs Direct TLS, usually on port 465. Without it the password would be sent in cleartext."
599 return
600 }
601
602 let target = IntegrationTarget(
603 id: targetID,
604 type: .email,
605 name: trimmedName,
606 isEnabled: isEnabled,
607 configuration: .email(
608 EmailIntegrationConfiguration(
609 smtpHost: emailHost.trimmingCharacters(in: .whitespacesAndNewlines),
610 port: port,
611 username: emailUsername.trimmingCharacters(in: .whitespacesAndNewlines),
612 senderAddress: senderAddress.trimmingCharacters(in: .whitespacesAndNewlines),
613 recipientAddresses: recipients,
614 securityMode: smtpSecurity,
615 credentialReference: existingReference
616 )
617 ),
618 filters: filters
619 )
620 try integrationService.upsert(
621 target: target,
622 emailPassword: emailPassword.nilIfBlank
623 )
624 case .s3:
625 guard FeatureAccessService.hasAccess(to: .bucketExport) else {
626 validationMessage = "Export to your own bucket is \(FeatureAccessService.upgradeMessage(for: .bucketExport))."
627 return
628 }
629
630 let existingReference: String? = {
631 guard case .s3(let configuration) = existingTarget?.configuration else { return nil }
632 return configuration.credentialReference
633 }()
634
635 let trimmedBucket = s3Bucket.trimmingCharacters(in: .whitespacesAndNewlines)
636 guard !trimmedBucket.isEmpty else {
637 validationMessage = "Bucket is required."
638 return
639 }
640 let trimmedAccessKeyID = s3AccessKeyID.trimmingCharacters(in: .whitespacesAndNewlines)
641 guard !trimmedAccessKeyID.isEmpty else {
642 validationMessage = "Access key ID is required."
643 return
644 }
645 if s3SecretAccessKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && existingReference == nil {
646 validationMessage = "Secret access key is required."
647 return
648 }
649
650 let target = IntegrationTarget(
651 id: targetID,
652 type: .s3,
653 name: trimmedName,
654 isEnabled: isEnabled,
655 configuration: .s3(
656 S3IntegrationConfiguration(
657 endpoint: s3Endpoint.trimmingCharacters(in: .whitespacesAndNewlines),
658 region: s3Region.trimmingCharacters(in: .whitespacesAndNewlines),
659 bucket: trimmedBucket,
660 keyPrefix: s3KeyPrefix.trimmingCharacters(in: .whitespacesAndNewlines),
661 usesPathStyle: s3UsesPathStyle,
662 accessKeyID: trimmedAccessKeyID,
663 credentialReference: existingReference,
664 triggers: s3Triggers,
665 extraFormats: s3ExtraFormats
666 )
667 ),
668 filters: filters
669 )
670 try integrationService.upsert(
671 target: target,
672 s3SecretAccessKey: s3SecretAccessKey.nilIfBlank
673 )
674 }
675
676 dismiss()
677 } catch {
678 validationMessage = error.localizedDescription
679 }
680 }
681
682 /// Bucket export is Pro+ (D1), so a tier without it does not get the
683 /// option. An existing target keeps its type listed, so a downgrade leaves
684 /// the editor readable rather than blank.
685 private var selectableTypes: [IntegrationType] {
686 IntegrationType.allCases.filter { integrationType in
687 if integrationType == existingTarget?.type { return true }
688 guard integrationType == .s3 else { return true }
689 return FeatureAccessService.hasAccess(to: .bucketExport)
690 }
691 }
692
693 private func existingWebhookDisplayHost() -> String {
694 guard case .webhook(let configuration) = existingTarget?.configuration else {
695 return ""
696 }
697 return configuration.endpointDisplayHost
698 }
699
700 private func existingSlackDestination() -> String {
701 guard case .slack(let configuration) = existingTarget?.configuration else {
702 return "Slack"
703 }
704 return configuration.destinationLabel
705 }
706}
707
708private extension String {
709}