SPB Git

Repository Public

SystemIntegration.swift 7.2 KB 160 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/App/SystemIntegration.swift4//  Description: System integration: Siri / Shortcuts intents, Home Screen quick actions, background refresh, notification taps.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import AppIntents11import BackgroundTasks12import UIKit13import UserNotifications1415// MARK: App Intents (Shortcuts, Siri, Spotlight, Action button)1617struct NewConversationIntent: AppIntent {18    static let title: LocalizedStringResource = "Nouvelle conversation"19    static let description = IntentDescription("Ouvre SP Chat sur une nouvelle conversation.")20    static let openAppWhenRun = true2122    @MainActor func perform() async throws -> some IntentResult {23        AppEnvironmentHolder.shared?.handle(url: URL(string: "spchat://new")!)24        return .result()25    }26}2728struct AskIntent: AppIntent {29    static let title: LocalizedStringResource = "Demander à SP Chat"30    static let description = IntentDescription("Ouvre SP Chat avec un message prêt à envoyer. Rien n’est envoyé sans toi.")31    static let openAppWhenRun = true3233    @Parameter(title: "Message", inputOptions: String.IntentInputOptions(multiline: true))34    var text: String3536    @MainActor func perform() async throws -> some IntentResult {37        var comps = URLComponents(); comps.scheme = AppConfiguration.urlScheme; comps.host = "new"38        comps.queryItems = [URLQueryItem(name: "text", value: text)]39        if let url = comps.url { AppEnvironmentHolder.shared?.handle(url: url) }40        return .result()41    }42}4344struct SPChatShortcuts: AppShortcutsProvider {45    static var appShortcuts: [AppShortcut] {46        AppShortcut(intent: NewConversationIntent(), phrases: ["Nouvelle conversation dans \(.applicationName)", "New chat in \(.applicationName)"], shortTitle: "Nouvelle conversation", systemImageName: "square.and.pencil")47        AppShortcut(intent: AskIntent(), phrases: ["Demander à \(.applicationName)", "Ask \(.applicationName)"], shortTitle: "Demander", systemImageName: "bubble.left.and.text.bubble.right")48    }49}5051/// Lets intents and delegates reach the running environment without a global mutable singleton of services.52@MainActor53enum AppEnvironmentHolder {54    static weak var shared: AppEnvironment?55}5657// MARK: background refresh5859/// Opportunistic refresh while the app is in the background: conversation list for offline reading, and the outbox.60/// iOS decides when (and whether) it runs; nothing depends on it.61enum BackgroundSync {62    static func register() {63        BGTaskScheduler.shared.register(forTaskWithIdentifier: AppConfiguration.backgroundSyncTaskIdentifier, using: nil) { task in64            guard let refresh = task as? BGAppRefreshTask else { return }65            schedule()66            // BGTask is not Sendable; it is only completed once, from the main actor67            let box = UncheckedBox(refresh)68            let work = Task { @MainActor in69                await AppEnvironmentHolder.shared?.synchronize()70                box.value.setTaskCompleted(success: !Task.isCancelled)71            }72            refresh.expirationHandler = { work.cancel() }73        }74    }7576    static func schedule() {77        let request = BGAppRefreshTaskRequest(identifier: AppConfiguration.backgroundSyncTaskIdentifier)78        request.earliestBeginDate = Date(timeIntervalSinceNow: 30 * 60)79        try? BGTaskScheduler.shared.submit(request)80    }81}8283struct UncheckedBox<T>: @unchecked Sendable { let value: T; init(_ v: T) { value = v } }8485// MARK: notifications8687final class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {88    /// Tapping "answer ready" opens its conversation.89    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {90        guard let id = response.notification.request.content.userInfo["conversationId"] as? String, let url = URL(string: "spchat://c/\(id)") else { return }91        await MainActor.run { AppEnvironmentHolder.shared?.handle(url: url) }92    }93    /// No banner for a conversation that is on screen.94    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { [] }95}9697// MARK: Home Screen Quick Actions9899/// The static shortcuts declared in Info.plist (`UIApplicationShortcutItems`): new chat, search, arena. Each one is100/// routed through the same deep links as everything else (`AppEnvironment.handle(url:)`).101@MainActor102enum QuickActions {103    static let prefix = AppConfiguration.bundleIdentifier + ".shortcut."104105    /// `ai.spboucher.spchat.shortcut.new` → `spchat://new`. Unknown types are refused.106    nonisolated static func url(forType type: String) -> URL? {107        let p = AppConfiguration.bundleIdentifier + ".shortcut."108        guard type.hasPrefix(p) else { return nil }109        let name = String(type.dropFirst(p.count))110        guard ["new", "search", "arena"].contains(name) else { return nil }111        return URL(string: "\(AppConfiguration.urlScheme)://\(name)")112    }113114    private static var pending: Task<Void, Never>?115116    /// Runs a shortcut. On a cold launch the environment may still be restoring its session (and the app may be117    /// locked): the action waits — at most 20 s — until the owner is signed in and the app unlocked, then runs once.118    @discardableResult119    static func perform(_ item: UIApplicationShortcutItem) -> Bool {120        guard let url = url(forType: item.type) else { return false }121        pending?.cancel()122        pending = Task { @MainActor in123            for _ in 0..<100 {124                if Task.isCancelled { return }125                if let env = AppEnvironmentHolder.shared, env.auth.phase == .signedIn, !env.appLock.isLocked, env.router.current != nil || url.host() != "new" {126                    env.handle(url: url)127                    return128                }129                try? await Task.sleep(for: .milliseconds(200))130            }131        }132        return true133    }134}135136/// Scene delegate used only for quick actions; SwiftUI keeps managing the window of the `WindowGroup`.137final class SceneDelegate: NSObject, UIWindowSceneDelegate {138    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {139        // cold launch from a shortcut140        if let item = connectionOptions.shortcutItem { QuickActions.perform(item) }141    }142    func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem) async -> Bool {143        QuickActions.perform(shortcutItem)144    }145}146147final class AppDelegate: NSObject, UIApplicationDelegate {148    let notifications = NotificationDelegate()149    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {150        let configuration = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role)151        configuration.delegateClass = SceneDelegate.self152        return configuration153    }154    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {155        BackgroundSync.register()156        UNUserNotificationCenter.current().delegate = notifications157        return true158    }159}160
Files main
Menu

Theme