Open History to see the last commit
1import Foundation
2
3public struct FeatureUploadedAttachmentReference: Sendable, Equatable, Codable {
4 public var environmentID: String
5 public var attachmentID: String
6
7 public init(environmentID: String, attachmentID: String) {
8 self.environmentID = environmentID
9 self.attachmentID = attachmentID
10 }
11}
12
13public struct FeatureOwnedAttachmentFile: Sendable, Equatable {
14 public let fileName: String
15 public let url: URL
16 public let byteCount: Int
17
18 public init(fileName: String, url: URL, byteCount: Int) {
19 self.fileName = fileName
20 self.url = url
21 self.byteCount = byteCount
22 }
23}
24
25public enum ManagedAttachmentFileError: LocalizedError, Equatable, Sendable {
26 case invalidSource
27 case invalidFileName
28 case empty
29 case tooLarge(actualBytes: Int, maximumBytes: Int)
30 case alreadyExists
31
32 public var errorDescription: String? {
33 switch self {
34 case .invalidSource:
35 "The selected attachment is not a local file."
36 case .invalidFileName:
37 "The attachment file name is invalid."
38 case .empty:
39 "The selected attachment is empty."
40 case let .tooLarge(actualBytes, maximumBytes):
41 "The attachment is \(actualBytes) bytes. T3 accepts up to \(maximumBytes) bytes."
42 case .alreadyExists:
43 "An owned attachment already exists for this ID."
44 }
45 }
46}
47
48/// Owns copies of provider files so drafts and outbox entries do not depend on
49/// temporary document-picker URLs. It never removes the provider-owned source.
50public struct ManagedAttachmentFileStore: Sendable {
51 public static let maximumBytes = 50 * 1024 * 1024
52 private static let chunkBytes = 256 * 1024
53
54 public let rootURL: URL
55
56 public init(rootURL: URL? = nil) {
57 if let rootURL {
58 self.rootURL = URL(fileURLWithPath: rootURL.standardizedFileURL.path, isDirectory: true)
59 } else {
60 let applicationSupport = FileManager.default.urls(
61 for: .applicationSupportDirectory,
62 in: .userDomainMask
63 ).first!
64 self.rootURL = applicationSupport
65 .appendingPathComponent("T3CodeSwift", isDirectory: true)
66 .appendingPathComponent("attachments", isDirectory: true)
67 .standardizedFileURL
68 }
69 }
70
71 public func writeOwnedFile(
72 data: Data,
73 attachmentID: UUID,
74 originalFileName: String,
75 maximumBytes: Int = Self.maximumBytes
76 ) throws -> FeatureOwnedAttachmentFile {
77 guard !data.isEmpty else { throw ManagedAttachmentFileError.empty }
78 let limit = min(Self.maximumBytes, max(0, maximumBytes))
79 guard data.count <= limit else {
80 throw ManagedAttachmentFileError.tooLarge(actualBytes: data.count, maximumBytes: limit)
81 }
82 let fileName = try Self.ownedFileName(attachmentID: attachmentID, originalFileName: originalFileName)
83 let destination = try resolvedFile(fileName: fileName, byteCount: data.count).url
84 try FileManager.default.createDirectory(at: rootURL, withIntermediateDirectories: true)
85 guard !FileManager.default.fileExists(atPath: destination.path) else {
86 throw ManagedAttachmentFileError.alreadyExists
87 }
88 try data.write(to: destination, options: .atomic)
89 return FeatureOwnedAttachmentFile(fileName: fileName, url: destination, byteCount: data.count)
90 }
91
92 public func copyOwnedFile(
93 from sourceURL: URL,
94 attachmentID: UUID,
95 originalFileName: String,
96 maximumBytes: Int = Self.maximumBytes
97 ) throws -> FeatureOwnedAttachmentFile {
98 guard sourceURL.isFileURL else { throw ManagedAttachmentFileError.invalidSource }
99 let effectiveMaximumBytes = min(Self.maximumBytes, max(0, maximumBytes))
100 let fileName = try Self.ownedFileName(
101 attachmentID: attachmentID,
102 originalFileName: originalFileName
103 )
104 let destination = try resolvedFile(fileName: fileName, byteCount: 0).url
105 try FileManager.default.createDirectory(at: rootURL, withIntermediateDirectories: true)
106 guard !FileManager.default.fileExists(atPath: destination.path) else {
107 throw ManagedAttachmentFileError.alreadyExists
108 }
109
110 let hasSecurityAccess = sourceURL.startAccessingSecurityScopedResource()
111 defer {
112 if hasSecurityAccess { sourceURL.stopAccessingSecurityScopedResource() }
113 }
114
115 let source = try FileHandle(forReadingFrom: sourceURL)
116 defer { try? source.close() }
117 guard FileManager.default.createFile(atPath: destination.path, contents: nil) else {
118 throw CocoaError(.fileWriteUnknown)
119 }
120 let output = try FileHandle(forWritingTo: destination)
121 var copiedBytes = 0
122 var completed = false
123 defer {
124 try? output.close()
125 if !completed { try? FileManager.default.removeItem(at: destination) }
126 }
127
128 while let chunk = try source.read(upToCount: Self.chunkBytes), !chunk.isEmpty {
129 copiedBytes += chunk.count
130 guard copiedBytes <= effectiveMaximumBytes else {
131 throw ManagedAttachmentFileError.tooLarge(
132 actualBytes: copiedBytes,
133 maximumBytes: effectiveMaximumBytes
134 )
135 }
136 try output.write(contentsOf: chunk)
137 }
138 guard copiedBytes > 0 else { throw ManagedAttachmentFileError.empty }
139 completed = true
140 return FeatureOwnedAttachmentFile(
141 fileName: fileName,
142 url: destination,
143 byteCount: copiedBytes
144 )
145 }
146
147 public func resolvedFile(fileName: String, byteCount: Int) throws
148 -> FeatureOwnedAttachmentFile
149 {
150 guard Self.isValidOwnedFileName(fileName) else {
151 throw ManagedAttachmentFileError.invalidFileName
152 }
153 let url = rootURL.appendingPathComponent(fileName, isDirectory: false).standardizedFileURL
154 guard url.deletingLastPathComponent() == rootURL else {
155 throw ManagedAttachmentFileError.invalidFileName
156 }
157 return FeatureOwnedAttachmentFile(fileName: fileName, url: url, byteCount: byteCount)
158 }
159
160 /// Removes one known owned file. Callers must coordinate ownership before
161 /// they use this helper because drafts and outbox entries can share a file.
162 public func removeOwnedFile(fileName: String) throws {
163 let file = try resolvedFile(fileName: fileName, byteCount: 0)
164 guard FileManager.default.fileExists(atPath: file.url.path) else { return }
165 try FileManager.default.removeItem(at: file.url)
166 }
167
168 private static func ownedFileName(
169 attachmentID: UUID,
170 originalFileName: String
171 ) throws -> String {
172 let pathExtension = URL(fileURLWithPath: originalFileName).pathExtension.lowercased()
173 let safeExtension = pathExtension.filter {
174 $0.isASCII && ($0.isLetter || $0.isNumber)
175 }
176 guard safeExtension.count <= 16 else { throw ManagedAttachmentFileError.invalidFileName }
177 return safeExtension.isEmpty
178 ? attachmentID.uuidString
179 : "\(attachmentID.uuidString).\(safeExtension)"
180 }
181
182 private static func isValidOwnedFileName(_ fileName: String) -> Bool {
183 guard fileName == URL(fileURLWithPath: fileName).lastPathComponent else { return false }
184 let url = URL(fileURLWithPath: fileName)
185 guard UUID(uuidString: url.deletingPathExtension().lastPathComponent) != nil else {
186 return false
187 }
188 let pathExtension = url.pathExtension
189 return pathExtension.count <= 16
190 && pathExtension.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber) }
191 }
192}