Sources/OrgApp/XCallback.swift
476 lines · 22350 bytes
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 var context = CaptureContext(initial: text)
264 context.linkProperties = Self.properties(request)
265 return Capture.questions(template.template, context: context).contains { question in
266 if case .clipboard = question.kind { return false }
267 return request.parameters[question.prompt] == nil
268 }
269 }
270
271 private func capture(_ request: XCallbackRequest, sheet: Bool) -> Step {
272 let properties = Self.properties(request)
273 if sheet { return .capture(template: request.value("template"), properties: properties) }
274 var answers = request.parameters
275 for name in Self.reservedCaptureParameters { answers[name] = nil }
276 let placed = session.capture(
277 request.parameters["text"] ?? "", templateKey: request.value("template"), templates: templates(), workspace: workspace, clock: clock,
278 clipboard: clipboard(), userName: userName, answers: answers, properties: properties
279 )
280 switch placed {
281 case .failure(let error): return .reply(.failure(.captureFailed, error.message))
282 case .success(let placed): return .reply(captured(placed.template, path: placed.path))
283 }
284 }
285
286 /// The reply to a capture filed from the sheet or without it.
287 public func captured(_ template: CaptureTemplate, path: String) -> XCallbackReply {
288 .success(["template": template.key, "file": relative(path)])
289 }
290
291 // MARK: - Open
292
293 private func open(_ request: XCallbackRequest) -> Step {
294 switch target(request) {
295 case .failed(let reply): return .reply(reply)
296 case .none: return .reply(.failure(.missingParameter, "Give file or id"))
297 case .found(let path, let offset): return .open(path: path, offset: offset, reply: .success(["file": relative(path)]))
298 }
299 }
300
301 /// The heading with `id`, or the file `file` (relative to a folder, or absolute inside one)
302 /// and in it the first heading titled `heading`.
303 func target(_ request: XCallbackRequest) -> Target {
304 if let id = request.value("id") {
305 guard let location = try? workspace.index.headings(withID: id).first else { return .failed(.failure(.notFound, "No heading with ID \"\(id)\"")) }
306 return .found(path: location.path, offset: location.start)
307 }
308 guard let file = request.value("file") else { return .none }
309 guard let path = resolve(file) else { return .failed(.failure(.notFound, "No file \"\(file)\" in orgstar's folders")) }
310 guard let heading = request.value("heading") else { return .found(path: path, offset: 0) }
311 guard let text = session.text(of: path),
312 let found = DocumentModel(tree: OrgParser.parse(text)).headings.first(where: { $0.title == heading }) else {
313 return .failed(.failure(.notFound, "No heading \"\(heading)\" in \(file)"))
314 }
315 return .found(path: path, offset: found.headingRange.lowerBound)
316 }
317
318 enum Target: Equatable {
319 case found(path: String, offset: Int)
320 /// The request names no entry.
321 case none
322 case failed(XCallbackReply)
323 }
324
325 /// A path relative to one of the folders, the first that has it, or an absolute path inside
326 /// one; nil for anything else.
327 func resolve(_ file: String) -> String? {
328 let roots = workspace.rootPaths
329 if file.hasPrefix("/") || file.hasPrefix("~") {
330 let path = (OrgPaths.expandingTilde(file) as NSString).standardizingPath
331 return roots.contains(where: { path.hasPrefix($0.hasSuffix("/") ? $0 : $0 + "/") }) && exists(path) ? path : nil
332 }
333 for root in roots {
334 let path = ((root as NSString).appendingPathComponent(file) as NSString).standardizingPath
335 if path.hasPrefix(root.hasSuffix("/") ? root : root + "/"), exists(path) { return path }
336 }
337 return nil
338 }
339
340 private func exists(_ path: String) -> Bool {
341 session.isOpen(path) || FileManager.default.fileExists(atPath: path)
342 }
343
344 /// `path` relative to the first folder holding it, or as it is.
345 func relative(_ path: String) -> String {
346 // `/tmp` and `/private/tmp` are one folder.
347 let resolved = URL(fileURLWithPath: path).resolvingSymlinksInPath().path
348 for root in workspace.rootPaths {
349 for (path, root) in [(path, root), (resolved, URL(fileURLWithPath: root).resolvingSymlinksInPath().path)] {
350 let prefix = root.hasSuffix("/") ? root : root + "/"
351 if path.hasPrefix(prefix) { return String(path.dropFirst(prefix.count)) }
352 }
353 }
354 return path
355 }
356
357 // MARK: - Agenda
358
359 /// One agenda line as the `result` JSON gives it.
360 struct Entry: Encodable, Equatable {
361 var section: String?
362 var date: String?
363 var time: String?
364 var end: String?
365 var kind: String?
366 var status: String
367 var todo: String?
368 var priority: String?
369 var title: String
370 var tags: [String]?
371 var category: String
372 var file: String?
373 }
374
375 private func agenda(_ request: XCallbackRequest) async -> XCallbackReply {
376 let name = request.value("view") ?? AgendaViewLoader.builtIn[0].name
377 let views = views()
378 guard let view = views.first(where: { $0.name == name }) ?? views.first(where: { $0.name.lowercased() == name.lowercased() }) else {
379 return .failure(.notFound, "No agenda view \"\(name)\"")
380 }
381 var limit = Self.defaultLimit
382 if let given = request.value("limit") {
383 guard let number = Int(given), number > 0 else { return .failure(.invalidParameter, "limit must be a number above 0") }
384 limit = min(number, Self.maximumLimit)
385 }
386 let model = AgendaModel(workspace: workspace)
387 model.viewSettings = AgendaViewLoader.settings(views)
388 model.mode = view.mode
389 model.span = OrgPreferences.agendaSpan()
390 model.startOffset = OrgPreferences.agendaStartOffset()
391 model.startOnWeekday = OrgPreferences.agendaStartOnWeekday()
392 model.includeSubfolders = OrgPreferences.agendaSubfolders()
393 model.excludeArchives = OrgPreferences.agendaExcludeArchives()
394 model.hiddenFolders = HiddenFolders.shared.all
395 model.agendaFiles = OrgPreferences.agendaFiles()
396 model.options = OrgPreferences.agendaOptions(model.options)
397 await model.refresh(open: session.openTexts, now: now(), calendar: calendar)
398 let entries = entries(model)
399 let kept = Array(entries.prefix(limit))
400 let encoder = JSONEncoder()
401 encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
402 let json = (try? encoder.encode(kept)).map { String(decoding: $0, as: UTF8.self) } ?? "[]"
403 return .success(["view": view.name, "result": json, "count": String(kept.count), "total": String(entries.count)])
404 }
405
406 /// The view's lines, in order: each day's overdue entries and then its rows, or the list.
407 func entries(_ model: AgendaModel) -> [Entry] {
408 let today = model.today
409 func make(_ results: [(header: String?, days: [AgendaDay], list: [AgendaItem])]) -> [Entry] {
410 results.flatMap { result -> [Entry] in
411 let days = AgendaRows.groups(result.days, today: today, calendar: calendar).flatMap { group in
412 (group.overdue + group.rows).map { line($0, day: group.day, section: result.header) }
413 }
414 let list = result.list.compactMap { AgendaRow(item: $0, day: today, today: today) }.map { line($0, day: nil, section: result.header) }
415 return days + list
416 }
417 }
418 if case .blocks = model.mode {
419 return make(model.blocks.map { ($0.header, $0.days, $0.list) })
420 }
421 return make([(nil, model.days, model.list)])
422 }
423
424 private func line(_ row: AgendaRow, day: Int?, section: String?) -> Entry {
425 func date(_ day: Int) -> String {
426 let d = Days.date(day)
427 return String(format: "%04d-%02d-%02d", d.year, d.month, d.day)
428 }
429 func time(_ hhmm: Int?) -> String? { hhmm.map { String(format: "%02d:%02d", $0 / 100, $0 % 100) } }
430 return Entry(
431 section: section, date: day.map(date), time: time(row.start), end: time(row.end), kind: row.icon?.rawValue, status: row.status.rawValue,
432 todo: row.todo, priority: row.priority, title: row.title, tags: row.tags.isEmpty ? nil : row.tags, category: row.category,
433 file: row.item?.path.map(relative)
434 )
435 }
436
437 // MARK: - Clock
438
439 private func clockIn(_ request: XCallbackRequest, ask: @escaping ClockModel.Ask) async -> XCallbackReply {
440 let target: ClockModel.Target
441 switch self.target(request) {
442 case .failed(let reply): return reply
443 case .found(let path, let offset): target = .entry(path: path, offset: offset)
444 case .none: target = .last
445 }
446 let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
447 let outcome = await clock.clockIn(session, target: target, paths: paths, ask: ask, now: now)
448 if let running = clock.running {
449 if case .entry(let path, _) = target, running.path != path {
450 return .failure(.clockFailed, outcome.messages.last ?? "Can't clock in there")
451 }
452 return .success(clockStatus())
453 }
454 return .failure(.clockFailed, outcome.messages.last ?? "Can't clock in there")
455 }
456
457 private func clockOut() -> XCallbackReply {
458 guard let running = clock.running else { return .failure(.noClock, "No active clock") }
459 let stopped = now()
460 let message = clock.clockOut(session, now: stopped)
461 guard clock.running == nil else { return .failure(.clockFailed, message) }
462 return .success([
463 "heading": running.heading, "file": relative(running.path),
464 "minutes": String(max(0, Int(stopped.timeIntervalSince(running.startedAt) / 60))),
465 ])
466 }
467
468 func clockStatus() -> [String: String] {
469 guard let running = clock.running else { return ["running": "false"] }
470 return [
471 "running": "true", "heading": running.heading, "file": relative(running.path),
472 "started": ISO8601DateFormatter().string(from: running.startedAt),
473 "minutes": String(max(0, Int(now().timeIntervalSince(running.startedAt) / 60))),
474 ]
475 }
476}