Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Drive pour macOS9// File : App/SpotlightIndexer.swift10// Description : Optional Core Spotlight index of item METADATA only —11// name, kind, dates, location — never content. Off by12// default; incremental from the mirror's change counter;13// erased when the setting is turned off and at sign-out.14// Module : App15// Repository : https://git.spboucher.ai/sp-drive-macos16// Created : 2026-11-1917// Last Modified : 2026-11-1918//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import CoreSpotlight92import Foundation93import SPDriveCore94import UniformTypeIdentifiers9596@MainActor final class SpotlightIndexer {97 static let shared = SpotlightIndexer()98 static let domain = "ai.spboucher.spdrive.items"99 private let index = CSSearchableIndex(name: "ai.spboucher.spdrive\(AppEnvironment.variant)")100 private var running = false101 private(set) var lastIndexed = 0102103 /// What Spotlight is told about one item. Deliberately small: nothing here is read from the file's bytes.104 static func attributes(for item: DriveItem, path: String) -> CSSearchableItemAttributeSet {105 let type: UTType = item.isFolder ? .folder : (UTType(filenameExtension: item.fileExtension) ?? .data)106 let a = CSSearchableItemAttributeSet(contentType: type)107 a.title = item.name; a.displayName = item.name108 a.contentCreationDate = item.createdAt; a.contentModificationDate = item.isFolder ? item.updatedAt : item.contentAt109 a.kind = type.localizedDescription110 a.containerTitle = "SP Drive"; a.containerDisplayName = "SP Drive"111 a.path = path.isEmpty ? "SP Drive" : "SP Drive › " + path112 if !item.isFolder { a.fileSize = NSNumber(value: item.size) }113 a.keywords = ["SP Drive"] + (item.fileExtension.isEmpty ? [] : [item.fileExtension]) + (item.starred ? ["favori"] : [])114 return a115 }116 /// Brings the index in line with the mirror (changes since the last pass). No-op when the setting is off.117 func sync(model: AppModel) async {118 guard model.settings.spotlightIndex, CSSearchableIndex.isIndexingAvailable(), let store = model.store, !running else { return }119 running = true; defer { running = false }120 let d = AppEnvironment.defaults121 var since: Int64 = d.string(forKey: "spotlightGeneration") == store.generation ? Int64(d.integer(forKey: "spotlightSeq")) : 0122 if since == 0 { try? await index.deleteSearchableItems(withDomainIdentifiers: [SpotlightIndexer.domain]) }123 while let page = try? store.changes(since: since, limit: 400), page.seq > since {124 let live = page.items.filter { !$0.isTrashed && !$0.isRoot && !$0.id.hasPrefix("local-") }125 let gone = page.deleted + page.items.filter(\.isTrashed).map(\.id)126 let items = live.map { i -> CSSearchableItem in127 let path = ((try? store.path(to: i.id)) ?? []).dropLast().map(\.name).joined(separator: " › ")128 return CSSearchableItem(uniqueIdentifier: i.id, domainIdentifier: SpotlightIndexer.domain, attributeSet: SpotlightIndexer.attributes(for: i, path: path))129 }130 do {131 if !items.isEmpty { try await index.indexSearchableItems(items) }132 if !gone.isEmpty { try await index.deleteSearchableItems(withIdentifiers: gone) }133 } catch { AppEnvironment.log.info("spotlight: \(error.localizedDescription, privacy: .public)"); return }134 lastIndexed += items.count135 since = page.seq136 d.set(store.generation, forKey: "spotlightGeneration"); d.set(Int(since), forKey: "spotlightSeq")137 if !page.more { break }138 }139 }140 /// Erases everything SP Drive put in Spotlight (setting turned off, sign-out).141 func removeAll() async {142 try? await index.deleteSearchableItems(withDomainIdentifiers: [SpotlightIndexer.domain])143 try? await index.deleteAllSearchableItems()144 AppEnvironment.defaults.removeObject(forKey: "spotlightSeq"); AppEnvironment.defaults.removeObject(forKey: "spotlightGeneration")145 lastIndexed = 0146 }147 /// Number of items Spotlight returns for a name, in SP Drive's own index (used by the self-test).148 func count(named name: String) async -> Int {149 let escaped = name.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")150 let context = CSSearchQueryContext(); context.fetchAttributes = ["title"]151 let q = CSSearchQuery(queryString: "title == \"\(escaped)\"", queryContext: context)152 var n = 0153 do { for try await r in q.results where r.item.domainIdentifier == SpotlightIndexer.domain { n += 1 } } catch { return -1 }154 return n155 }156}157