Sources/OrgApp/ProAccess.swift

143 lines · 5634 bytes

  1import Foundation
  2import Observation
  3
  4/// Features that need orgstar+.
  5public enum ProFeature: String, CaseIterable, Sendable, Identifiable {
  6    case babel, export, encryption, roam
  7    case widgets, watch, liveActivity, calendar, shortcuts
  8
  9    public var id: String { rawValue }
 10
 11    public var title: String {
 12        switch self {
 13        case .babel: "Run and tangle source blocks"
 14        case .export: "PDF, Word and other export, and publishing"
 15        case .encryption: "Encrypted entries"
 16        case .roam: "Org-roam nodes and backlinks"
 17        case .widgets: "Widgets"
 18        case .watch: "Apple Watch app"
 19        case .liveActivity: "Clock Live Activity"
 20        case .calendar: "Calendar and Reminders"
 21        case .shortcuts: "Shortcuts actions"
 22        }
 23    }
 24
 25    public var systemImage: String {
 26        switch self {
 27        case .babel: "play.rectangle"
 28        case .export: "square.and.arrow.up"
 29        case .encryption: "lock"
 30        case .roam: "point.3.connected.trianglepath.dotted"
 31        case .widgets: "square.grid.2x2"
 32        case .watch: "applewatch"
 33        case .liveActivity: "timer"
 34        case .calendar: "calendar"
 35        case .shortcuts: "square.stack.3d.up"
 36        }
 37    }
 38}
 39
 40extension ProFeature {
 41    /// Export formats that stay free.
 42    static let freeExports: Set<String> = ["html", "html-open", "markdown"]
 43
 44    /// The feature an export format needs, if any.
 45    public static func required(byExport format: String) -> ProFeature? {
 46        freeExports.contains(format) ? nil : .export
 47    }
 48
 49    /// The feature an app command (`app.…`, from a key, menu or the palette) needs, if any.
 50    /// Decrypting stays free so no one is locked out of their own text.
 51    public static func required(byCommand id: String) -> ProFeature? {
 52        switch id {
 53        case "app.copy-rich-text": .export
 54        case let id where id.hasPrefix("app.export."): required(byExport: String(id.dropFirst("app.export.".count)))
 55        case let id where id.hasPrefix("app.publish"): .export
 56        case "app.crypt.encrypt-entry", "app.crypt.encrypt-entries": .encryption
 57        case let id where id.hasPrefix("app.dailies.") || id.hasPrefix("app.node."): .roam
 58        case "app.toggle-backlinks", "app.backlinks": .roam
 59        default: nil
 60        }
 61    }
 62}
 63
 64/// Why Pro is unlocked.
 65public enum ProGrant: String, Codable, Sendable {
 66    /// Installed before Pro existed.
 67    case grandfathered
 68    /// An App Store purchase or subscription.
 69    case purchase
 70    /// A Mac license key.
 71    case license
 72}
 73
 74/// Whether Pro is unlocked. The app writes it; the app group's defaults carry it to the widgets,
 75/// share extension and intents, which only read it.
 76@MainActor @Observable
 77public final class ProAccess {
 78    public static let shared = ProAccess(defaults: ProAccess.groupDefaults)
 79
 80    nonisolated static let grantKey = "pro.grant"
 81
 82    /// The app group's defaults, or the standard ones when the app isn't in the group (the Mac app).
 83    public nonisolated static var groupDefaults: UserDefaults {
 84        UserDefaults(suiteName: CaptureInbox.group) ?? .standard
 85    }
 86
 87    /// For code outside the main actor (widgets, intents): reads the stored grant.
 88    public nonisolated static var isUnlockedNow: Bool {
 89        groupDefaults.string(forKey: grantKey).flatMap(ProGrant.init(rawValue:)) != nil
 90    }
 91
 92    private let defaults: UserDefaults
 93    public private(set) var grant: ProGrant?
 94    /// The feature whose paywall should show, if any.
 95    public var paywall: ProFeature?
 96
 97    public init(defaults: UserDefaults) {
 98        self.defaults = defaults
 99        grant = defaults.string(forKey: Self.grantKey).flatMap(ProGrant.init(rawValue:))
100    }
101
102    public var isUnlocked: Bool { grant != nil }
103
104    public func set(_ grant: ProGrant?) {
105        self.grant = grant
106        defaults.set(grant?.rawValue, forKey: Self.grantKey)
107    }
108
109    /// True when `feature` may be used; otherwise shows its paywall and returns false.
110    @discardableResult
111    public func allows(_ feature: ProFeature) -> Bool {
112        if isUnlocked { return true }
113        paywall = feature
114        return false
115    }
116}
117
118/// Who installed before Pro and keeps it free.
119public enum Grandfathering {
120    /// The first iOS build (`CFBundleVersion`, the commit count) that sells Pro: one more than
121    /// main's count before Pro merged. An App Store `originalAppVersion` below it means the app was
122    /// first downloaded while it was free.
123    public static let firstPaidIOSBuild = 569
124
125    /// Whether an App Store original build number predates Pro.
126    public static func predatesPro(originalBuild: String, firstPaidBuild: Int = firstPaidIOSBuild) -> Bool {
127        guard let build = Int(originalBuild.trimmingCharacters(in: .whitespaces)) else { return false }
128        return build < firstPaidBuild
129    }
130
131    static let macDecidedKey = "pro.macGrandfatherDecided"
132
133    /// Decides once, on the first launch of a Pro build of the Mac app, whether this Mac ran an
134    /// earlier free version: Sparkle marks its first launch, and `marker` (the workspace's list of
135    /// folders) exists once folders were added. Later launches return the first answer.
136    public static func macPredatesPro(defaults: UserDefaults = .standard, marker: URL?) -> Bool {
137        if let decided = defaults.object(forKey: macDecidedKey) as? Bool { return decided }
138        let ranBefore = defaults.object(forKey: "SUHasLaunchedBefore") != nil
139            || marker.map { FileManager.default.fileExists(atPath: $0.path) } == true
140        defaults.set(ranBefore, forKey: macDecidedKey)
141        return ranBefore
142    }
143}