Sources/OrgApp/XCallback.swift

73b5c3d29343d6a3801f3a9a591fa434c01c9f06
orgstar/Sources/OrgApp/XCallback.swift

491 lines · 23185 bytes

43 symbols in this file
  1import Foundation
  2import Observation
  3import OrgCore
  4import OrgPresentation
  5
  6/// An x-callback-url 1.0 request on the app's scheme:
  7/// `orgstar://x-callback-url/<action>?…&x-success=…&x-error=…&x-cancel=…&x-source=…`.
  8public struct XCallbackRequest: Equatable, Sendable {
  9    public enum Action: String, CaseIterable, Sendable {
 10        case capture, open, agenda
 11        case clockIn = "clock-in"
 12        case clockOut = "clock-out"
 13        case clockStatus = "clock-status"
 14    }
 15
 16    public static let host = "x-callback-url"
 17
 18    /// The path after the host, as given.
 19    public let action: String
 20    /// The query's parameters other than the `x-` ones; the first of repeated names wins.
 21    public let parameters: [String: String]
 22    public let success: URL?
 23    public let failure: URL?
 24    public let cancel: URL?
 25    /// `x-source`: the calling app's name, as it gives it.
 26    public let source: String?
 27
 28    public init?(url: URL) {
 29        guard url.scheme?.lowercased() == AppLink.scheme, url.host?.lowercased() == Self.host,
 30              let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil }
 31        action = components.path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
 32        var parameters: [String: String] = [:]
 33        for item in components.queryItems ?? [] where parameters[item.name] == nil {
 34            parameters[item.name] = item.value ?? ""
 35        }
 36        func callback(_ name: String) -> URL? {
 37            parameters.removeValue(forKey: name).flatMap { $0.isEmpty ? nil : URL(string: $0) }
 38        }
 39        success = callback("x-success")
 40        failure = callback("x-error")
 41        cancel = callback("x-cancel")
 42        source = parameters.removeValue(forKey: "x-source").flatMap { $0.isEmpty ? nil : $0 }
 43        self.parameters = parameters
 44    }
 45
 46    public var known: Action? { Action(rawValue: action) }
 47
 48    /// A parameter, nil when missing or empty.
 49    public func value(_ name: String) -> String? {
 50        parameters[name].flatMap { $0.isEmpty ? nil : $0 }
 51    }
 52
 53    /// The URL to open for `reply`: its callback with the reply's parameters added; nil when the
 54    /// request gave none or its scheme is refused (`XCallback.allows`).
 55    public func callbackURL(for reply: XCallbackReply) -> URL? {
 56        let url: URL?
 57        switch reply {
 58        case .success(let parameters): url = success.flatMap { XCallback.url($0, adding: parameters) }
 59        case .failure(let code, let message): url = failure.flatMap { XCallback.url($0, adding: ["errorCode": code, "errorMessage": message]) }
 60        case .cancel: url = cancel
 61        }
 62        return url.flatMap { XCallback.allows($0) ? $0 : nil }
 63    }
 64
 65    /// Who an approval is for: the name the request gives and the schemes its callbacks open.
 66    public var approvalSource: XCallbackApprovals.Source {
 67        let schemes = Set([success, failure, cancel].compactMap { $0?.scheme?.lowercased() })
 68        return XCallbackApprovals.Source(name: source ?? "", schemes: schemes.sorted())
 69    }
 70}
 71
 72/// What an action ends with.
 73public enum XCallbackReply: Equatable, Sendable {
 74    /// For `x-success`, with the result's parameters.
 75    case success([String: String])
 76    /// For `x-error`, as `errorCode` and `errorMessage`.
 77    case failure(code: String, message: String)
 78    /// For `x-cancel`.
 79    case cancel
 80
 81    public static func failure(_ code: XCallback.ErrorCode, _ message: String) -> XCallbackReply {
 82        .failure(code: code.rawValue, message: message)
 83    }
 84}
 85
 86public enum XCallback {
 87    public enum ErrorCode: String, Sendable {
 88        case unknownAction = "unknown-action"
 89        case missingParameter = "missing-parameter"
 90        case invalidParameter = "invalid-parameter"
 91        case notFound = "not-found"
 92        case captureFailed = "capture-failed"
 93        case clockFailed = "clock-failed"
 94        case noClock = "no-clock"
 95        case notAllowed = "not-allowed"
 96        case needsPro = "needs-orgstar-plus"
 97        case notReady = "not-ready"
 98    }
 99
100    /// Callback schemes never opened: the app's own (a loop), org-protocol (it would capture),
101    /// and web and file URLs, which would hand results to a web server or download a file.
102    public static let refusedSchemes: Set<String> = ["orgstar", "org-protocol", "http", "https", "file", "ftp", "javascript", "data", "about", "blob"]
103
104    public static func allows(_ url: URL) -> Bool {
105        guard let scheme = url.scheme?.lowercased(), !scheme.isEmpty else { return false }
106        return !refusedSchemes.contains(scheme)
107    }
108
109    /// Characters left as they are in a query value: `&`, `=`, `+`, `?`, `#` and `/` are encoded.
110    static let valueCharacters = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._~"))
111
112    /// `base` with `parameters` added to its query, after any it has, in name order.
113    public static func url(_ base: URL, adding parameters: [String: String]) -> URL? {
114        guard var components = URLComponents(url: base, resolvingAgainstBaseURL: false) else { return nil }
115        let added = parameters.sorted { $0.key < $1.key }.map { name, value in
116            URLQueryItem(name: name.addingPercentEncoding(withAllowedCharacters: valueCharacters) ?? name,
117                         value: value.addingPercentEncoding(withAllowedCharacters: valueCharacters) ?? value)
118        }
119        guard !added.isEmpty else { return base }
120        components.percentEncodedQueryItems = (components.percentEncodedQueryItems ?? []) + added
121        return components.url
122    }
123}
124
125/// The apps allowed to capture, clock and read the agenda and clock through x-callback-url
126/// links, kept on the device. An app is the name it gives in `x-source` with the schemes its
127/// callbacks open, so a link that names an allowed app but sends results elsewhere asks again.
128@MainActor
129@Observable
130public final class XCallbackApprovals {
131    public static let shared = XCallbackApprovals()
132    static let key = "xCallbackApprovals"
133
134    public struct Source: Codable, Hashable, Sendable, Identifiable {
135        public let name: String
136        public let schemes: [String]
137        public var id: String { ([name] + schemes).joined(separator: "\u{0}") }
138
139        public init(name: String, schemes: [String]) {
140            self.name = name
141            self.schemes = schemes
142        }
143    }
144
145    public private(set) var sources: [Source] = []
146    private let defaults: UserDefaults
147
148    public init(defaults: UserDefaults = .standard) {
149        self.defaults = defaults
150        if let data = defaults.data(forKey: Self.key), let saved = try? JSONDecoder().decode([Source].self, from: data) { sources = saved }
151    }
152
153    public func allows(_ source: Source) -> Bool { sources.contains(source) }
154
155    public func allow(_ source: Source) {
156        guard !allows(source) else { return }
157        sources.append(source)
158        save()
159    }
160
161    public func forget(_ source: Source) {
162        sources.removeAll { $0 == source }
163        save()
164    }
165
166    private func save() {
167        if sources.isEmpty {
168            defaults.removeObject(forKey: Self.key)
169        } else if let data = try? JSONEncoder().encode(sources) {
170            defaults.set(data, forKey: Self.key)
171        }
172    }
173}
174
175/// Runs x-callback-url actions against the app's models. What needs the app (a sheet, a
176/// question, showing a file) comes back as a step for it to take.
177@MainActor
178public struct XCallbackRunner {
179    public let workspace: WorkspaceModel
180    public let session: DocumentSession
181    public let clock: ClockModel
182    public var approvals: XCallbackApprovals
183    public var templates: () -> [CaptureTemplate] = { CaptureTemplates.load().templates }
184    public var views: () -> [AgendaViewDefinition] = { AgendaViewLoader.load().views }
185    public var isUnlocked: () -> Bool = { ProAccess.shared.isUnlocked }
186    /// `%c` and `%n` for captures without the sheet.
187    public var clipboard: () -> String = { "" }
188    public var userName = ""
189    public var now: () -> Date = Date.init
190    public var calendar = Calendar.current
191
192    /// Agenda entries returned when the request sets no `limit`, and the most it may set.
193    public static let defaultLimit = 50
194    public static let maximumLimit = 200
195
196    public init(workspace: WorkspaceModel, session: DocumentSession, clock: ClockModel, approvals: XCallbackApprovals = .shared) {
197        self.workspace = workspace
198        self.session = session
199        self.clock = clock
200        self.approvals = approvals
201    }
202
203    public enum Step: Equatable {
204        /// Open the reply's callback, if any.
205        case reply(XCallbackReply)
206        /// Ask whether the request's source may write to files and read them through links;
207        /// then `allow` and run again, or reply `notAllowed`.
208        case approve(XCallbackApprovals.Source)
209        /// Show the capture sheet or window with this template (nil for the list) and link
210        /// properties; reply with `captured` when it files, `.cancel` when it is dismissed.
211        case capture(template: String?, properties: [String: String])
212        /// Show the entry, then reply.
213        case open(path: String, offset: Int, reply: XCallbackReply)
214    }
215
216    public func run(_ request: XCallbackRequest, ask: @escaping ClockModel.Ask = { _ in nil }) async -> Step {
217        guard let action = request.known else {
218            return .reply(.failure(.unknownAction, "Unknown action \"\(request.action)\""))
219        }
220        // Capture and open show what they do; the others write to files or send what they hold
221        // to the caller without showing anything.
222        let interactive: Bool
223        switch action {
224        case .open: interactive = true
225        case .capture: interactive = captureNeedsSheet(request)
226        case .agenda, .clockIn, .clockOut, .clockStatus: interactive = false
227        }
228        if !interactive {
229            guard isUnlocked() else { return .reply(.failure(.needsPro, "x-callback-url actions need orgstar+")) }
230            guard approvals.allows(request.approvalSource) else { return .approve(request.approvalSource) }
231        }
232        // A link that launched the app can come before the folders were first read.
233        if workspace.files.isEmpty { await workspace.refresh() }
234        switch action {
235        case .capture: return capture(request, sheet: interactive)
236        case .open: return open(request)
237        case .agenda: return .reply(await agenda(request))
238        case .clockIn: return .reply(await clockIn(request, ask: ask))
239        case .clockOut: return .reply(clockOut())
240        case .clockStatus: return .reply(.success(clockStatus()))
241        }
242    }
243
244    // MARK: - Capture
245
246    /// The template a capture names, its link properties and its text as org-protocol gives
247    /// them: `%a`, `%i`, `%:link`, `%:description`.
248    static func properties(_ request: XCallbackRequest) -> [String: String] {
249        let link = OrgProtocol.captureURL(template: nil, url: request.value("url"), title: request.value("title") ?? "", body: request.value("text") ?? "")
250        guard case .capture(_, let properties)? = OrgProtocol.parse(link) else { return [:] }
251        return properties
252    }
253
254    static let reservedCaptureParameters: Set<String> = ["template", "text", "url", "title"]
255
256    /// Without the sheet only when the template and text are given and every prompt in the
257    /// template has a parameter named for it; templates that make a Denote note or ask for a
258    /// date tree's day always show it.
259    func captureNeedsSheet(_ request: XCallbackRequest) -> Bool {
260        guard let key = request.value("template"), let text = request.parameters["text"],
261              let template = templates().first(where: { $0.key == key }) else { return true }
262        if template.options.denote || template.asksTreeDate { return true }
263        return !Self.unanswered(template, text: text, properties: Self.properties(request), given: Set(request.parameters.keys)).isEmpty
264    }
265
266    /// The prompts of `template` that `given` has no answer for, by prompt text, in order.
267    static func unanswered(_ template: CaptureTemplate, text: String, properties: [String: String], given: Set<String>) -> [String] {
268        var context = CaptureContext(initial: text)
269        context.linkProperties = properties
270        return Capture.questions(template.template, context: context).compactMap { question in
271            if case .clipboard = question.kind { return nil }
272            return given.contains(question.prompt) ? nil : question.prompt
273        }
274    }
275
276    private func capture(_ request: XCallbackRequest, sheet: Bool) -> Step {
277        let properties = Self.properties(request)
278        if sheet { return .capture(template: request.value("template"), properties: properties) }
279        var answers = request.parameters
280        for name in Self.reservedCaptureParameters { answers[name] = nil }
281        let placed = session.capture(
282            request.parameters["text"] ?? "", templateKey: request.value("template"), templates: templates(), workspace: workspace, clock: clock,
283            clipboard: clipboard(), userName: userName, answers: answers, properties: properties
284        )
285        switch placed {
286        case .failure(let error): return .reply(.failure(.captureFailed, error.message))
287        case .success(let placed): return .reply(captured(placed.template, path: placed.path))
288        }
289    }
290
291    /// The reply to a capture filed from the sheet or without it.
292    public func captured(_ template: CaptureTemplate, path: String) -> XCallbackReply {
293        .success(["template": template.key, "file": relative(path)])
294    }
295
296    // MARK: - Open
297
298    private func open(_ request: XCallbackRequest) -> Step {
299        switch target(request) {
300        case .failed(let reply): return .reply(reply)
301        case .none: return .reply(.failure(.missingParameter, "Give file or id"))
302        case .found(let path, let offset): return .open(path: path, offset: offset, reply: .success(["file": relative(path)]))
303        }
304    }
305
306    /// The heading with `id`, or the file `file` (relative to a folder, or absolute inside one)
307    /// and in it the first heading titled `heading`.
308    func target(_ request: XCallbackRequest) -> Target {
309        if let id = request.value("id") {
310            guard let location = try? workspace.index.headings(withID: id).first else { return .failed(.failure(.notFound, "No heading with ID \"\(id)\"")) }
311            return .found(path: location.path, offset: location.start)
312        }
313        guard let file = request.value("file") else { return .none }
314        guard let path = resolve(file) else { return .failed(.failure(.notFound, "No file \"\(file)\" in orgstar's folders")) }
315        guard let heading = request.value("heading") else { return .found(path: path, offset: 0) }
316        guard let text = session.text(of: path),
317              let found = DocumentModel(tree: OrgParser.parse(text)).headings.first(where: { $0.title == heading }) else {
318            return .failed(.failure(.notFound, "No heading \"\(heading)\" in \(file)"))
319        }
320        return .found(path: path, offset: found.headingRange.lowerBound)
321    }
322
323    enum Target: Equatable {
324        case found(path: String, offset: Int)
325        /// The request names no entry.
326        case none
327        case failed(XCallbackReply)
328    }
329
330    /// A path relative to one of the folders, the first that has it, or an absolute path inside
331    /// one; nil for anything else.
332    func resolve(_ file: String) -> String? {
333        let roots = workspace.rootPaths
334        if file.hasPrefix("/") || file.hasPrefix("~") {
335            let path = (OrgPaths.expandingTilde(file) as NSString).standardizingPath
336            return roots.contains(where: { path.hasPrefix($0.hasSuffix("/") ? $0 : $0 + "/") }) && exists(path) ? path : nil
337        }
338        for root in roots {
339            let path = ((root as NSString).appendingPathComponent(file) as NSString).standardizingPath
340            if path.hasPrefix(root.hasSuffix("/") ? root : root + "/"), exists(path) { return path }
341        }
342        return nil
343    }
344
345    private func exists(_ path: String) -> Bool {
346        session.isOpen(path) || FileManager.default.fileExists(atPath: path)
347    }
348
349    /// `path` relative to the first folder holding it, or as it is.
350    func relative(_ path: String) -> String {
351        // `/tmp` and `/private/tmp` are one folder.
352        let resolved = URL(fileURLWithPath: path).resolvingSymlinksInPath().path
353        for root in workspace.rootPaths {
354            for (path, root) in [(path, root), (resolved, URL(fileURLWithPath: root).resolvingSymlinksInPath().path)] {
355                let prefix = root.hasSuffix("/") ? root : root + "/"
356                if path.hasPrefix(prefix) { return String(path.dropFirst(prefix.count)) }
357            }
358        }
359        return path
360    }
361
362    // MARK: - Agenda
363
364    /// One agenda line as the `result` JSON gives it.
365    struct Entry: Encodable, Equatable {
366        var section: String?
367        var date: String?
368        var time: String?
369        var end: String?
370        var kind: String?
371        var status: String
372        var todo: String?
373        var priority: String?
374        var title: String
375        var tags: [String]?
376        var category: String
377        var file: String?
378    }
379
380    private func agenda(_ request: XCallbackRequest) async -> XCallbackReply {
381        let name = request.value("view") ?? AgendaViewLoader.builtIn[0].name
382        let views = views()
383        guard let view = views.first(where: { $0.name == name }) ?? views.first(where: { $0.name.lowercased() == name.lowercased() }) else {
384            return .failure(.notFound, "No agenda view \"\(name)\"")
385        }
386        var limit = Self.defaultLimit
387        if let given = request.value("limit") {
388            guard let number = Int(given), number > 0 else { return .failure(.invalidParameter, "limit must be a number above 0") }
389            limit = min(number, Self.maximumLimit)
390        }
391        let model = AgendaModel(workspace: workspace)
392        model.viewSettings = AgendaViewLoader.settings(views)
393        model.mode = view.mode
394        Self.configure(model)
395        await model.refresh(open: session.openTexts, now: now(), calendar: calendar)
396        let entries = entries(model)
397        let kept = Array(entries.prefix(limit))
398        let encoder = JSONEncoder()
399        encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
400        let json = (try? encoder.encode(kept)).map { String(decoding: $0, as: UTF8.self) } ?? "[]"
401        return .success(["view": view.name, "result": json, "count": String(kept.count), "total": String(entries.count)])
402    }
403
404    /// The agenda settings of the app's preferences.
405    static func configure(_ model: AgendaModel) {
406        model.span = OrgPreferences.agendaSpan()
407        model.startOffset = OrgPreferences.agendaStartOffset()
408        model.startOnWeekday = OrgPreferences.agendaStartOnWeekday()
409        model.includeSubfolders = OrgPreferences.agendaSubfolders()
410        model.excludeArchives = OrgPreferences.agendaExcludeArchives()
411        model.hiddenFolders = HiddenFolders.shared.all
412        model.agendaFiles = OrgPreferences.agendaFiles()
413        model.options = OrgPreferences.agendaOptions(model.options)
414    }
415
416    /// The view's lines, in order: each day's overdue entries and then its rows, or the list.
417    func entries(_ model: AgendaModel) -> [Entry] {
418        Self.entries(model, calendar: calendar, relative: relative)
419    }
420
421    /// `entries(_:)` with files named by `relative`.
422    static func entries(_ model: AgendaModel, calendar: Calendar, relative: (String) -> String) -> [Entry] {
423        let today = model.today
424        func make(_ results: [(header: String?, days: [AgendaDay], list: [AgendaItem])]) -> [Entry] {
425            results.flatMap { result -> [Entry] in
426                let days = AgendaRows.groups(result.days, today: today, calendar: calendar).flatMap { group in
427                    (group.overdue + group.rows).map { Self.line($0, day: group.day, section: result.header, relative: relative) }
428                }
429                let list = result.list.compactMap { AgendaRow(item: $0, day: today, today: today) }.map { Self.line($0, day: nil, section: result.header, relative: relative) }
430                return days + list
431            }
432        }
433        if case .blocks = model.mode {
434            return make(model.blocks.map { ($0.header, $0.days, $0.list) })
435        }
436        return make([(nil, model.days, model.list)])
437    }
438
439    private static func line(_ row: AgendaRow, day: Int?, section: String?, relative: (String) -> String) -> Entry {
440        func date(_ day: Int) -> String {
441            let d = Days.date(day)
442            return String(format: "%04d-%02d-%02d", d.year, d.month, d.day)
443        }
444        func time(_ hhmm: Int?) -> String? { hhmm.map { String(format: "%02d:%02d", $0 / 100, $0 % 100) } }
445        return Entry(
446            section: section, date: day.map(date), time: time(row.start), end: time(row.end), kind: row.icon?.rawValue, status: row.status.rawValue,
447            todo: row.todo, priority: row.priority, title: row.title, tags: row.tags.isEmpty ? nil : row.tags, category: row.category,
448            file: row.item?.path.map(relative)
449        )
450    }
451
452    // MARK: - Clock
453
454    private func clockIn(_ request: XCallbackRequest, ask: @escaping ClockModel.Ask) async -> XCallbackReply {
455        let target: ClockModel.Target
456        switch self.target(request) {
457        case .failed(let reply): return reply
458        case .found(let path, let offset): target = .entry(path: path, offset: offset)
459        case .none: target = .last
460        }
461        let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
462        let outcome = await clock.clockIn(session, target: target, paths: paths, ask: ask, now: now)
463        if let running = clock.running {
464            if case .entry(let path, _) = target, running.path != path {
465                return .failure(.clockFailed, outcome.messages.last ?? "Can't clock in there")
466            }
467            return .success(clockStatus())
468        }
469        return .failure(.clockFailed, outcome.messages.last ?? "Can't clock in there")
470    }
471
472    private func clockOut() -> XCallbackReply {
473        guard let running = clock.running else { return .failure(.noClock, "No active clock") }
474        let stopped = now()
475        let message = clock.clockOut(session, now: stopped)
476        guard clock.running == nil else { return .failure(.clockFailed, message) }
477        return .success([
478            "heading": running.heading, "file": relative(running.path),
479            "minutes": String(max(0, Int(stopped.timeIntervalSince(running.startedAt) / 60))),
480        ])
481    }
482
483    func clockStatus() -> [String: String] {
484        guard let running = clock.running else { return ["running": "false"] }
485        return [
486            "running": "true", "heading": running.heading, "file": relative(running.path),
487            "started": ISO8601DateFormatter().string(from: running.startedAt),
488            "minutes": String(max(0, Int(now().timeIntervalSince(running.startedAt) / 60))),
489        ]
490    }
491}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form