Sources/OrgApp/AttachmentInbox.swift
42 lines · 1837 bytes
1import Foundation
2
3/// Files shared from other apps to attach, waiting for the app to ask which entry they go to:
4/// a folder for each share in the app group's container, which the share extension writes.
5public struct AttachmentInbox: Sendable {
6 public let folder: URL
7
8 /// The app group's inbox; nil when the app isn't entitled to the group.
9 public init?(group: String = CaptureInbox.group) {
10 guard let container = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group) else { return nil }
11 folder = container.appendingPathComponent("Attachments")
12 }
13
14 public init(folder: URL) {
15 self.folder = folder
16 }
17
18 /// `files` copied in as one share.
19 public func add(_ files: [URL]) throws {
20 let batch = folder.appendingPathComponent(String(format: "%020.6f", Date().timeIntervalSince1970) + "-" + UUID().uuidString)
21 try FileManager.default.createDirectory(at: batch, withIntermediateDirectories: true)
22 for file in files {
23 try FileManager.default.copyItem(at: file, to: batch.appendingPathComponent(file.lastPathComponent))
24 }
25 }
26
27 /// The waiting shares, oldest first.
28 public func batches() -> [URL] {
29 let names = ((try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []).filter { !$0.hasPrefix(".") }.sorted()
30 return names.map { folder.appendingPathComponent($0) }
31 }
32
33 /// A share's files, by name.
34 public static func files(in batch: URL) -> [URL] {
35 ((try? FileManager.default.contentsOfDirectory(atPath: batch.path)) ?? []).filter { !$0.hasPrefix(".") }.sorted().map { batch.appendingPathComponent($0) }
36 }
37
38 /// The share and whatever is left of it.
39 public func remove(_ batch: URL) {
40 try? FileManager.default.removeItem(at: batch)
41 }
42}