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
import CryptoKit
import Foundation
actor DraftLocalMediaStore {
struct Entry: Codable {
let id: UUID
let images: [ImageFile]
let video: VideoFile?
let replyTo: String?
let publishResultUnknown: Bool
var references: [String] {
images.map { "oldfella-drafts/\(id.uuidString)/image-\($0.id.uuidString)" }
+ (video.map { ["oldfella-drafts/\(id.uuidString)/video-\($0.id.uuidString)"] } ?? [])
}
}
struct ImageFile: Codable {
let id: UUID
let mimeType: String
}
struct VideoFile: Codable {
let id: UUID
let mimeType: String
}
private struct Binding: Codable {
let remoteID: String
let entryID: UUID
let fingerprint: String
}
private let directory: URL?
private let fileManager = FileManager.default
init(directory: URL? = nil) {
self.directory = directory ?? FileManager.default.containerURL(
forSecurityApplicationGroupIdentifier: AppGroup.identifier)?
.appendingPathComponent("DraftMedia", isDirectory: true)
}
func prepare(_ draft: ComposerDraft, accountID: String) throws -> Entry {
let account = try accountDirectory(accountID)
try fileManager.createDirectory(at: account, withIntermediateDirectories: true)
let id = UUID()
let entry = Entry(
id: id, images: draft.attachments.map { ImageFile(id: $0.id, mimeType: $0.mimeType) },
video: draft.video.map { VideoFile(id: $0.id, mimeType: $0.mimeType) }, replyTo: draft.replyTo,
publishResultUnknown: draft.publishResultUnknown)
let staging = account.appendingPathComponent(".\(id.uuidString)", isDirectory: true)
try fileManager.createDirectory(at: staging, withIntermediateDirectories: false)
defer { try? fileManager.removeItem(at: staging) }
for image in draft.attachments {
try image.data.write(to: staging.appendingPathComponent("image-\(image.id.uuidString)"), options: .atomic)
}
if let video = draft.video {
let destination = staging.appendingPathComponent("video-\(video.id.uuidString)")
switch video.source {
case .data(let data): try data.write(to: destination, options: .atomic)
case .file(let source): try fileManager.copyItem(at: source, to: destination)
}
}
try JSONEncoder().encode(entry).write(to: staging.appendingPathComponent("entry.json"), options: .atomic)
try fileManager.moveItem(at: staging, to: account.appendingPathComponent(id.uuidString, isDirectory: true))
return entry
}
func bind(_ entry: Entry, remoteID: String, fingerprint: String, accountID: String) throws {
let destination = try bindingURL(remoteID, accountID: accountID)
let previous = try? JSONDecoder().decode(Binding.self, from: Data(contentsOf: destination))
try fileManager.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
let binding = Binding(remoteID: remoteID, entryID: entry.id, fingerprint: fingerprint)
try JSONEncoder().encode(binding).write(to: destination, options: .atomic)
if let previous, previous.entryID != entry.id {
let directory = try accountDirectory(accountID).appendingPathComponent(previous.entryID.uuidString)
try? fileManager.removeItem(at: directory)
}
}
func entry(remoteID: String, fingerprint: String, accountID: String) throws -> Entry? {
let bindingURL = try bindingURL(remoteID, accountID: accountID)
guard fileManager.fileExists(atPath: bindingURL.path) else { return nil }
let binding = try JSONDecoder().decode(Binding.self, from: Data(contentsOf: bindingURL))
guard binding.remoteID == remoteID, binding.fingerprint == fingerprint else { return nil }
let directory = try accountDirectory(accountID).appendingPathComponent(binding.entryID.uuidString)
let entry = try JSONDecoder().decode(
Entry.self, from: Data(contentsOf: directory.appendingPathComponent("entry.json")))
guard entry.id == binding.entryID, entry.images.count <= 4,
entry.video == nil || entry.images.isEmpty,
Set(entry.images.map(\.id)).count == entry.images.count,
entry.images.allSatisfy({ $0.mimeType.hasPrefix("image/") }),
entry.video.map({ $0.mimeType.hasPrefix("video/") }) ?? true
else { throw SavedPostDraftError.unavailable("The media for this draft could not be read.") }
for reference in entry.references {
let filename = URL(fileURLWithPath: reference).lastPathComponent
guard fileManager.fileExists(atPath: directory.appendingPathComponent(filename).path) else {
throw SavedPostDraftError.unavailable("The media for this draft is no longer on this device.")
}
}
return entry
}
func images(_ entry: Entry, altText: [String], accountID: String) throws -> [ImageAttachment] {
guard entry.images.count == altText.count else { throw ServiceError.invalidResponse }
let directory = try accountDirectory(accountID).appendingPathComponent(entry.id.uuidString)
return try zip(entry.images, altText).map { image, alt in
ImageAttachment(
id: image.id,
data: try Data(
contentsOf: directory.appendingPathComponent("image-\(image.id.uuidString)"),
options: .mappedIfSafe),
altText: alt, mimeType: image.mimeType)
}
}
func video(_ entry: Entry, accountID: String) throws -> VideoAttachment? {
guard let video = entry.video else { return nil }
let directory = try accountDirectory(accountID).appendingPathComponent(entry.id.uuidString)
return VideoAttachment(
id: video.id,
data: try Data(
contentsOf: directory.appendingPathComponent("video-\(video.id.uuidString)"), options: .mappedIfSafe),
mimeType: video.mimeType)
}
func removeBinding(remoteID: String, accountID: String) throws {
let url = try bindingURL(remoteID, accountID: accountID)
guard fileManager.fileExists(atPath: url.path) else { return }
let binding = try JSONDecoder().decode(Binding.self, from: Data(contentsOf: url))
guard binding.remoteID == remoteID else { throw ServiceError.invalidResponse }
try fileManager.removeItem(at: url)
let directory = try accountDirectory(accountID).appendingPathComponent(binding.entryID.uuidString)
try? fileManager.removeItem(at: directory)
}
func removePrepared(_ entry: Entry, accountID: String) throws {
let directory = try accountDirectory(accountID).appendingPathComponent(entry.id.uuidString)
if fileManager.fileExists(atPath: directory.path) { try fileManager.removeItem(at: directory) }
}
private func accountDirectory(_ accountID: String) throws -> URL {
guard let directory, !accountID.isEmpty else {
throw SavedPostDraftError.unavailable("Old Fella could not access the media for saved drafts. Try again.")
}
return directory.appendingPathComponent(Self.hash(Data(accountID.utf8)), isDirectory: true)
}
private func bindingURL(_ remoteID: String, accountID: String) throws -> URL {
try accountDirectory(accountID).appendingPathComponent("bindings", isDirectory: true)
.appendingPathComponent(Self.hash(Data(remoteID.utf8)) + ".json")
}
static func hash(_ data: Data) -> String {
SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
}
}