Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / R2Settings.swift

1import AppKit
2import SwiftUI
3import UniformTypeIdentifiers
4
5struct R2Settings: View {
6 let workspace: Workspace
7 @State private var account = ""
8 @State private var bucket = ""
9 @State private var jurisdiction = "default"
10 @State private var key = ""
11 @State private var secret = ""
12 @State private var current: R2Configuration?
13 @State private var busy = false
14
15 private var media: [WorkspaceRecord] {
16 guard let current else { return [] }
17 return Array(workspace.records.filter {
18 $0.kind == "r2-object" && $0["accountId"] == current.accountId && $0["bucket"] == current.bucket
19 && ($0["jurisdiction"].isEmpty ? "default" : $0["jurisdiction"]) == current.jurisdiction
20 }.prefix(10))
21 }
22
23 var body: some View {
24 GroupBox("Instagram media hosting") {
25 VStack(alignment: .leading, spacing: 10) {
26 Text("Use a private Cloudflare R2 bucket to publish attached Instagram images.")
27 SetupHelpLink("Instagram media hosting help", topic: "media-hosting")
28 TextField("Cloudflare account ID", text: $account).studioInput()
29 TextField("R2 bucket", text: $bucket).studioInput()
30 let regions = ["default": "Default", "eu": "European Union", "us": "United States", "fedramp": "FedRAMP"]
31 StudioLabeledChoice(title: "Jurisdiction", selection: $jurisdiction,
32 options: ["default", "eu", "us", "fedramp"], label: { regions[$0] ?? $0 })
33 SecureField("S3 Access Key ID", text: $key).studioInput()
34 SecureField("S3 Secret Access Key", text: $secret).studioInput()
35 HStack {
36 Button("Save R2 connection", action: save)
37 if current != nil {
38 Button("Test connection") { Task { await test() } }
39 Button("Disconnect") {
40 workspace.perform { try R2Profile.remove(); current = nil }
41 }
42 }
43 Spacer()
44 StudioExternalLink("Cloudflare R2", destination: URL(string: "https://dash.cloudflare.com/?to=/:account/r2/overview")!)
45 }
46 if current != nil {
47 Button("Upload image or video…", systemImage: "square.and.arrow.up", action: upload)
48 ForEach(media) { item in
49 HStack {
50 Text(item["name"]).lineLimit(1)
51 Spacer()
52 Button("Copy temporary link") {
53 workspace.perform {
54 copy(try client().link(item["key"]).absoluteString)
55 workspace.notice = "Two-hour media link copied"
56 }
57 }
58 }
59 }
60 }
61 if busy { ProgressView().controlSize(.small) }
62 }
63 .disabled(busy)
64 .frame(maxWidth: .infinity, alignment: .leading)
65 }
66 .onAppear {
67 workspace.perform {
68 let saved = try R2Profile.saved()?.configuration
69 current = saved
70 if let saved { account = saved.accountId; bucket = saved.bucket; jurisdiction = saved.jurisdiction }
71 }
72 }
73 }
74
75 private func save() {
76 workspace.perform {
77 let config = R2Configuration(accountId: account.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(),
78 bucket: bucket.trimmingCharacters(in: .whitespacesAndNewlines), jurisdiction: jurisdiction)
79 let existing = try R2Profile.saved()
80 let profile = R2Profile(
81 configuration: config,
82 accessKeyId: key.isEmpty && existing?.configuration == config ? existing?.accessKeyId ?? "" : key.trimmingCharacters(in: .whitespacesAndNewlines),
83 secretAccessKey: secret.isEmpty && existing?.configuration == config ? existing?.secretAccessKey ?? "" : secret.trimmingCharacters(in: .whitespacesAndNewlines)
84 )
85 try profile.save()
86 current = config
87 key = ""
88 secret = ""
89 workspace.notice = "R2 connection saved"
90 }
91 }
92
93 private func client() throws -> R2Client {
94 guard let profile = try R2Profile.saved() else { throw WorkspaceError("Save the R2 connection first.") }
95 return R2Client(profile: profile)
96 }
97
98 private func test() async {
99 guard !busy else { return }
100 busy = true
101 defer { busy = false }
102 do { try await client().test(); workspace.notice = "R2 read, write, and cleanup worked" }
103 catch { workspace.error = error.localizedDescription }
104 }
105
106 private func upload() {
107 let panel = NSOpenPanel()
108 panel.allowedContentTypes = [.png, .jpeg, .webP, .mpeg4Movie, .quickTimeMovie] + [UTType(filenameExtension: "webm")].compactMap { $0 }
109 guard panel.runModal() == .OK, let file = panel.url else { return }
110 Task {
111 busy = true
112 defer { busy = false }
113 do {
114 let client = try client()
115 let media = try await client.upload(file)
116 try workspace.saveR2Media(media, config: client.profile.configuration)
117 workspace.notice = "Media uploaded to R2"
118 } catch { workspace.error = error.localizedDescription }
119 }
120 }
121}