proofmode 0.9.0

Capture, share, and preserve verifiable photos and videos
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
import SwiftUI
import PhotosUI

struct VerifyView: View {
    @EnvironmentObject var proofViewModel: ProofViewModel
    @EnvironmentObject var permissionService: PermissionService
    @StateObject private var proofModeService = ProofModeService()
    
    @Binding var selectedProof: Proof?
    
    @State private var showingImagePicker = false
    @State private var verificationResult: String?
    @State private var showingVerificationResult = false
    
    var body: some View {
        VStack(spacing: 20) {
            // Verify Files Section
            VStack(alignment: .leading, spacing: 16) {
                HStack {
                    Image(systemName: "doc.text.magnifyingglass")
                        .font(.title2)
                        .foregroundColor(.blue)
                    
                    VStack(alignment: .leading) {
                        Text("Verify Files")
                            .font(.headline)
                        Text("Check photos for proof data")
                            .font(.caption)
                            .foregroundColor(.secondary)
                    }
                    
                    Spacer()
                }
                
                Button(action: {
                    checkPhotoLibraryPermissionAndVerify()
                }) {
                    HStack {
                        Image(systemName: "photo.on.rectangle")
                            .font(.title2)
                        Text("Choose Photo to Verify")
                            .font(.headline)
                    }
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(Color.orange)
                    .foregroundColor(.white)
                    .cornerRadius(12)
                }
            }
            .padding()
            .background(Color.gray.opacity(0.05))
            .cornerRadius(12)
            
            // Progress View for File Verification
            if proofModeService.isVerifying {
                VStack(spacing: 12) {
                    ProgressView(value: proofModeService.progress)
                        .progressViewStyle(LinearProgressViewStyle())
                    
                    HStack {
                        ProgressView()
                            .scaleEffect(0.8)
                        Text(proofModeService.status.isEmpty ? "Verifying file..." : proofModeService.status)
                            .font(.caption)
                            .foregroundColor(.secondary)
                    }
                }
                .padding()
                .background(Color.gray.opacity(0.1))
                .cornerRadius(12)
            }
            
            Divider()
            
            // Generated Proofs Section
            VStack(alignment: .leading, spacing: 16) {
                HStack {
                    Image(systemName: "shield.checkerboard")
                        .font(.title2)
                        .foregroundColor(.green)
                    
                    VStack(alignment: .leading) {
                        Text("Generated Proofs")
                            .font(.headline)
                        Text("Verify proofs you've created")
                            .font(.caption)
                            .foregroundColor(.secondary)
                    }
                    
                    Spacer()
                }
                
                // Show existing proofs
                if proofViewModel.proofs.isEmpty {
                    VStack(spacing: 12) {
                        Image(systemName: "shield.slash")
                            .font(.system(size: 40))
                            .foregroundColor(.gray)
                        Text("No Generated Proofs")
                            .font(.subheadline)
                            .fontWeight(.medium)
                        Text("Generate proofs first to verify them here")
                            .font(.caption)
                            .foregroundColor(.secondary)
                            .multilineTextAlignment(.center)
                    }
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(Color.gray.opacity(0.05))
                    .cornerRadius(8)
                } else {
                    ProofListView(selectedProof: $selectedProof)
                        .frame(maxHeight: 300)
                }
            }
            .padding()
            .background(Color.gray.opacity(0.05))
            .cornerRadius(12)
            
            Spacer()
        }
        .padding()
        .sheet(isPresented: $showingImagePicker) {
            ImagePicker(sourceType: .photoLibrary) { image in
                verifySelectedImage(image)
            }
        }
        .sheet(isPresented: $showingVerificationResult) {
            NavigationStack {
                FileVerificationResultView(result: verificationResult ?? "No result")
                    .navigationTitle("Verification Result")
                    .navigationBarTitleDisplayMode(.inline)
                    .toolbar {
                        ToolbarItem(placement: .navigationBarTrailing) {
                            Button("Done") {
                                showingVerificationResult = false
                            }
                        }
                    }
            }
        }
    }
    
    private func checkPhotoLibraryPermissionAndVerify() {
        permissionService.requestPhotoLibraryPermission { granted in
            if granted {
                showingImagePicker = true
            }
        }
    }
    
    private func verifySelectedImage(_ image: UIImage) {
        // Create a temporary proof-like object for verification
        guard let imageData = image.jpegData(compressionQuality: 1.0) else {
            verificationResult = "Failed to process selected image"
            showingVerificationResult = true
            return
        }
        
        let tempProof = Proof(
            fileName: "selected_image.jpg",
            hash: proofModeService.calculateHash(for: imageData),
            fileSize: Int64(imageData.count),
            imageData: imageData
        )
        
        proofModeService.verifyProof(tempProof) { result in
            switch result {
            case .success(let output):
                verificationResult = output
            case .failure(let error):
                verificationResult = "Verification failed: \(error.localizedDescription)"
            }
            showingVerificationResult = true
        }
    }
}

struct FileVerificationResultView: View {
    let result: String
    
    private var parsedResult: VerificationResult? {
        guard let data = result.data(using: .utf8) else { return nil }
        
        // Try to parse as JSON
        if let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) {
            // Check if it's an empty array
            if let array = jsonObject as? [[String: Any]], array.isEmpty {
                return VerificationResult(
                    isEmpty: true,
                    summary: "No verification data found",
                    details: []
                )
            }
            
            // Parse the actual verification data
            if let dict = jsonObject as? [String: Any] {
                return parseVerificationDict(dict)
            } else if let array = jsonObject as? [[String: Any]], let first = array.first {
                return parseVerificationDict(first)
            }
        }
        
        // If not JSON, return the raw text
        return VerificationResult(
            isEmpty: false,
            summary: "Verification Complete",
            details: [("Raw Result", result)]
        )
    }
    
    private func parseVerificationDict(_ dict: [String: Any]) -> VerificationResult {
        var details: [(String, String)] = []
        var summary = "Verification Complete"
        
        // Check for files
        if let files = dict["files"] as? [[String: Any]] {
            if files.isEmpty {
                summary = "No proof files found"
            } else {
                summary = "Found \(files.count) file(s) with proof data"
                for file in files {
                    if let name = file["name"] as? String {
                        var fileStatus = "✓ Verified"
                        if let integrity = file["integrity"] as? [String: Any],
                           let verified = integrity["verified"] as? Bool {
                            fileStatus = verified ? "✓ Verified" : "✗ Not Verified"
                        }
                        details.append((name, fileStatus))
                    }
                }
            }
        }
        
        // Check for integrity results
        if let integrity = dict["integrity"] as? [String: Any] {
            if let c2pa = integrity["c2pa"] as? [String: Any],
               let verified = c2pa["verified"] as? Bool {
                details.append(("C2PA", verified ? "✓ Verified" : "✗ Not Found"))
            }
            if let pgp = integrity["pgp"] as? [String: Any],
               let verified = pgp["verified"] as? Bool {
                details.append(("PGP Signature", verified ? "✓ Verified" : "✗ Not Found"))
            }
            if let ots = integrity["ots"] as? [String: Any],
               let verified = ots["verified"] as? Bool {
                details.append(("OpenTimestamps", verified ? "✓ Verified" : "✗ Not Found"))
            }
        }
        
        // Check for errors
        if let errors = dict["errors"] as? [[String: Any]], !errors.isEmpty {
            summary = "Verification completed with \(errors.count) error(s)"
            for error in errors {
                if let name = error["name"] as? String,
                   let errorMsg = error["error"] as? String {
                    details.append((name, "Error: \(errorMsg)"))
                }
            }
        }
        
        return VerificationResult(
            isEmpty: details.isEmpty,
            summary: summary,
            details: details
        )
    }
    
    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 16) {
                titleView
                
                if let parsed = parsedResult {
                    parsedResultView(parsed)
                } else {
                    rawResultView
                }
            }
        }
    }
    
    // MARK: - Sub-views
    
    private var titleView: some View {
        Text("Verification Results")
            .font(.headline)
            .padding(.horizontal)
    }
    
    @ViewBuilder
    private func parsedResultView(_ parsed: VerificationResult) -> some View {
        VStack(alignment: .leading, spacing: 16) {
            summaryView(parsed)
            
            if !parsed.details.isEmpty {
                detailsView(parsed.details)
            }
            
            if parsed.isEmpty {
                helpTextView
            }
            
            rawDataDisclosureView
            copyButtonView
        }
        .padding()
    }
    
    private func summaryView(_ parsed: VerificationResult) -> some View {
        HStack {
            Image(systemName: parsed.isEmpty ? "exclamationmark.circle" : "checkmark.circle")
                .foregroundColor(parsed.isEmpty ? .orange : .green)
            Text(parsed.summary)
                .font(.subheadline)
                .fontWeight(.medium)
        }
        .padding()
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(Color.gray.opacity(0.05))
        .cornerRadius(8)
    }
    
    private func detailsView(_ details: [(String, String)]) -> some View {
        VStack(alignment: .leading, spacing: 8) {
            Text("Details")
                .font(.caption)
                .fontWeight(.semibold)
                .foregroundColor(.secondary)
            
            ForEach(Array(details.enumerated()), id: \.offset) { index, item in
                detailRow(item: item, isLast: index == details.count - 1)
            }
        }
        .padding()
        .background(Color.gray.opacity(0.05))
        .cornerRadius(8)
    }
    
    private func detailRow(item: (String, String), isLast: Bool) -> some View {
        VStack(spacing: 0) {
            HStack {
                Text(item.0)
                    .font(.caption)
                    .foregroundColor(.primary)
                Spacer()
                Text(item.1)
                    .font(.caption)
                    .foregroundColor(detailColor(for: item.1))
            }
            .padding(.vertical, 4)
            
            if !isLast {
                Divider()
            }
        }
    }
    
    private func detailColor(for text: String) -> Color {
        if text.contains("✓") {
            return .green
        } else if text.contains("✗") {
            return .red
        } else {
            return .secondary
        }
    }
    
    private var helpTextView: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text("How to add ProofMode data:")
                .font(.caption)
                .fontWeight(.semibold)
            
            Text("1. Go to the Generate tab")
            Text("2. Select a photo from your library")
            Text("3. Generate proof data for it")
            Text("4. The proof files will be saved with the image")
        }
        .font(.caption)
        .foregroundColor(.secondary)
        .padding()
        .background(Color.blue.opacity(0.05))
        .cornerRadius(8)
    }
    
    private var rawDataDisclosureView: some View {
        DisclosureGroup("View Raw Data") {
            Text(result)
                .font(.system(.caption2, design: .monospaced))
                .textSelection(.enabled)
                .frame(maxWidth: .infinity, alignment: .leading)
                .padding()
                .background(Color.gray.opacity(0.05))
                .cornerRadius(8)
        }
        .font(.caption)
        .foregroundColor(.secondary)
        .padding(.top, 8)
    }
    
    private var copyButtonView: some View {
        HStack {
            Button("Copy Raw Data") {
                UIPasteboard.general.string = result
            }
            .font(.caption)
            .foregroundColor(.blue)
            
            Spacer()
        }
    }
    
    private var rawResultView: some View {
        VStack(alignment: .leading, spacing: 12) {
            Text(result)
                .font(.system(.caption, design: .monospaced))
                .textSelection(.enabled)
                .frame(maxWidth: .infinity, alignment: .leading)
                .padding()
                .background(Color.gray.opacity(0.05))
                .cornerRadius(8)
                .overlay(
                    RoundedRectangle(cornerRadius: 8)
                        .stroke(Color.gray.opacity(0.3), lineWidth: 1)
                )
            
            HStack {
                Button("Copy Results") {
                    UIPasteboard.general.string = result
                }
                .font(.caption)
                .foregroundColor(.blue)
                
                Spacer()
                
                Text("Tap text to select")
                    .font(.caption2)
                    .foregroundColor(.secondary)
            }
        }
        .padding()
    }
}

// Helper struct for parsed verification results
private struct VerificationResult {
    let isEmpty: Bool
    let summary: String
    let details: [(String, String)]
}

#Preview {
    VerifyView(selectedProof: .constant(nil))
        .environmentObject(ProofViewModel())
        .environmentObject(PermissionService())
}