← All repositories

reportage

A life-logging app for iPhone

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


Reportage/Services/Prompts/PromptSettings.swift (2538B)

1import Foundation
2
3/// When random prompts come: how many a day, within which hours, and how far
4/// apart.
5///
6/// Kept in `UserDefaults` on each device and never synced: only the iPhone
7/// that schedules prompts uses it.
8struct PromptSettings: Codable, Equatable, Sendable {
9    /// Prompts are off until the user turns them on, which is when
10    /// notifications (and the upgrade to 'Always' location) are asked for.
11    var isEnabled = false
12    var perDay = 4
13    /// The waking window, every day or on weekdays only.
14    var window = WakingWindow(start: 9 * 60, end: 22 * 60)
15    /// The waking window on weekends, if it differs.
16    var weekendWindow: WakingWindow?
17    /// The least time between two prompts on the same day, in minutes.
18    var minimumGap = 30
19    /// How long Snooze puts a prompt off, in minutes.
20    var snooze = 15
21
22    /// The waking window on `day`.
23    func window(on day: Date, calendar: Calendar) -> WakingWindow {
24        if let weekendWindow, calendar.isDateInWeekend(day) {
25            return weekendWindow
26        }
27        return window
28    }
29}
30
31/// The hours prompts may come in, as minutes after midnight. An end at or
32/// before the start is on the next day, so a window can run past midnight.
33struct WakingWindow: Codable, Equatable, Sendable {
34    var start: Int
35    var end: Int
36}
37
38extension PromptSettings {
39    private static let key = "promptSettings"
40
41    /// The saved settings, or the defaults if there are none.
42    static func load(from defaults: UserDefaults = .standard) -> PromptSettings {
43        guard let data = defaults.data(forKey: key),
44            let settings = try? JSONDecoder().decode(PromptSettings.self, from: data)
45        else { return PromptSettings() }
46        return settings
47    }
48
49    func save(to defaults: UserDefaults = .standard) {
50        guard let data = try? JSONEncoder().encode(self) else { return }
51        defaults.set(data, forKey: Self.key)
52    }
53}
54
55/// A random number made once per install, which seeds each day's prompt
56/// times. Together with the date it makes the times unpredictable but the
57/// same every time they're worked out.
58enum PromptSecret {
59    private static let key = "promptSecret"
60
61    static func value(in defaults: UserDefaults = .standard) -> UInt64 {
62        if let stored = defaults.string(forKey: key), let value = UInt64(stored, radix: 16) {
63            return value
64        }
65        let value = UInt64.random(in: .min ... .max)
66        defaults.set(String(value, radix: 16), forKey: key)
67        return value
68    }
69}