DomainDig/DomainViewModel+Export.swift
566 lines · 23068 bytes
1import Foundation
2
3/// Export and data-portability surface of `DomainViewModel`: rendering the
4/// current report, batch results, tracked domains, timelines, and workflow runs
5/// into the shareable formats, plus the full-backup / portable-slice exporters
6/// and the import + app-settings persistence entry points.
7///
8/// These are thin adapters over `DomainReportExporter` and
9/// `DomainDataPortabilityService`. The report-projection helpers they call
10/// (`currentBatchReports`, `reports(for:)`, `timelineReports`, `workflowReports`)
11/// remain on the main type — they belong to the report layer shared with
12/// inspection, not to export.
13extension DomainViewModel {
14 func exportJSONData() -> Data? {
15 guard let currentReport else { return nil }
16 return try? DomainReportExporter.data(for: currentReport, format: .json)
17 }
18
19 func exportJSONString() -> String? {
20 guard let data = exportJSONData() else { return nil }
21 return String(data: data, encoding: .utf8)
22 }
23
24 func exportSingleReportData(format: DomainExportFormat) -> Data? {
25 guard let currentReport else { return nil }
26 return try? DomainReportExporter.data(for: currentReport, format: format)
27 }
28
29 func exportBatchReportData(format: DomainExportFormat) -> Data? {
30 try? DomainReportExporter.data(
31 for: currentBatchReports(),
32 format: format,
33 title: batchLookupSource == .watchlistRefresh ? "Tracked Domains Export" : "Batch Results Export"
34 )
35 }
36
37 func exportTrackedDomainsData(domains: [TrackedDomain], format: DomainExportFormat) -> Data? {
38 try? DomainReportExporter.data(
39 for: reports(for: domains),
40 format: format,
41 title: "Tracked Domains Export"
42 )
43 }
44
45 func exportTimelineText(domain: String, includeDiffSummary: Bool) -> String {
46 DomainReportExporter.timelineText(
47 for: timelineReports(for: domain),
48 domain: domain,
49 includeDiffSummary: includeDiffSummary
50 )
51 }
52
53 func exportTimelineJSONData(domain: String, includeDiffSummary: Bool) -> Data? {
54 try? DomainReportExporter.timelineData(
55 for: timelineReports(for: domain),
56 domain: domain,
57 includeDiffSummary: includeDiffSummary
58 )
59 }
60
61 func exportFullBackupData() -> Data? {
62 try? DomainDataPortabilityService.backupData(defaults: defaults, historyLocation: historyLocation)
63 }
64
65 func exportPortableTrackedDomainsJSONData() -> Data? {
66 try? DomainDataPortabilityService.trackedDomainsExportData(defaults: defaults)
67 }
68
69 func exportPortableTrackedDomainsCSV() -> String {
70 DomainDataPortabilityService.trackedDomainsCSV(defaults: defaults)
71 }
72
73 func exportPortableWorkflowsJSONData() -> Data? {
74 try? DomainDataPortabilityService.workflowsExportData(defaults: defaults)
75 }
76
77 func exportPortableWorkflowsCSV() -> String {
78 DomainDataPortabilityService.workflowsCSV(defaults: defaults)
79 }
80
81 func exportPortableHistoryJSONData() -> Data? {
82 try? DomainDataPortabilityService.historyExportData(defaults: defaults, historyLocation: historyLocation)
83 }
84
85 func prepareDataImport(
86 data: Data,
87 fileName: String,
88 mode: DataPortabilityImportMode
89 ) throws -> DataImportPreview {
90 try DomainDataPortabilityService.prepareImport(
91 data: data,
92 fileName: fileName,
93 mode: mode,
94 defaults: defaults,
95 historyLocation: historyLocation
96 )
97 }
98
99 func applyDataImport(_ preview: DataImportPreview, mode: DataPortabilityImportMode) throws -> DataImportResult {
100 let result = try DomainDataPortabilityService.applyImport(
101 preview,
102 mode: mode,
103 defaults: defaults,
104 historyLocation: historyLocation
105 )
106 refreshPersistedData()
107 portabilityStatusMessage = result.summary
108 CloudSyncService.shared.markAppSettingsChanged()
109 CloudSyncService.shared.markMonitoringSettingsChanged(localActivationConfirmed: monitoringSettings.isEnabled)
110 CloudSyncService.shared.scheduleSyncIfNeeded(trigger: .imported)
111 return result
112 }
113
114 func persistCurrentAppSettings(resolverURLString: String, appDensityRawValue: String) {
115 DomainDataPortabilityService.saveAppSettings(
116 AppSettingsSnapshot(
117 recentSearches: recentSearches,
118 resolverURLString: resolverURLString,
119 appDensityRawValue: appDensityRawValue
120 ),
121 defaults: defaults
122 )
123 CloudSyncService.shared.markAppSettingsChanged()
124 refreshDataLifecycleSummary()
125 }
126
127 func exportWorkflowText(summary: WorkflowRunSummary, changedOnly: Bool) -> String {
128 let reports = workflowReports(from: summary, changedOnly: changedOnly)
129 let base = DomainReportExporter.batchText(
130 for: reports,
131 title: "\(summary.workflowName) Workflow Export"
132 )
133 guard !summary.workflowInsights.isEmpty else { return base }
134 let insightLines = summary.workflowInsights.map {
135 "- \($0.description): \($0.domainsInvolved.joined(separator: ", "))"
136 }
137 return ([ "\(summary.workflowName) Workflow Insights", String(repeating: "-", count: 32) ] + insightLines + ["", base]).joined(separator: "\n")
138 }
139
140 func exportWorkflowCSV(summary: WorkflowRunSummary, changedOnly: Bool) -> String {
141 DomainReportExporter.csv(
142 for: workflowReports(from: summary, changedOnly: changedOnly),
143 workflowInsights: summary.workflowInsights
144 )
145 }
146
147 func exportWorkflowJSONData(summary: WorkflowRunSummary, changedOnly: Bool) -> Data? {
148 let payload = WorkflowExportPayload(
149 workflowName: summary.workflowName,
150 generatedAt: summary.generatedAt,
151 workflowInsights: summary.workflowInsights,
152 reports: workflowReports(from: summary, changedOnly: changedOnly)
153 )
154 let encoder = JSONEncoder()
155 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
156 encoder.dateEncodingStrategy = .iso8601
157 return try? encoder.encode(payload)
158 }
159
160 func exportWorkflowMarkdown(summary: WorkflowRunSummary, changedOnly: Bool) -> String {
161 let reports = workflowReports(from: summary, changedOnly: changedOnly)
162 let base = DomainReportExporter.batchMarkdown(for: reports, title: "\(summary.workflowName) Workflow Export")
163 guard !summary.workflowInsights.isEmpty else { return base }
164 let insightLines = summary.workflowInsights.map {
165 "- \($0.description): \($0.domainsInvolved.joined(separator: ", "))"
166 }
167 return (["## \(summary.workflowName) Workflow Insights"] + insightLines + ["", base]).joined(separator: "\n")
168 }
169
170 func exportWorkflowData(summary: WorkflowRunSummary, changedOnly: Bool, format: DomainExportFormat) -> Data? {
171 switch format {
172 case .text:
173 return Data(exportWorkflowText(summary: summary, changedOnly: changedOnly).utf8)
174 case .csv:
175 return Data(exportWorkflowCSV(summary: summary, changedOnly: changedOnly).utf8)
176 case .json:
177 return exportWorkflowJSONData(summary: summary, changedOnly: changedOnly)
178 case .markdown:
179 return Data(exportWorkflowMarkdown(summary: summary, changedOnly: changedOnly).utf8)
180 case .pdf:
181 return DomainReportExporter.pdfData(fromMarkdown: exportWorkflowMarkdown(summary: summary, changedOnly: changedOnly))
182 }
183 }
184}
185
186private struct WorkflowExportPayload: Codable {
187 let workflowName: String
188 let generatedAt: Date
189 let workflowInsights: [WorkflowInsight]
190 let reports: [DomainReport]
191}
192
193// MARK: - Export line builders
194
195// Moved out of DomainViewModel.swift (A13): these are static functions
196// over a snapshot or report, so they hold no view-model state and the
197// core file was carrying a quarter of its length in them.
198
199extension DomainViewModel {
200 static func formatBatchExportText(
201 title: String,
202 entries: [(snapshot: LookupSnapshot, trackedDomain: TrackedDomain?, changeSummary: DomainChangeSummary?, diffSections: [DomainDiffSection])]
203 ) -> String {
204 guard !entries.isEmpty else {
205 return "\(title)\nNo results available."
206 }
207
208 var lines = [title, String(repeating: "=", count: title.count), ""]
209 for (index, entry) in entries.enumerated() {
210 if index > 0 {
211 lines.append("")
212 lines.append(String(repeating: "=", count: 48))
213 lines.append("")
214 }
215
216 lines.append(
217 formatExportText(
218 from: entry.snapshot,
219 trackedDomain: entry.trackedDomain,
220 changeSummary: entry.changeSummary,
221 diffSections: entry.diffSections
222 )
223 )
224 }
225 return lines.joined(separator: "\n")
226 }
227
228 static func formatCSV(from snapshots: [LookupSnapshot]) -> String {
229 let headers = [
230 "domain",
231 "availability",
232 "primary_ip",
233 "redirect_target",
234 "tls_status",
235 "http_status_grade",
236 "email_security_summary",
237 "registrar",
238 "ownership_expires",
239 "ownership_status",
240 "ownership_nameservers",
241 "subdomain_count",
242 "subdomains",
243 "last_updated"
244 ]
245
246 let rows = snapshots.map { snapshot in
247 [
248 snapshot.domain,
249 availabilityLabel(snapshot.availabilityResult?.status),
250 primaryIPAddress(from: snapshot) ?? "",
251 finalRedirectTarget(from: snapshot) ?? "",
252 httpsSummary(from: snapshot),
253 httpStatusGradeSummary(from: snapshot),
254 emailSummary(from: snapshot),
255 snapshot.ownership?.registrar ?? "",
256 snapshot.ownership?.expirationDate.map(csvDateFormatter.string(from:)) ?? "",
257 snapshot.ownership?.status.joined(separator: " | ") ?? "",
258 snapshot.ownership?.nameservers.joined(separator: " | ") ?? "",
259 "\(snapshot.subdomains.count)",
260 snapshot.subdomains.map(\.hostname).joined(separator: " | "),
261 csvDateFormatter.string(from: snapshot.timestamp)
262 ]
263 }
264
265 return ([headers] + rows)
266 .map { row in row.map(csvEscaped).joined(separator: ",") }
267 .joined(separator: "\n")
268 }
269
270 static func formatExportText(
271 from snapshot: LookupSnapshot,
272 trackedDomain: TrackedDomain?,
273 changeSummary: DomainChangeSummary?,
274 diffSections: [DomainDiffSection]
275 ) -> String {
276 let exportDateFormatter = DateFormatter()
277 exportDateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
278
279 var lines: [String] = [
280 "DomainDig Export",
281 "Domain: \(snapshot.domain)",
282 "Date: \(exportDateFormatter.string(from: snapshot.timestamp))",
283 "Mode: \(snapshot.statusMessage ?? snapshot.resultSource.label)",
284 "Resolver: \(snapshot.resolverDisplayName)",
285 "Lookup Duration: \(durationLabel(snapshot.totalLookupDurationMs))",
286 "Tracked: \(trackedDomain == nil ? "No" : "Yes")"
287 ]
288
289 if let note = trackedDomain?.note?.nilIfEmpty {
290 lines.append("Tracking Note: \(note)")
291 }
292
293 func appendSection(_ title: String, _ body: [String]) {
294 lines.append("")
295 lines.append(title)
296 lines.append(String(repeating: "-", count: title.count))
297 lines += body
298 }
299
300 appendSection("Summary", exportSummaryLines(snapshot, changeSummary: changeSummary, exportDateFormatter: exportDateFormatter))
301 appendSection("Tracking", exportTrackingLines(trackedDomain, exportDateFormatter: exportDateFormatter))
302 appendSection("Diff Summary", exportDiffSummaryLines(diffSections))
303 appendSection("Domain", exportDomainLines(snapshot))
304 appendSection("Ownership", exportOwnershipLines(snapshot))
305 appendSection("Subdomains", exportSubdomainsLines(snapshot))
306 appendSection("DNS", exportDnsLines(snapshot))
307 appendSection("Web", exportWebLines(snapshot))
308 appendSection("Email", exportEmailLines(snapshot))
309 appendSection("Network", exportNetworkLines(snapshot))
310
311 return lines.joined(separator: "\n")
312 }
313
314 private static func exportSummaryLines(
315 _ snapshot: LookupSnapshot,
316 changeSummary: DomainChangeSummary?,
317 exportDateFormatter: DateFormatter
318 ) -> [String] {
319 var lines: [String] = []
320 for item in summaryFields(from: snapshot) {
321 lines.append(" \(item.label): \(item.value)")
322 }
323 if let changeSummary {
324 lines.append(" Change Summary: \(changeSummary.message)")
325 lines.append(" Severity: \(changeSummary.severity.title)")
326 lines.append(" Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))")
327 lines.append(" Compared At: \(exportDateFormatter.string(from: changeSummary.generatedAt))")
328 }
329 return lines
330 }
331
332 private static func exportTrackingLines(_ trackedDomain: TrackedDomain?, exportDateFormatter: DateFormatter) -> [String] {
333 var lines: [String] = []
334 if let trackedDomain {
335 lines.append(" Pinned: \(trackedDomain.isPinned ? "Yes" : "No")")
336 lines.append(" Last Refresh: \(exportDateFormatter.string(from: trackedDomain.updatedAt))")
337 lines.append(" Last Known Availability: \(availabilityLabel(trackedDomain.lastKnownAvailability))")
338 if let note = trackedDomain.note?.nilIfEmpty {
339 lines.append(" Note: \(note)")
340 }
341 } else {
342 lines.append(" This domain is not currently tracked.")
343 }
344 return lines
345 }
346
347 private static func exportDiffSummaryLines(_ diffSections: [DomainDiffSection]) -> [String] {
348 var lines: [String] = []
349 if diffSections.isEmpty {
350 lines.append(" No comparison available")
351 } else {
352 for section in diffSections where section.items.contains(where: { $0.changeType != .unchanged }) {
353 lines.append(" \(section.title)")
354 for item in section.items where item.changeType != .unchanged {
355 lines.append(" [\(item.changeType.rawValue.capitalized)] \(item.label): \(item.oldValue ?? "None") -> \(item.newValue ?? "None")")
356 }
357 }
358 }
359 return lines
360 }
361
362 private static func exportDomainLines(_ snapshot: LookupSnapshot) -> [String] {
363 var lines: [String] = []
364 for row in domainRows(from: snapshot) {
365 lines.append(" \(row.label): \(row.value)")
366 }
367 if snapshot.suggestions.isEmpty {
368 lines.append(" Suggestions: None")
369 } else {
370 lines.append(" Suggestions:")
371 for suggestion in snapshot.suggestions {
372 lines.append(" \(suggestion.domain): \(availabilityLabel(suggestion.status))")
373 }
374 }
375 return lines
376 }
377
378 private static func exportOwnershipLines(_ snapshot: LookupSnapshot) -> [String] {
379 var lines: [String] = []
380 for row in ownershipRows(from: snapshot) {
381 lines.append(" \(row.label): \(row.value)")
382 }
383 if let ownershipError = snapshot.ownershipError, snapshot.ownership == nil {
384 lines.append(" Source: \(ownershipError)")
385 }
386 return lines
387 }
388
389 private static func exportSubdomainsLines(_ snapshot: LookupSnapshot) -> [String] {
390 var lines: [String] = []
391 lines.append(" Count: \(snapshot.subdomains.count)")
392 if snapshot.subdomains.isEmpty {
393 lines.append(" \(snapshot.subdomainsError ?? "No passive subdomains found")")
394 } else {
395 for subdomain in subdomainRows(from: snapshot) {
396 let marker = subdomain.isInteresting ? " [interesting]" : ""
397 lines.append(" \(subdomain.hostname)\(marker)")
398 }
399 }
400 if !FeatureAccessService.hasAccess(to: .extendedSubdomains) {
401 lines.append(" Extended subdomain discovery (Pro)")
402 }
403 return lines
404 }
405
406 private static func exportDnsLines(_ snapshot: LookupSnapshot) -> [String] {
407 var lines: [String] = []
408 if let dnsError = snapshot.dnsError {
409 lines.append(" Error: \(dnsError)")
410 }
411 if let dnssecLabel = dnssecLabel(from: snapshot) {
412 lines.append(" \(dnssecLabel)")
413 }
414 for section in dnsRows(from: snapshot) {
415 lines += exportDNSSectionLines(section)
416 }
417 if let ptrRecord = snapshot.ptrRecord {
418 lines.append(" PTR: \(ptrRecord)")
419 } else if let ptrError = snapshot.ptrError {
420 lines.append(" PTR Error: \(ptrError)")
421 }
422 return lines
423 }
424
425 private static func exportDNSSectionLines(_ section: DNSRecordSectionViewData) -> [String] {
426 var lines = [" \(section.title)"]
427 if let message = section.message {
428 lines.append(" \(message.isError ? "Error" : "Info"): \(message.text)")
429 }
430 for row in section.rows {
431 lines.append(" \(row.value) (\(row.label))")
432 }
433 if let wildcardTitle = section.wildcardTitle {
434 lines.append(" \(wildcardTitle)")
435 for row in section.wildcardRows {
436 lines.append(" \(row.value) (\(row.label))")
437 }
438 }
439 return lines
440 }
441
442 private static func exportResponseLines(_ snapshot: LookupSnapshot) -> [String] {
443 if let httpHeadersError = snapshot.httpHeadersError {
444 return [" Headers Error: \(httpHeadersError)"]
445 }
446 var lines = webResponseRows(from: snapshot).map { " \($0.label): \($0.value)" }
447 if snapshot.httpHeaders.isEmpty {
448 lines.append(" Headers: No headers returned")
449 } else {
450 lines.append(" Headers:")
451 for header in snapshot.httpHeaders {
452 lines.append(" \(header.name): \(header.value)")
453 }
454 }
455 return lines
456 }
457
458 private static func exportWebLines(_ snapshot: LookupSnapshot) -> [String] {
459 var lines: [String] = []
460 if let sslError = snapshot.sslError {
461 lines.append(" TLS Error: \(sslError)")
462 } else {
463 for row in webCertificateRows(from: snapshot) {
464 lines.append(" \(row.label): \(row.value)")
465 }
466 }
467 lines += exportResponseLines(snapshot)
468
469 if let redirectChainError = snapshot.redirectChainError {
470 lines.append(" Redirect Error: \(redirectChainError)")
471 } else if snapshot.redirectChain.isEmpty {
472 lines.append(" Redirects: No redirect data available")
473 } else {
474 lines.append(" Redirects:")
475 for hop in redirectRows(from: snapshot) {
476 lines.append(" \(hop.stepLabel). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
477 }
478 }
479 return lines
480 }
481
482 private static func exportEmailLines(_ snapshot: LookupSnapshot) -> [String] {
483 var lines: [String] = []
484 if let emailSecurityError = snapshot.emailSecurityError {
485 lines.append(" Error: \(emailSecurityError)")
486 } else if emailRows(from: snapshot).isEmpty {
487 lines.append(" No email security records found")
488 } else {
489 for row in emailRows(from: snapshot) {
490 lines.append(" \(row.label): \(row.status)")
491 lines.append(" \(row.detail)")
492 if let auxiliaryDetail = row.auxiliaryDetail {
493 lines.append(" \(auxiliaryDetail)")
494 }
495 }
496 }
497 return lines
498 }
499
500 private static func exportPortLines(_ rows: [PortScanRowViewData]) -> [String] {
501 guard !rows.isEmpty else { return [" No results"] }
502 var lines: [String] = []
503 for row in rows {
504 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
505 if let banner = row.banner {
506 lines.append(" Banner: \(banner)")
507 }
508 }
509 return lines
510 }
511
512 private static func exportNetworkLines(_ snapshot: LookupSnapshot) -> [String] {
513 var lines: [String] = []
514 if let reachabilityError = snapshot.reachabilityError {
515 lines.append(" Reachability Error: \(reachabilityError)")
516 } else if reachabilityRows(from: snapshot).isEmpty {
517 lines.append(" Reachability: No results")
518 } else {
519 lines.append(" Reachability:")
520 for row in reachabilityRows(from: snapshot) {
521 lines.append(" \(row.portLabel): \(row.statusLabel) \(row.latencyLabel)")
522 }
523 }
524
525 if let ipGeolocationError = snapshot.ipGeolocationError, snapshot.ipGeolocation == nil {
526 lines.append(" Location Error: \(ipGeolocationError)")
527 } else if locationRows(from: snapshot).isEmpty {
528 lines.append(" Location: No data")
529 } else {
530 lines.append(" Location:")
531 for row in locationRows(from: snapshot) {
532 lines.append(" \(row.label): \(row.value)")
533 }
534 }
535
536 if let portScanError = snapshot.portScanError, snapshot.portScanResults.isEmpty {
537 lines.append(" Port Scan Error: \(portScanError)")
538 }
539
540 lines.append(" Standard Ports:")
541 lines += exportPortLines(portRows(from: snapshot, kind: .standard))
542 lines.append(" Custom Ports:")
543 lines += exportPortLines(portRows(from: snapshot, kind: .custom))
544 return lines
545 }
546
547 private static let csvDateFormatter: ISO8601DateFormatter = {
548 let formatter = ISO8601DateFormatter()
549 formatter.formatOptions = [.withInternetDateTime]
550 return formatter
551 }()
552
553 private static func csvEscaped(_ value: String) -> String {
554 let escaped = value.replacingOccurrences(of: "\"", with: "\"\"")
555 return "\"\(escaped)\""
556 }
557
558 private static func httpStatusGradeSummary(from snapshot: LookupSnapshot) -> String {
559 let parts = [snapshot.httpStatusCode.map(String.init), snapshot.httpSecurityGrade].compactMap { $0 }
560 if !parts.isEmpty {
561 return parts.joined(separator: " / ")
562 }
563 return snapshot.httpHeadersError ?? "Unavailable"
564 }
565}
566