SPB Git

Repository Public

SearchRequest.swift 11.6 KB 232 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Search iOS9// File             : Core/Sources/SPSearchKit/SearchRequest.swift10// Description      : Search request, region choice and construction of the API11//                    addresses.12// Module           : SPSearchKit13// Repository       : https://git.spboucher.ai/sp-search-ios14// Project Website  : https://search.spboucher.ai15// Created          : 2026-12-0116// Last Modified    : 2026-12-0117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation9192/// The reader's region setting. `automatic` sends no parameter: the server reads the region declared by Accept-Language.93public enum RegionChoice: String, Sendable, CaseIterable, Hashable {94    case automatic = "", canada = "ca", quebec = "ca-qc", france = "fr", switzerland = "ch", belgium = "be"95    case unitedStates = "us", unitedKingdom = "gb", off = "none"96}9798public struct SearchFilters: Sendable, Hashable {99    /// ISO 639 language code, e.g. "fr".100    public var language: String?101    /// Domain, e.g. "ulaval.ca".102    public var site: String?103    /// Page type as the server names it, e.g. "encyclopedia".104    public var kind: String?105    /// Shortcut for a recent period, as `/v2/filters` lists them: "day", "week", "month", "year". Replaces the bounds.106    public var fresh: String?107    /// Bounds on the verified publication date, as calendar days.108    public var from: Date?109    public var to: Date?110111    public init(language: String? = nil, site: String? = nil, kind: String? = nil, fresh: String? = nil, from: Date? = nil, to: Date? = nil) {112        self.language = language; self.site = site; self.kind = kind; self.fresh = fresh; self.from = from; self.to = to113    }114    public var hasDate: Bool { fresh != nil || from != nil || to != nil }115    public var isEmpty: Bool { language == nil && site == nil && kind == nil && !hasDate }116    public var count: Int { [language != nil, site != nil, kind != nil, hasDate].filter { $0 }.count }117}118119public struct SearchRequest: Sendable, Hashable {120    public static let maxQueryLength = 256121    public static let defaultVertical = "web"122    public var query: String123    public var limit: Int124    public var cursor: String?125    public var filters: SearchFilters126    public var region: RegionChoice127    /// Interface language, a light ranking signal: "fr" or "en".128    public var interfaceLanguage: String?129    /// A category listed by `/v2/filters`.130    public var vertical: String131    /// False: search the query as typed, without automatic correction (`correct=0`).132    public var correct: Bool133134    public init(query: String, limit: Int = 10, cursor: String? = nil, filters: SearchFilters = SearchFilters(),135                region: RegionChoice = .automatic, interfaceLanguage: String? = nil, vertical: String = SearchRequest.defaultVertical,136                correct: Bool = true) {137        self.query = query; self.limit = limit; self.cursor = cursor; self.filters = filters138        self.region = region; self.interfaceLanguage = interfaceLanguage; self.vertical = vertical; self.correct = correct139    }140141    /// Trimmed, inner whitespace collapsed, cut to the length the server accepts.142    public static func normalise(_ text: String) -> String {143        let collapsed = text.split(whereSeparator: \.isWhitespace).joined(separator: " ")144        return String(collapsed.prefix(maxQueryLength))145    }146147    /// The same search at another position.148    public func page(after cursor: String) -> SearchRequest { var r = self; r.cursor = cursor; return r }149150    /// Parameters of `/v2/search`.151    public var queryItems: [URLQueryItem] { items(.v2) }152153    /// A V1 server knows neither categories, page types, periods nor the correction switch: they are left out.154    public func items(_ version: APIVersion) -> [URLQueryItem] {155        let v2 = version == .v2156        var items = [URLQueryItem(name: "q", value: Self.normalise(query)), URLQueryItem(name: "limit", value: String(min(20, max(1, limit))))]157        if let cursor, !cursor.isEmpty { items.append(URLQueryItem(name: "cursor", value: cursor)) }158        if v2, !vertical.isEmpty, vertical != Self.defaultVertical { items.append(URLQueryItem(name: "vertical", value: vertical)) }159        if let l = filters.language, !l.isEmpty { items.append(URLQueryItem(name: "lang", value: l)) }160        if let s = filters.site, !s.isEmpty { items.append(URLQueryItem(name: "site", value: s)) }161        if v2, let k = filters.kind, !k.isEmpty { items.append(URLQueryItem(name: "kind", value: k)) }162        if v2, let f = filters.fresh, !f.isEmpty {163            items.append(URLQueryItem(name: "fresh", value: f))164        } else {165            if let d = filters.from { items.append(URLQueryItem(name: "from", value: Self.day(d))) }166            if let d = filters.to { items.append(URLQueryItem(name: "to", value: Self.day(d))) }167        }168        if let hl = interfaceLanguage, !hl.isEmpty { items.append(URLQueryItem(name: "hl", value: hl)) }169        if region != .automatic { items.append(URLQueryItem(name: "region", value: region.rawValue)) }170        if v2, !correct { items.append(URLQueryItem(name: "correct", value: "0")) }171        return items172    }173174    /// Calendar day in the device's time zone, as the API expects it: 2026-12-01.175    public static func day(_ date: Date, calendar: Calendar = .current) -> String {176        var cal = Calendar(identifier: .gregorian)177        cal.timeZone = calendar.timeZone178        let c = cal.dateComponents([.year, .month, .day], from: date)179        return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0)180    }181182    /// Reads `2026-12-01` back as the start of that day in the device's time zone.183    public static func date(day: String, calendar: Calendar = .current) -> Date? {184        let parts = day.split(separator: "-").compactMap { Int($0) }185        guard day.count == 10, parts.count == 3, (1...12).contains(parts[1]), (1...31).contains(parts[2]) else { return nil }186        var cal = Calendar(identifier: .gregorian)187        cal.timeZone = calendar.timeZone188        return cal.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2]))189    }190}191192public enum Endpoint {193    public static let production = URL(string: "https://search.spboucher.ai")!194195    /// Everything outside the unreserved set is percent-encoded, `+` included (a server reads a bare `+` as a space).196    static let unreserved = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")197198    public static func url(base: URL = production, path: String, items: [URLQueryItem]) -> URL {199        var c = URLComponents(url: base, resolvingAgainstBaseURL: false) ?? URLComponents()200        c.path = path201        if !items.isEmpty {202            c.percentEncodedQueryItems = items.map {203                URLQueryItem(name: $0.name, value: ($0.value ?? "").addingPercentEncoding(withAllowedCharacters: unreserved))204            }205        }206        return c.url ?? base207    }208209    public static func search(_ r: SearchRequest, version: APIVersion = .v2, base: URL = production) -> URL {210        url(base: base, path: version == .v2 ? "/v2/search" : "/v1/search", items: r.items(version))211    }212    public static func autocomplete(_ q: String, interfaceLanguage: String? = nil, base: URL = production) -> URL {213        var items = [URLQueryItem(name: "q", value: SearchRequest.normalise(q))]214        if let hl = interfaceLanguage, !hl.isEmpty { items.append(URLQueryItem(name: "hl", value: hl)) }215        return url(base: base, path: "/v2/autocomplete", items: items)216    }217    public static func filters(base: URL = production) -> URL { url(base: base, path: "/v2/filters", items: []) }218    public static func status(base: URL = production) -> URL { url(base: base, path: "/v2/status", items: []) }219    // V1, used only when the server does not know the V2 routes.220    public static func suggest(_ q: String, base: URL = production) -> URL {221        url(base: base, path: "/v1/suggest", items: [URLQueryItem(name: "q", value: SearchRequest.normalise(q))])222    }223    public static func stats(base: URL = production) -> URL { url(base: base, path: "/v1/stats", items: []) }224225    /// Address of a site icon on the engine's own server. A path that leads to another host is refused: the app226    /// never contacts a third-party site on its own.227    public static func favicon(path: String, base: URL = production) -> URL? {228        guard path.hasPrefix("/"), !path.hasPrefix("//"), let u = URL(string: path, relativeTo: base)?.absoluteURL else { return nil }229        return u.host == base.host && u.scheme == base.scheme ? u : nil230    }231}232
Files main
Menu

Theme