← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Reportage/Services/Prompts/PromptSchedule.swift (5052B)

1import Foundation
2
3/// One notification the scheduler wants pending: a prompt, or the reminder
4/// that ends the horizon.
5struct PlannedPrompt: Equatable, Sendable {
6    enum Kind: String, Sendable {
7        case prompt
8        /// Takes the place of the horizon's last prompt, so a long stretch
9        /// without opening the app ends with a nudge rather than silence.
10        case reminder
11    }
12
13    var kind: Kind
14    let date: Date
15    /// The fire time as wall-clock components, without a time zone, so the
16    /// notification fires at that local time wherever the phone is.
17    let components: DateComponents
18
19    /// Named by kind and wall-clock time, so the same plan always has the
20    /// same identifiers and rescheduling only touches what changed.
21    var identifier: String {
22        let c = components
23        return String(
24            format: "%@.%04d%02d%02d-%02d%02d%02d", kind.rawValue,
25            c.year ?? 0, c.month ?? 0, c.day ?? 0, c.hour ?? 0, c.minute ?? 0, c.second ?? 0)
26    }
27}
28
29/// Works out when prompts fire. Pure: the same settings, secret and day
30/// always give the same times.
31enum PromptSchedule {
32    /// The prompt times on `day`, in order.
33    ///
34    /// The window is split into `perDay` equal slots with one time drawn in
35    /// each, which avoids clusters and long silences while keeping each
36    /// prompt unpredictable. To keep the minimum gap, the slots share the
37    /// window less the gaps between them, and each later time is pushed on
38    /// by one gap more. A gap too large for the window shrinks to fit.
39    static func times(
40        on day: Date, settings: PromptSettings, secret: UInt64, calendar: Calendar
41    ) -> [Date] {
42        let count = settings.perDay
43        let window = settings.window(on: day, calendar: calendar)
44        guard count > 0,
45            let start = calendar.date(
46                bySettingHour: window.start / 60, minute: window.start % 60, second: 0, of: day),
47            var end = calendar.date(
48                bySettingHour: window.end / 60, minute: window.end % 60, second: 0, of: day)
49        else { return [] }
50        if end <= start {
51            end = calendar.date(byAdding: .day, value: 1, to: end) ?? end
52        }
53        let length = end.timeIntervalSince(start)
54        let gap = min(Double(settings.minimumGap * 60), length / Double(count))
55        let slot = (length - Double(count - 1) * gap) / Double(count)
56        var generator = SeededGenerator(seed: seed(for: day, secret: secret, calendar: calendar))
57        return (0..<count).map { index in
58            let offset = Double(index) * (slot + gap) + generator.nextUnit() * slot
59            return start.addingTimeInterval(offset.rounded(.down))
60        }
61    }
62
63    /// The notifications to keep pending from `now`: every prompt in the
64    /// next `days` days, up to `limit`, with the last one made a reminder.
65    /// The limit leaves room under iOS's 64 for snoozed prompts.
66    static func horizon(
67        from now: Date, settings: PromptSettings, secret: UInt64, calendar: Calendar,
68        days: Int = 7, limit: Int = 50
69    ) -> [PlannedPrompt] {
70        guard settings.isEnabled else { return [] }
71        let today = calendar.startOfDay(for: now)
72        // Yesterday too, for a window that runs past midnight.
73        let dates = (-1..<days)
74            .compactMap { calendar.date(byAdding: .day, value: $0, to: today) }
75            .flatMap { times(on: $0, settings: settings, secret: secret, calendar: calendar) }
76            .filter { $0 > now }
77            .sorted()
78            .prefix(limit)
79        var prompts = dates.map { date in
80            PlannedPrompt(
81                kind: .prompt,
82                date: date,
83                components: calendar.dateComponents(
84                    [.year, .month, .day, .hour, .minute, .second], from: date)
85            )
86        }
87        if !prompts.isEmpty {
88            prompts[prompts.count - 1].kind = .reminder
89        }
90        return prompts
91    }
92
93    /// Mixes the secret with the calendar date of `day`.
94    private static func seed(for day: Date, secret: UInt64, calendar: Calendar) -> UInt64 {
95        let c = calendar.dateComponents([.year, .month, .day], from: day)
96        let date = UInt64((c.year ?? 0) * 10_000 + (c.month ?? 0) * 100 + (c.day ?? 0))
97        return secret ^ (date &* 0x9E37_79B9_7F4A_7C15)
98    }
99}
100
101/// SplitMix64. Written out rather than using the standard library's
102/// generators and `random(in:)`, whose algorithms could change between OS
103/// versions and so move already-scheduled prompts.
104struct SeededGenerator: RandomNumberGenerator {
105    private var state: UInt64
106
107    init(seed: UInt64) {
108        state = seed
109    }
110
111    mutating func next() -> UInt64 {
112        state &+= 0x9E37_79B9_7F4A_7C15
113        var z = state
114        z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
115        z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
116        return z ^ (z >> 31)
117    }
118
119    /// A number in `0..<1`.
120    mutating func nextUnit() -> Double {
121        Double(next() >> 11) * 0x1.0p-53
122    }
123}