SPB Git

Repository Public

SPSearchModels.swift 12.9 KB 328 lines swift

1import Foundation23/// The three modes of SP Search.4enum SearchKind: String, Codable, CaseIterable, Identifiable, Sendable {5    case web, images, videos6    var id: String { rawValue }78    var title: String {9        switch self {10        case .web: return L("All")11        case .images: return L("Images")12        case .videos: return L("Videos")13        }14    }1516    var symbol: String {17        switch self {18        case .web: return "magnifyingglass"19        case .images: return "photo.on.rectangle"20        case .videos: return "play.rectangle"21        }22    }23}2425enum SearchTimeRange: String, Codable, CaseIterable, Identifiable, Sendable {26    case day, week, month, year27    var id: String { rawValue }28    var title: String {29        switch self {30        case .day: return L("Past 24 hours")31        case .week: return L("Past week")32        case .month: return L("Past month")33        case .year: return L("Past year")34        }35    }36}3738enum VideoSource: String, Codable, CaseIterable, Identifiable, Sendable {39    case youtube, vimeo, dailymotion40    var id: String { rawValue }41    var title: String {42        switch self {43        case .youtube: return "YouTube"44        case .vimeo: return "Vimeo"45        case .dailymotion: return "Dailymotion"46        }47    }48}4950/// User-chosen search preferences. Synchronized between devices as part of the preferences record.51struct SearchPreferences: Codable, Equatable, Sendable {52    /// ISO 639-1 code; empty = no language restriction.53    var language = ""54    /// ISO 3166-1 alpha-2 code; empty = no region boost.55    var region = ""56    var safeSearch = true57    /// Ask the provider for a short AI-generated summary above web results.58    var showSummary = true59    var keepSearchHistory = true60    var videoLayoutIsGrid = true6162    static let languages: [(code: String, name: String)] = [63        ("", "—"), ("en", "English"), ("fr", "Français"), ("es", "Español"), ("de", "Deutsch"), ("it", "Italiano"), ("pt", "Português"),64        ("nl", "Nederlands"), ("ja", "日本語"), ("ko", "한국어"), ("zh", "中文"), ("ar", "العربية"), ("hi", "हिन्दी"),65    ]66    static let regions: [String] = ["", "ca", "us", "fr", "gb", "de", "es", "it", "be", "ch", "au", "br", "mx", "jp", "in", "nl", "se", "ie", "nz", "pt"]6768    static func regionName(_ code: String, locale: Locale = .current) -> String {69        code.isEmpty ? L("Any region") : (locale.localizedString(forRegionCode: code.uppercased()) ?? code.uppercased())70    }71}7273/// One search as sent to the backend (`POST /api/search`).74struct SearchQuery: Codable, Equatable, Hashable, Sendable {75    var query: String76    var type: SearchKind = .web77    var language: String?78    var region: String?79    var page = 180    var timeRange: SearchTimeRange?81    var safeSearch = true82    var summary = false83    var source: VideoSource?8485    init(_ text: String, kind: SearchKind = .web, preferences: SearchPreferences = SearchPreferences(), timeRange: SearchTimeRange? = nil,86         source: VideoSource? = nil, page: Int = 1) {87        query = SearchQuery.normalize(text)88        type = kind89        language = preferences.language.isEmpty ? nil : preferences.language90        region = preferences.region.isEmpty ? nil : preferences.region91        safeSearch = preferences.safeSearch92        summary = kind == .web && preferences.showSummary93        self.timeRange = timeRange94        self.source = kind == .videos ? source : nil95        self.page = page96    }9798    /// Same normalization as the server: control characters out, whitespace collapsed.99    static func normalize(_ text: String) -> String {100        let cleaned = text.precomposedStringWithCanonicalMapping.unicodeScalars.map { $0.value < 0x20 || $0.value == 0x7f ? " " : String($0) }.joined()101        return cleaned.split(whereSeparator: { $0.isWhitespace }).joined(separator: " ")102    }103}104105struct WebResult: Codable, Equatable, Identifiable, Sendable {106    var id: String107    var title: String108    var url: String109    var domain: String110    var favicon: String?111    var snippet: String112    var publishedDate: String?113    var score: Double?114}115116struct ImageResult: Codable, Equatable, Identifiable, Sendable {117    var id: String118    var imageURL: String119    var imageDomain: String120    var description: String?121    var sourceURL: String?122    var sourceTitle: String?123    var sourceDomain: String?124    var thumbnailURL: String?125    var width: Int?126    var height: Int?127    var author: String?128    var license: String?129    var provider: String130131    /// The address shown in the grid: the provider's smaller rendition when there is one.132    var displayURL: URL? { URL(string: thumbnailURL ?? imageURL) }133    var aspectRatio: Double? {134        guard let width, let height, width > 0, height > 0 else { return nil }135        return Double(width) / Double(height)136    }137}138139struct VideoResult: Codable, Equatable, Identifiable, Sendable {140    var id: String141    var url: String142    var title: String143    var platform: String144    var channel: String?145    var channelURL: String?146    var thumbnail: String?147    var durationSeconds: Int?148    var publishedDate: String?149    var description: String?150    var embedURL: String?151    var verifiedBy: String152153    var platformName: String { VideoSource(rawValue: platform)?.title ?? platform.capitalized }154155    var durationText: String? {156        guard let seconds = durationSeconds, seconds > 0 else { return nil }157        let h = seconds / 3600, m = (seconds % 3600) / 60, s = seconds % 60158        return h > 0 ? String(format: "%d:%02d:%02d", h, m, s) : String(format: "%d:%02d", m, s)159    }160}161162struct SearchAnswer: Codable, Equatable, Sendable {163    var text: String164    var generatedBy: String165}166167enum SearchResults: Equatable, Sendable {168    case web([WebResult])169    case images([ImageResult])170    case videos([VideoResult])171172    var count: Int {173        switch self {174        case .web(let r): return r.count175        case .images(let r): return r.count176        case .videos(let r): return r.count177        }178    }179    var isEmpty: Bool { count == 0 }180}181182/// One page of results as returned by the backend. `results` is decoded according to `type`.183struct SearchPage: Decodable, Equatable, Sendable {184    var query: String185    var type: SearchKind186    var page: Int187    var pageSize: Int188    var hasMore: Bool189    var provider: String190    var cached: Bool191    var tookMs: Int192    var answer: SearchAnswer?193    var results: SearchResults194    var notices: [String]195196    private enum CodingKeys: String, CodingKey { case query, type, page, pageSize, hasMore, provider, cached, tookMs, answer, results, notices }197198    init(from decoder: Decoder) throws {199        let c = try decoder.container(keyedBy: CodingKeys.self)200        query = try c.decode(String.self, forKey: .query)201        type = try c.decode(SearchKind.self, forKey: .type)202        page = try c.decode(Int.self, forKey: .page)203        pageSize = try c.decode(Int.self, forKey: .pageSize)204        hasMore = try c.decode(Bool.self, forKey: .hasMore)205        provider = try c.decode(String.self, forKey: .provider)206        cached = try c.decodeIfPresent(Bool.self, forKey: .cached) ?? false207        tookMs = try c.decodeIfPresent(Int.self, forKey: .tookMs) ?? 0208        answer = try c.decodeIfPresent(SearchAnswer.self, forKey: .answer)209        notices = try c.decodeIfPresent([String].self, forKey: .notices) ?? []210        switch type {211        case .web: results = .web(try c.decode([WebResult].self, forKey: .results))212        case .images: results = .images(try c.decode([ImageResult].self, forKey: .results))213        case .videos: results = .videos(try c.decode([VideoResult].self, forKey: .results))214        }215    }216217    init(query: String, type: SearchKind, page: Int, pageSize: Int, hasMore: Bool, provider: String, results: SearchResults,218         answer: SearchAnswer? = nil, notices: [String] = [], cached: Bool = false, tookMs: Int = 0) {219        self.query = query; self.type = type; self.page = page; self.pageSize = pageSize; self.hasMore = hasMore220        self.provider = provider; self.cached = cached; self.tookMs = tookMs; self.answer = answer; self.results = results; self.notices = notices221    }222}223224/// The address of a native SP Search results page. It is a real entry in a tab's back/forward list:225/// the web view holds an empty placeholder document for it and the app draws the native results on top.226enum SPSearchURL {227    static let scheme = "spsearch"228    static let host = "results"229230    static func make(query: String, kind: SearchKind = .web) -> URL? {231        let text = SearchQuery.normalize(query)232        guard !text.isEmpty else { return nil }233        var components = URLComponents()234        components.scheme = scheme235        components.host = host236        components.queryItems = [URLQueryItem(name: "q", value: text)] + (kind == .web ? [] : [URLQueryItem(name: "type", value: kind.rawValue)])237        return components.url238    }239240    static func isSearch(_ url: URL?) -> Bool { url?.scheme?.lowercased() == scheme }241242    static func parse(_ url: URL?) -> (query: String, kind: SearchKind)? {243        guard let url, isSearch(url), let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil }244        let items = components.queryItems ?? []245        let query = SearchQuery.normalize(items.first { $0.name == "q" }?.value ?? "")246        guard !query.isEmpty else { return nil }247        let kind = items.first { $0.name == "type" }?.value.flatMap(SearchKind.init(rawValue:)) ?? .web248        return (query, kind)249    }250251    /// The template of the built-in "SP Search" engine, in the form `SearchEngine` expects.252    static let engineTemplate = "\(scheme)://\(host)?q=%s"253}254255/// Splits `text` into runs that match one of the query's terms (case and diacritic insensitive) and runs that do not.256/// Used to emphasise matching terms in titles and snippets.257enum SearchHighlighter {258    static func terms(in query: String) -> [String] {259        let stop: Set<String> = ["the", "a", "an", "of", "to", "in", "on", "for", "and", "or", "is", "le", "la", "les", "de", "des", "du", "un", "une", "et", "ou", "en", "à"]260        var seen = Set<String>()261        return query.split(whereSeparator: { !$0.isLetter && !$0.isNumber }).map { fold(String($0)) }262            .filter { $0.count >= 2 && !stop.contains($0) && seen.insert($0).inserted }263    }264265    static func fold(_ text: String) -> String {266        text.folding(options: [.caseInsensitive, .diacriticInsensitive, .widthInsensitive], locale: nil)267    }268269    static func segments(of text: String, query: String) -> [(text: String, isMatch: Bool)] {270        let terms = terms(in: query)271        guard !terms.isEmpty, !text.isEmpty else { return text.isEmpty ? [] : [(text, false)] }272        var out: [(String, Bool)] = []273        var plain = ""274        var index = text.startIndex275        while index < text.endIndex {276            if text[index].isLetter || text[index].isNumber {277                var end = index278                while end < text.endIndex, text[end].isLetter || text[end].isNumber { end = text.index(after: end) }279                let word = String(text[index..<end])280                let folded = fold(word)281                if terms.contains(where: { folded == $0 || (folded.hasPrefix($0) && $0.count >= 4) }) {282                    if !plain.isEmpty { out.append((plain, false)); plain = "" }283                    out.append((word, true))284                } else {285                    plain += word286                }287                index = end288            } else {289                plain.append(text[index])290                index = text.index(after: index)291            }292        }293        if !plain.isEmpty { out.append((plain, false)) }294        return out295    }296}297298/// Publication dates arrive in several formats (RFC 1123 from the web provider, ISO 8601 from video platforms).299enum SearchDate {300    static func parse(_ text: String?) -> Date? {301        guard let text, !text.isEmpty else { return nil }302        let iso = ISO8601DateFormatter()303        iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]304        if let date = iso.date(from: text) { return date }305        iso.formatOptions = [.withInternetDateTime]306        if let date = iso.date(from: text) { return date }307        let formatter = DateFormatter()308        formatter.locale = Locale(identifier: "en_US_POSIX")309        for format in ["EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"] {310            formatter.dateFormat = format311            formatter.timeZone = TimeZone(identifier: "UTC")312            if let date = formatter.date(from: text) { return date }313        }314        return nil315    }316317    static func display(_ text: String?, now: Date = Date()) -> String? {318        guard let date = parse(text), date <= now.addingTimeInterval(86400) else { return nil }319        let days = now.timeIntervalSince(date) / 86400320        if days < 7 {321            let relative = RelativeDateTimeFormatter()322            relative.unitsStyle = .full323            return relative.localizedString(for: date, relativeTo: now)324        }325        return date.formatted(date: .abbreviated, time: .omitted)326    }327}328
Files main
Menu

Theme