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
import ImageIO
import os
import PhotosUI
import UIKit
private let logger = Logger(subsystem: "social.grain.grain", category: "GalleryDraft")
enum GalleryDraftError: LocalizedError {
case photoUnavailable(index: Int)
var errorDescription: String? {
switch self {
case let .photoUnavailable(index):
"Photo \(index + 1) couldn't be read from your library. Remove it and try again."
}
}
}
extension GalleryDraft {
/// Turn what's on screen into a draft on disk.
///
/// This is where the expensive, entirely offline half of posting happens:
/// each photo is decoded, resized to upload size, and written into the
/// draft's directory, and every record key is assigned. Once this returns
/// the gallery can be published from the draft alone — the picker items,
/// the in-memory previews, and even this app process are no longer needed.
static func build(
items: [PhotoItem],
repo: String,
title: String,
description: String,
labels: [String],
location: Location?,
includeExif: Bool,
postToBluesky: Bool,
store: GalleryDraftStore = .shared,
onProgress: @MainActor @Sendable (Int, Int) -> Void = { _, _ in }
) async throws -> GalleryDraft {
let draftID = UUID()
do {
return try await assemble(
draftID: draftID,
items: items,
repo: repo,
title: title,
description: description,
labels: labels,
location: location,
includeExif: includeExif,
postToBluesky: postToBluesky,
store: store,
onProgress: onProgress
)
} catch {
// Don't leave the JPEGs we'd already written behind: without a
// draft.json beside them nothing would ever pick them up again.
store.delete(draftID)
throw error
}
}
private static func assemble(
draftID: UUID,
items: [PhotoItem],
repo: String,
title: String,
description: String,
labels: [String],
location: Location?,
includeExif: Bool,
postToBluesky: Bool,
store: GalleryDraftStore,
onProgress: @MainActor @Sendable (Int, Int) -> Void
) async throws -> GalleryDraft {
let total = items.count
var photos: [Photo] = []
for (index, item) in items.enumerated() {
let resized: Data
let size: CGSize
var exif: [String: AnyCodable]?
switch item.source {
case let .picker(pickerItem):
guard let data = try await pickerItem.loadTransferable(type: Data.self),
let original = UIImage(data: data)
else {
// Previously this photo was silently dropped and the
// gallery posted one short. Better to say so.
throw GalleryDraftError.photoUnavailable(index: index)
}
if includeExif {
exif = extractGalleryExif(from: data)
}
(resized, size) = ImageProcessing.resizeImage(original, maxDimension: 2000, maxBytes: 900_000)
case let .camera(image, metadata):
if includeExif {
exif = extractExifFromMetadata(metadata)
}
(resized, size) = ImageProcessing.resizeImage(image, maxDimension: 2000, maxBytes: 900_000)
}
let fileName = "\(item.id.uuidString).jpg"
try store.writeImage(resized, draftID: draftID, fileName: fileName)
logger.info("Prepared photo \(index + 1)/\(total): \(resized.count) bytes, \(Int(size.width))x\(Int(size.height))")
photos.append(Photo(
id: item.id,
fileName: fileName,
width: Int(size.width),
height: Int(size.height),
alt: item.alt,
exif: exif,
photoRkey: TID.next(),
exifRkey: TID.next(),
itemRkey: TID.next()
))
await onProgress(index + 1, total)
}
let draft = GalleryDraft(
id: draftID,
repo: repo,
title: title,
description: description,
labels: labels,
location: location,
includeExif: includeExif,
postToBluesky: postToBluesky,
createdAt: DateFormatting.nowISO(),
galleryRkey: TID.next(),
blueskyRkey: TID.next(),
photos: photos
)
store.save(draft)
return draft
}
}
// MARK: - EXIF record extraction
// These build the `social.grain.photo.exif` record. The display-oriented
// `ExifSummary` used by the editor is a separate path in `CreateGalleryView`.
private func flashDescription(for flash: Int) -> String {
switch flash {
case 0: "Off, Did not fire"
case 1: "On, Fired"
case 5: "On, Return not detected"
case 7: "On, Return detected"
case 16: "Off, Did not fire"
case 24: "Off, Auto"
case 25: "On, Auto"
default: "Unknown (\(flash))"
}
}
private func extractCameraInfo(
exifDict: [String: Any]?,
tiffDict: [String: Any]?,
exifAux: [String: Any]?,
into result: inout [String: AnyCodable]
) {
if let make = tiffDict?[kCGImagePropertyTIFFMake as String] as? String {
result["make"] = AnyCodable(make.trimmingCharacters(in: .whitespaces))
}
if let model = tiffDict?[kCGImagePropertyTIFFModel as String] as? String {
result["model"] = AnyCodable(model.trimmingCharacters(in: .whitespaces))
}
let lensMake = exifAux?["LensMake"] as? String
?? exifDict?["LensMake"] as? String
?? tiffDict?[kCGImagePropertyTIFFMake as String] as? String
if let lensMake {
result["lensMake"] = AnyCodable(lensMake.trimmingCharacters(in: .whitespaces))
}
let lensModel = exifAux?["LensModel"] as? String
?? exifDict?[kCGImagePropertyExifLensModel as String] as? String
if let lensModel {
result["lensModel"] = AnyCodable(lensModel.trimmingCharacters(in: .whitespaces))
}
}
private func extractExposureInfo(
exifDict: [String: Any]?,
scale: Int,
into result: inout [String: AnyCodable]
) {
if let exposureTime = exifDict?[kCGImagePropertyExifExposureTime as String] as? Double {
result["exposureTime"] = AnyCodable(Int(exposureTime * Double(scale)))
}
if let fNumber = exifDict?[kCGImagePropertyExifFNumber as String] as? Double {
result["fNumber"] = AnyCodable(Int(fNumber * Double(scale)))
}
if let isoRaw = exifDict?[kCGImagePropertyExifISOSpeedRatings as String] as? [Any],
let iso = (isoRaw.first as? NSNumber)?.intValue
{
result["iSO"] = AnyCodable(iso * scale)
}
if let focal35 = exifDict?[kCGImagePropertyExifFocalLenIn35mmFilm as String] as? Int {
result["focalLengthIn35mmFormat"] = AnyCodable(focal35 * scale)
} else if let focal35 = exifDict?[kCGImagePropertyExifFocalLenIn35mmFilm as String] as? Double {
result["focalLengthIn35mmFormat"] = AnyCodable(Int(focal35) * scale)
}
if let flash = exifDict?[kCGImagePropertyExifFlash as String] as? Int {
result["flash"] = AnyCodable(flashDescription(for: flash))
}
if let dateStr = exifDict?[kCGImagePropertyExifDateTimeOriginal as String] as? String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy:MM:dd HH:mm:ss"
if let date = formatter.date(from: dateStr) {
result["dateTimeOriginal"] = AnyCodable(ISO8601DateFormatter().string(from: date))
}
}
}
func extractExifFromMetadata(_ metadata: [String: Any]?) -> [String: AnyCodable]? {
guard let metadata else { return nil }
let exifDict = metadata[kCGImagePropertyExifDictionary as String] as? [String: Any]
let tiffDict = metadata[kCGImagePropertyTIFFDictionary as String] as? [String: Any]
let exifAux = metadata[kCGImagePropertyExifAuxDictionary as String] as? [String: Any]
var result: [String: AnyCodable] = [:]
extractCameraInfo(exifDict: exifDict, tiffDict: tiffDict, exifAux: exifAux, into: &result)
extractExposureInfo(exifDict: exifDict, scale: 1_000_000, into: &result)
return result.isEmpty ? nil : result
}
func extractGalleryExif(from data: Data) -> [String: AnyCodable]? {
guard let source = CGImageSourceCreateWithData(data as CFData, nil),
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [String: Any]
else {
logger.warning("No image properties found")
return nil
}
let exifDict = properties[kCGImagePropertyExifDictionary as String] as? [String: Any]
let tiffDict = properties[kCGImagePropertyTIFFDictionary as String] as? [String: Any]
let exifAux = properties[kCGImagePropertyExifAuxDictionary as String] as? [String: Any]
var result: [String: AnyCodable] = [:]
extractCameraInfo(exifDict: exifDict, tiffDict: tiffDict, exifAux: exifAux, into: &result)
extractExposureInfo(exifDict: exifDict, scale: 1_000_000, into: &result)
return result.isEmpty ? nil : result
}