Ariver
2026-06-28 0badb998147135c75187a0c48f926b665af734c5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
import Foundation
import StoreKit
import SwiftUI
 
enum ProFeature: String, CaseIterable {
    case premiumThemes
    case layoutImport
    case layoutExport
    case unlimitedNotes
    case persistentAppSorting
 
    var titleKey: String {
        switch self {
        case .premiumThemes:
            return "pro.feature.themes"
        case .layoutImport:
            return "pro.feature.import"
        case .layoutExport:
            return "pro.feature.export"
        case .unlimitedNotes:
            return "pro.feature.notes"
        case .persistentAppSorting:
            return "pro.feature.sorting"
        }
    }
 
    var benefitKey: String {
        switch self {
        case .premiumThemes:
            return "pro.feature.themes.benefit"
        case .layoutImport:
            return "pro.feature.import.benefit"
        case .layoutExport:
            return "pro.feature.export.benefit"
        case .unlimitedNotes:
            return "pro.feature.notes.benefit"
        case .persistentAppSorting:
            return "pro.feature.sorting.benefit"
        }
    }
}
 
enum ProAccessState: String, Codable, Equatable {
    case free
    case purchased
    case legacy
 
    var isUnlocked: Bool {
        self != .free
    }
}
 
enum ProOperationState: Equatable {
    case idle
    case loading
    case purchasing
    case restoring
    case pending
    case cancelled
    case restoreNotFound
    case failed(messageKey: String)
 
    var isBusy: Bool {
        switch self {
        case .loading, .purchasing, .restoring:
            return true
        case .idle, .pending, .cancelled, .restoreNotFound, .failed:
            return false
        }
    }
}
 
enum ProEntitlementError: Error, Equatable {
    case featureLocked(ProFeature)
    case noteQuotaExceeded(ProNoteQuotaStatus)
 
    var feature: ProFeature? {
        switch self {
        case .featureLocked(let feature):
            return feature
        case .noteQuotaExceeded:
            return .unlimitedNotes
        }
    }
 
    var noteQuotaStatus: ProNoteQuotaStatus? {
        switch self {
        case .featureLocked:
            return nil
        case .noteQuotaExceeded(let status):
            return status
        }
    }
}
 
struct ProThemePreviewState: Equatable {
    let theme: AppGridTheme
    let startedAt: Date
    let endsAt: Date
 
    func remainingSeconds(at date: Date = Date()) -> Int {
        max(0, Int(ceil(endsAt.timeIntervalSince(date))))
    }
}
 
struct ProNoteQuotaStatus: Equatable {
    let isUnlimited: Bool
    let used: Int
    let limit: Int
 
    var remaining: Int {
        max(0, limit - used)
    }
}
 
enum ProNoteSaveDecision: Equatable {
    case allow(ProNoteQuotaStatus)
    case blocked(ProNoteQuotaStatus)
}
 
enum ProEntitlementConfig {
    // 发布前只改这里,不允许把商品信息和边界版本散落到业务模块。
    static let lifetimeProductID = "com.taglauncher.pro.lifetime"
    static let firstFreeProVersion = "8.1.0"
    static let legacyFallbackOriginalPurchaseDateISO8601: String? = nil
 
    static let freeThemes: Set<AppGridTheme> = [.defaultLight, .deepBlue, .black]
    static let freeNoteLimit = 5
    static let defaultThemePreviewDuration: TimeInterval = 5 * 60
 
    static let qaStateEnvKey = "TAGLAUNCHER_QA_PRO_STATE"
    static let qaThemePreviewSecondsEnvKey = "TAGLAUNCHER_QA_THEME_PREVIEW_SECONDS"
 
    static var legacyFallbackOriginalPurchaseDate: Date? {
        guard let value = legacyFallbackOriginalPurchaseDateISO8601 else { return nil }
        return iso8601Formatter.date(from: value)
    }
 
    static var themePreviewDuration: TimeInterval {
        let environment = ProcessInfo.processInfo.environment
        if let raw = environment[qaThemePreviewSecondsEnvKey],
           let seconds = TimeInterval(raw),
           seconds > 0 {
            return seconds
        }
        return defaultThemePreviewDuration
    }
 
    private static let iso8601Formatter: ISO8601DateFormatter = {
        let formatter = ISO8601DateFormatter()
        formatter.formatOptions = [.withInternetDateTime]
        return formatter
    }()
}
 
private struct ProEntitlementCache: Codable {
    var accessState: ProAccessState
    var updatedAt: Date
    var originalAppVersion: String?
    var originalPurchaseDate: Date?
}
 
private struct ProEntitlementSnapshot {
    var accessState: ProAccessState = .free
    var previewThemeID: String? = nil
}
 
private enum ProEntitlementSnapshotStore {
    private static let lock = NSLock()
    private static var snapshot = ProEntitlementSnapshot()
 
    static func update(_ block: (inout ProEntitlementSnapshot) -> Void) {
        lock.lock()
        block(&snapshot)
        lock.unlock()
    }
 
    static func read() -> ProEntitlementSnapshot {
        lock.lock()
        let value = snapshot
        lock.unlock()
        return value
    }
}
 
enum ProEntitlementPolicy {
    static func accessState() -> ProAccessState {
        ProEntitlementSnapshotStore.read().accessState
    }
 
    static func lockedErrorIfNeeded(for feature: ProFeature) -> ProEntitlementError? {
        isUnlocked(feature) ? nil : .featureLocked(feature)
    }
 
    static func requireUnlocked(_ feature: ProFeature) throws {
        if let error = lockedErrorIfNeeded(for: feature) {
            throw error
        }
    }
 
    static func isUnlocked(_ feature: ProFeature) -> Bool {
        switch feature {
        case .premiumThemes, .layoutImport, .layoutExport, .unlimitedNotes, .persistentAppSorting:
            return accessState().isUnlocked
        }
    }
 
    static func canUseTheme(_ theme: AppGridTheme) -> Bool {
        ProEntitlementConfig.freeThemes.contains(theme) || isUnlocked(.premiumThemes)
    }
 
    static func effectiveTheme(for storedTheme: AppGridTheme) -> AppGridTheme {
        if let previewID = ProEntitlementSnapshotStore.read().previewThemeID,
           let previewTheme = AppGridTheme(rawValue: previewID) {
            return previewTheme
        }
        guard canUseTheme(storedTheme) else {
            return .defaultLight
        }
        return storedTheme
    }
 
    static func noteQuotaStatus(in store: TagDatabase.Store? = nil) -> ProNoteQuotaStatus {
        guard !isUnlocked(.unlimitedNotes) else {
            return ProNoteQuotaStatus(isUnlimited: true, used: 0, limit: Int.max)
        }
        let used = TagDatabase.manualNonEmptyNoteCount(in: store)
        return ProNoteQuotaStatus(
            isUnlimited: false,
            used: used,
            limit: ProEntitlementConfig.freeNoteLimit
        )
    }
 
    static func noteSaveDecision(note: String, for path: String, in store: TagDatabase.Store? = nil) -> ProNoteSaveDecision {
        let trimmed = note.trimmingCharacters(in: .whitespacesAndNewlines)
        let effectiveStore = store ?? TagDatabase.load()
        let currentQuota = noteQuotaStatus(in: effectiveStore)
        guard !currentQuota.isUnlimited else { return .allow(currentQuota) }
 
        let manualNotePaths = TagDatabase.manualNonEmptyNotePaths(in: effectiveStore)
        let hasExistingManualNote = manualNotePaths.contains(path)
        let willPersistManualNote = !trimmed.isEmpty
        let limit = ProEntitlementConfig.freeNoteLimit
        let resultingUsed: Int
 
        switch (hasExistingManualNote, willPersistManualNote) {
        case (true, true):
            resultingUsed = manualNotePaths.count
        case (true, false):
            resultingUsed = max(0, manualNotePaths.count - 1)
        case (false, true):
            guard manualNotePaths.count < limit else {
                return .blocked(currentQuota)
            }
            resultingUsed = manualNotePaths.count + 1
        case (false, false):
            resultingUsed = manualNotePaths.count
        }
 
        return .allow(
            ProNoteQuotaStatus(
                isUnlimited: false,
                used: resultingUsed,
                limit: limit
            )
        )
    }
 
    static func requireNoteSave(note: String, for path: String, in store: TagDatabase.Store? = nil) throws -> ProNoteQuotaStatus {
        switch noteSaveDecision(note: note, for: path, in: store) {
        case .allow(let status):
            return status
        case .blocked(let status):
            throw ProEntitlementError.noteQuotaExceeded(status)
        }
    }
}
 
@MainActor
final class ProEntitlementCenter: ObservableObject {
    static let shared = ProEntitlementCenter()
 
    @Published private(set) var accessState: ProAccessState = .free
    @Published private(set) var operationState: ProOperationState = .idle
    @Published private(set) var priceDisplayText: String? = nil
    @Published private(set) var themePreviewState: ProThemePreviewState? = nil
 
    private var hasStarted = false
    private var cachedProduct: Product?
    private var updateTask: Task<Void, Never>?
    private var themePreviewTask: Task<Void, Never>?
 
    private init() {}
 
    deinit {
        updateTask?.cancel()
        themePreviewTask?.cancel()
    }
 
    var isUnlocked: Bool {
        accessState.isUnlocked
    }
 
    var isPreviewingTheme: Bool {
        themePreviewState != nil
    }
 
    var compactStatusTextKey: String {
        if themePreviewState != nil {
            return "pro.theme.preview.status"
        }
        switch accessState {
        case .free:
            return "pro.status.free"
        case .purchased:
            return "pro.status.unlocked"
        case .legacy:
            return "pro.status.legacyUnlocked"
        }
    }
 
    func start() {
        guard !hasStarted else { return }
        hasStarted = true
 
        if let override = qaOverrideAccessState {
            applyAccessState(override, persistCache: false)
            operationState = .idle
            return
        }
 
        if let cached = loadCache() {
            applyAccessState(cached.accessState, persistCache: false)
        }
 
        operationState = .loading
        startTransactionUpdates()
 
        Task {
            _ = try? await loadProductIfNeeded()
            await refreshEntitlements()
        }
    }
 
    func purchasePro() {
        Task {
            operationState = .purchasing
            do {
                guard let product = try await loadProductIfNeeded() else {
                    operationState = .failed(messageKey: "pro.purchase.unavailable")
                    return
                }
                let result = try await product.purchase()
                switch result {
                case .success(let verification):
                    switch verification {
                    case .verified(let transaction):
                        await transaction.finish()
                        await refreshEntitlements()
                        operationState = .idle
                    case .unverified:
                        operationState = .failed(messageKey: "pro.purchase.verificationFailed")
                    }
                case .pending:
                    operationState = .pending
                case .userCancelled:
                    operationState = .cancelled
                @unknown default:
                    operationState = .failed(messageKey: "pro.purchase.failed")
                }
            } catch {
                operationState = .failed(messageKey: "pro.purchase.failed")
            }
        }
    }
 
    func restorePurchases() {
        Task {
            operationState = .restoring
            do {
                try await AppStore.sync()
                await refreshEntitlements()
                if accessState.isUnlocked {
                    operationState = .idle
                } else {
                    operationState = .restoreNotFound
                }
            } catch {
                operationState = .failed(messageKey: "pro.restore.failed")
            }
        }
    }
 
    func clearTransientOperationState() {
        switch operationState {
        case .pending, .cancelled, .restoreNotFound, .failed:
            operationState = .idle
        case .idle, .loading, .purchasing, .restoring:
            break
        }
    }
 
    func startThemePreview(for theme: AppGridTheme) {
        guard !ProEntitlementConfig.freeThemes.contains(theme) else { return }
        guard !accessState.isUnlocked else { return }
 
        themePreviewTask?.cancel()
 
        let preview = ProThemePreviewState(
            theme: theme,
            startedAt: Date(),
            endsAt: Date().addingTimeInterval(ProEntitlementConfig.themePreviewDuration)
        )
        applyThemePreview(preview)
 
        themePreviewTask = Task { [weak self] in
            let duration = max(1, ProEntitlementConfig.themePreviewDuration)
            try? await Task.sleep(nanoseconds: UInt64(duration * 1_000_000_000))
            guard !Task.isCancelled else { return }
            self?.stopThemePreview()
        }
    }
 
    func stopThemePreview() {
        themePreviewTask?.cancel()
        themePreviewTask = nil
        applyThemePreview(nil)
    }
 
    private func startTransactionUpdates() {
        guard updateTask == nil else { return }
        updateTask = Task { [weak self] in
            for await update in Transaction.updates {
                guard let self else { return }
                if case .verified(let transaction) = update,
                   transaction.productID == ProEntitlementConfig.lifetimeProductID {
                    await transaction.finish()
                }
                await self.refreshEntitlements()
            }
        }
    }
 
    @discardableResult
    private func loadProductIfNeeded() async throws -> Product? {
        if let cachedProduct {
            return cachedProduct
        }
        let products = try await Product.products(for: [ProEntitlementConfig.lifetimeProductID])
        let product = products.first
        cachedProduct = product
        priceDisplayText = product?.displayPrice
        return product
    }
 
    private func refreshEntitlements() async {
        if let override = qaOverrideAccessState {
            applyAccessState(override, persistCache: false)
            operationState = .idle
            return
        }
 
        let purchased = await hasPurchasedLifetimePro()
        let appTransaction = await verifiedAppTransaction()
        let legacy = appTransaction.map(isLegacyPaidUser(appTransaction:)) ?? false
 
        let state: ProAccessState
        if purchased {
            state = .purchased
        } else if legacy {
            state = .legacy
        } else {
            state = .free
        }
 
        applyAccessState(
            state,
            persistCache: true,
            originalAppVersion: appTransaction?.originalAppVersion,
            originalPurchaseDate: appTransaction?.originalPurchaseDate
        )
 
        if case .loading = operationState {
            operationState = .idle
        }
    }
 
    private func hasPurchasedLifetimePro() async -> Bool {
        for await verification in Transaction.currentEntitlements {
            switch verification {
            case .verified(let transaction):
                if transaction.productID == ProEntitlementConfig.lifetimeProductID,
                   transaction.revocationDate == nil {
                    return true
                }
            case .unverified:
                continue
            }
        }
        return false
    }
 
    private func verifiedAppTransaction() async -> AppTransaction? {
        do {
            let verification = try await AppTransaction.shared
            switch verification {
            case .verified(let transaction):
                if #available(macOS 13.0, *) {
                    if transaction.revocationDate != nil {
                        return nil
                    }
                }
                return transaction
            case .unverified:
                return nil
            }
        } catch {
            return nil
        }
    }
 
    private func isLegacyPaidUser(appTransaction: AppTransaction) -> Bool {
        if let current = SemanticVersion(appTransaction.originalAppVersion),
           let cutoff = SemanticVersion(ProEntitlementConfig.firstFreeProVersion) {
            return current < cutoff
        }
 
        guard let fallbackDate = ProEntitlementConfig.legacyFallbackOriginalPurchaseDate else {
            return false
        }
        return appTransaction.originalPurchaseDate < fallbackDate
    }
 
    private func applyAccessState(
        _ state: ProAccessState,
        persistCache: Bool,
        originalAppVersion: String? = nil,
        originalPurchaseDate: Date? = nil
    ) {
        accessState = state
        ProEntitlementSnapshotStore.update { snapshot in
            snapshot.accessState = state
        }
 
        if persistCache {
            writeCache(
                ProEntitlementCache(
                    accessState: state,
                    updatedAt: Date(),
                    originalAppVersion: originalAppVersion,
                    originalPurchaseDate: originalPurchaseDate
                )
            )
        }
    }
 
    private func applyThemePreview(_ preview: ProThemePreviewState?) {
        themePreviewState = preview
        ProEntitlementSnapshotStore.update { snapshot in
            snapshot.previewThemeID = preview?.theme.rawValue
        }
    }
 
    private var cacheURL: URL {
        AppIdentity.applicationSupportDirectory
            .appendingPathComponent("pro-entitlement-cache.json")
    }
 
    private func loadCache() -> ProEntitlementCache? {
        guard let data = try? Data(contentsOf: cacheURL) else { return nil }
        return try? JSONDecoder().decode(ProEntitlementCache.self, from: data)
    }
 
    private func writeCache(_ cache: ProEntitlementCache) {
        try? FileManager.default.createDirectory(
            at: AppIdentity.applicationSupportDirectory,
            withIntermediateDirectories: true,
            attributes: nil
        )
        guard let data = try? JSONEncoder().encode(cache) else { return }
        try? data.write(to: cacheURL, options: .atomic)
    }
 
    private var qaOverrideAccessState: ProAccessState? {
        guard let raw = ProcessInfo.processInfo.environment[ProEntitlementConfig.qaStateEnvKey] else {
            return nil
        }
        switch raw {
        case "free":
            return .free
        case "pro":
            return .purchased
        case "legacyPro":
            return .legacy
        default:
            return nil
        }
    }
}
 
private struct SemanticVersion: Comparable {
    private let components: [Int]
 
    init?(_ raw: String) {
        let values = raw
            .split(separator: ".")
            .compactMap { Int($0.trimmingCharacters(in: .whitespacesAndNewlines)) }
        guard !values.isEmpty else { return nil }
        components = values
    }
 
    static func < (lhs: SemanticVersion, rhs: SemanticVersion) -> Bool {
        let maxCount = max(lhs.components.count, rhs.components.count)
        for index in 0..<maxCount {
            let left = index < lhs.components.count ? lhs.components[index] : 0
            let right = index < rhs.components.count ? rhs.components[index] : 0
            if left != right {
                return left < right
            }
        }
        return false
    }
}
 
extension TagDatabase {
    static func manualNonEmptyNotePaths(in store: Store) -> Set<String> {
        Set(
            store.appNotes.compactMap { path, note in
                let trimmed = note.trimmingCharacters(in: .whitespacesAndNewlines)
                guard !trimmed.isEmpty,
                      store.appNoteMetadata[path]?.origin == .manual
                else { return nil }
                return path
            }
        )
    }
 
    static func manualNonEmptyNoteCount(in store: Store? = nil) -> Int {
        let effectiveStore = store ?? load()
        return manualNonEmptyNotePaths(in: effectiveStore).count
    }
}