Sources/OrgstarMobile/SpotlightIndexer.swift

a866e469a3568bf7a2829a8dd2a56317ced4736e
orgstar/Sources/OrgstarMobile/SpotlightIndexer.swift history · blame · raw

95 lines · 4330 bytes

 1#if os(iOS)
 2import CoreSpotlight
 3import Foundation
 4import OrgApp
 5import OrgCore
 6import UniformTypeIdentifiers
 7
 8/// The workspace's org files in Spotlight with what the Mac's importer gives it: the text,
 9/// title, author, description, tags and headings. A file is indexed again when it changes.
10@MainActor
11final class SpotlightIndexer {
12    private struct State: Codable {
13        /// Also kept as the index's client state; the system deleting the index (as it does
14        /// when the app is installed again) takes it away, and every file is indexed again.
15        var generation = UUID()
16        /// Modification dates of the files as indexed.
17        var stamps: [String: Date] = [:]
18    }
19
20    private let index = CSSearchableIndex(name: "files")
21    private let stateFile = WorkspaceModel.defaultDirectory.appendingPathComponent("spotlight.json")
22    private var state: State
23    /// Files to index once the running update finishes; a batch can't start while one is open.
24    private var waiting: [FileEntry]?
25    private var running = false
26
27    init() {
28        state = (try? JSONDecoder().decode(State.self, from: Data(contentsOf: stateFile))) ?? State()
29    }
30
31    func update(_ files: [FileEntry]) async {
32        let interval = Perf.begin("spotlight.update")
33        defer { interval.end("\(files.count) files") }
34        guard !running else { return waiting = files }
35        running = true
36        defer { running = false }
37        var next: [FileEntry]? = files
38        while let files = next {
39            await index(files)
40            next = waiting
41            waiting = nil
42        }
43    }
44
45    /// Opens a batch with the changes; `endBatch` commits them. Not async: in a batch the
46    /// calls' completion handlers wait for the batch to end.
47    private func submit(_ items: [CSSearchableItem], removing gone: [String]) {
48        index.beginBatch()
49        if !items.isEmpty { index.indexSearchableItems(items, completionHandler: nil) }
50        if !gone.isEmpty { index.deleteSearchableItems(withIdentifiers: gone, completionHandler: nil) }
51    }
52
53    private func index(_ files: [FileEntry]) async {
54        let generation = Data(state.generation.uuidString.utf8)
55        let stamps = (try? await index.fetchLastClientState()) == generation ? state.stamps : [:]
56        // Reading and summarizing files stays off the main thread.
57        let (current, changed) = await Task.detached {
58            var current: [String: Date] = [:]
59            var changed: [(file: FileEntry, text: String, summary: FileSummary)] = []
60            for file in files where file.kind == .org {
61                guard let date = (try? FileManager.default.attributesOfItem(atPath: file.path))?[.modificationDate] as? Date else { continue }
62                if stamps[file.path] == date {
63                    current[file.path] = date
64                } else if let text = try? String(contentsOfFile: file.path, encoding: .utf8) {
65                    changed.append((file, text, FileSummary(text)))
66                    current[file.path] = date
67                }
68            }
69            return (current, changed)
70        }.value
71        let items = changed.map { Self.item($0.file, text: $0.text, summary: $0.summary) }
72        let gone = stamps.keys.filter { current[$0] == nil }
73        guard !items.isEmpty || !gone.isEmpty else { return }
74        submit(items, removing: gone)
75        do {
76            try await index.endBatch(withClientState: generation)
77        } catch {
78            return
79        }
80        state.stamps = current
81        try? JSONEncoder().encode(state).write(to: stateFile, options: .atomic)
82    }
83
84    private static func item(_ file: FileEntry, text: String, summary: FileSummary) -> CSSearchableItem {
85        let attributes = CSSearchableItemAttributeSet(contentType: .text)
86        attributes.title = summary.title ?? (file.name as NSString).deletingPathExtension
87        attributes.displayName = attributes.title
88        attributes.contentDescription = summary.description ?? file.relativePath
89        attributes.textContent = text
90        if let author = summary.author { attributes.authorNames = [author] }
91        attributes.keywords = summary.tags + summary.headings
92        return CSSearchableItem(uniqueIdentifier: file.path, domainIdentifier: "files", attributeSet: attributes)
93    }
94}
95#endif