SPB Git

Repository Public

LocalSearch.swift 5.1 KB 92 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Metadata/LocalSearch.swift3// Description: Search in the local metadata mirror — by name, extension, type, folder, date, size, favourites, shared — paginated, usable without a network.4import Foundation56public enum FileCategory: String, CaseIterable, Sendable, Identifiable {7    case any, folder, image, pdf, document, sheet, video, audio, archive, text8    public var id: String { rawValue }9    /// Same families as the server's own search.10    public var extensions: [String] {11        switch self {12        case .any, .folder: return []13        case .image: return ["jpg", "jpeg", "png", "webp", "gif", "heic", "heif", "svg", "tiff", "bmp"]14        case .pdf: return ["pdf"]15        case .document: return ["doc", "docx", "odt", "ppt", "pptx", "odp", "rtf", "pages", "key"]16        case .sheet: return ["xlsx", "xls", "ods", "csv", "numbers"]17        case .video: return ["mp4", "m4v", "mov", "webm", "mkv", "avi"]18        case .audio: return ["mp3", "m4a", "aac", "wav", "ogg", "flac"]19        case .archive: return ["zip", "tar", "gz", "tgz", "7z", "rar"]20        case .text: return ["txt", "md", "json", "xml", "log", "yaml", "yml", "tex"]21        }22    }23    public static func of(_ item: DriveItem) -> FileCategory {24        if item.isFolder { return .folder }25        let e = item.fileExtension26        return allCases.first { $0.extensions.contains(e) } ?? .any27    }28}29public enum SortKey: String, Sendable, CaseIterable { case name, updated, size, kind }3031public struct LocalSearch: Sendable {32    public var text = ""33    public var category = FileCategory.any34    /// Explicit extension ("pdf"), in addition to the category.35    public var fileExtension: String?36    /// Restricts to a folder and everything below it.37    public var folderID: String?38    public var modifiedAfter: Date?39    public var modifiedBefore: Date?40    public var minSize: Int64?41    public var maxSize: Int64?42    public var starredOnly = false43    /// When set, only these identifiers (e.g. the items that have a share link).44    public var onlyIDs: Set<String>?45    public var sort = SortKey.name46    public var ascending = true47    public var limit = 20048    public var offset = 049    public init(text: String = "") { self.text = text }50    public var isEmpty: Bool {51        text.trimmingCharacters(in: .whitespaces).isEmpty && category == .any && fileExtension == nil && modifiedAfter == nil && modifiedBefore == nil && minSize == nil && maxSize == nil && !starredOnly && onlyIDs == nil52    }53}5455extension MetadataStore {56    /// Live items matching the query. Words of the text must all appear in the name (accents and case ignored).57    public func search(_ q: LocalSearch) throws -> [DriveItem] {58        var sql = "", v: [SQLValue] = [], w: [String] = ["i.trashed_at IS NULL", "i.parent_id IS NOT NULL"]59        if let f = q.folderID {60            sql = "WITH RECURSIVE sub(id) AS (SELECT ? UNION ALL SELECT c.id FROM items c JOIN sub ON c.parent_id = sub.id WHERE c.trashed_at IS NULL AND c.kind = 'folder') "61            v.append(.text(f)); w.append("i.parent_id IN (SELECT id FROM sub)")62        }63        for word in NameRules.searchKey(q.text).split(separator: " ") where !word.isEmpty {64            w.append("i.name_key LIKE ? ESCAPE '\\'")65            v.append(.text("%" + word.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "%", with: "\\%").replacingOccurrences(of: "_", with: "\\_") + "%"))66        }67        if q.category == .folder { w.append("i.kind = 'folder'") }68        else if !q.category.extensions.isEmpty { w.append("i.kind = 'file' AND i.ext IN (\(q.category.extensions.map { _ in "?" }.joined(separator: ",")))"); v += q.category.extensions.map(SQLValue.text) }69        if let e = q.fileExtension?.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: ". ")), !e.isEmpty { w.append("i.kind = 'file' AND i.ext = ?"); v.append(.text(e)) }70        if let d = q.modifiedAfter { w.append("i.updated_at >= ?"); v.append(.double(d.timeIntervalSince1970)) }71        if let d = q.modifiedBefore { w.append("i.updated_at < ?"); v.append(.double(d.timeIntervalSince1970)) }72        if let s = q.minSize { w.append("i.kind = 'file' AND i.size >= ?"); v.append(.int(s)) }73        if let s = q.maxSize { w.append("i.kind = 'file' AND i.size <= ?"); v.append(.int(s)) }74        if q.starredOnly { w.append("i.starred = 1") }75        if let ids = q.onlyIDs {76            guard !ids.isEmpty else { return [] }77            w.append("i.id IN (\(ids.map { _ in "?" }.joined(separator: ",")))"); v += ids.sorted().map(SQLValue.text)78        }79        let dir = q.ascending ? "ASC" : "DESC"80        let order: String81        switch q.sort {82        case .name: order = "i.kind DESC, i.name_key \(dir)"83        case .updated: order = "i.updated_at \(dir)"84        case .size: order = "i.kind DESC, i.size \(dir), i.name_key"85        case .kind: order = "i.kind DESC, i.ext \(dir), i.name_key"86        }87        sql += "SELECT i.* FROM items i WHERE \(w.joined(separator: " AND ")) ORDER BY \(order), i.id LIMIT ? OFFSET ?"88        v += [.int(Int64(q.limit)), .int(Int64(q.offset))]89        return try db.query(sql, v).map(MetadataStore.item)90    }91}92
Files main
Menu

Theme