← All repositories

reportage

A life-logging app for iPhone

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


Reportage/Services/DemoSeed.swift (13991B)

1import Foundation
2
3/// Invented reports for screenshots and for looking at the timeline without
4/// real data. Driven solely by the `--reportage-seed-demo` launch argument,
5/// which also swaps the store for a throwaway in-memory one, so the real
6/// store is never touched. `Scripts/run-demo.sh` and
7/// `Scripts/screenshots-iphone.sh` launch the app with it.
8enum DemoSeed {
9    #if DEBUG
10    static let isActive = ProcessInfo.processInfo.arguments.contains("--reportage-seed-demo")
11    #else
12    static let isActive = false
13    #endif
14
15    /// A screen the demo opens to, for `Scripts/screenshots-marketing.sh`.
16    enum Screen: String {
17        case timeline
18        /// The afternoon's report, opened from the timeline.
19        case detail
20        case charts
21        /// A new manual report's survey.
22        case survey
23    }
24
25    /// The screen named by `--reportage-demo-screen <name>`; the timeline
26    /// without it, or outside the demo.
27    static let screen: Screen = {
28        let arguments = ProcessInfo.processInfo.arguments
29        guard isActive, let index = arguments.firstIndex(of: "--reportage-demo-screen"),
30            arguments.indices.contains(index + 1)
31        else { return .timeline }
32        return Screen(rawValue: arguments[index + 1]) ?? .timeline
33    }()
34
35    /// The report the detail screen opens: the last one seeded.
36    static let detailReportID = UUID(uuidString: "DE000000-0000-4000-8000-000000000006")!
37
38    #if DEBUG
39    /// Adds the reports, dated today and yesterday, after the default
40    /// questions have been seeded. Their answers use the default questions.
41    static func populate(_ store: ReportStore, now: Date = Date()) async throws {
42        let p = DefaultQuestions.idPrefix
43        // The moods the reports use that the defaults don't offer.
44        if var mood = try await store.allQuestions().first(where: { $0.id == p + "mood" }) {
45            mood.options += ["Not so self-assured", "Appreciative"]
46            mood.modifiedAt = now
47            try await store.save([mood])
48        }
49        let calendar = Calendar.current
50        let today = calendar.startOfDay(for: now)
51        func at(_ dayOffset: Int, _ hour: Int, _ minute: Int) -> Date {
52            calendar.date(byAdding: DateComponents(day: dayOffset, hour: hour, minute: minute), to: today)!
53        }
54        func token(
55            _ id: String, _ question: String, _ text: String, form: String? = nil, place: Coordinate? = nil
56        ) -> Token {
57            Token(
58                id: id, questionID: p + question, text: text,
59                place: place.map { PlaceDetails(coordinate: $0) }, narrativeForm: form, modifiedAt: now)
60        }
61
62        let home = Coordinate(latitude: 53.3866, longitude: -2.9185)
63        let park = Coordinate(latitude: 53.38133, longitude: -2.93534)
64        let cavern = Coordinate(latitude: 53.4064, longitude: -2.9876)
65        let strawberry = Coordinate(latitude: 53.3889, longitude: -2.8869)
66        let tokens = [
67            token("demo-doors", "activity", "Opening up the doors"),
68            token("demo-ground", "activity", "Getting my feet back on the ground"),
69            token("demo-cooking", "activity", "Cooking"),
70            token("demo-home", "location", "Home", form: "home", place: home),
71            token("demo-park", "location", "Sefton Park", form: "the park", place: park),
72            token("demo-alex", "people", "Alex"),
73            token("demo-paul", "people", "Paul"),
74            // Used only by the history.
75            token("demo-rehearsing", "activity", "Rehearsing"),
76            token("demo-writing", "activity", "Writing songs"),
77            token("demo-recording", "activity", "Recording"),
78            token("demo-reading", "activity", "Reading"),
79            token("demo-walking", "activity", "Walking"),
80            token("demo-cavern", "location", "The Cavern", form: "the Cavern", place: cavern),
81            token(
82                "demo-strawberry", "location", "Strawberry Field", form: "Strawberry Field", place: strawberry),
83            token("demo-john", "people", "John"),
84            token("demo-george", "people", "George"),
85            token("demo-ringo", "people", "Ringo"),
86        ]
87
88        func context(_ coordinate: Coordinate, _ temperature: Double, _ condition: String) -> Context {
89            var placemark = Placemark()
90            placemark.locality = "Liverpool"
91            placemark.administrativeArea = "England"
92            placemark.countryCode = "GB"
93            placemark.cityWithContext = "Liverpool, England"
94            return Context(
95                location: LocationContext(coordinate: coordinate, placemark: placemark),
96                weather: WeatherContext(source: .weatherKit, condition: condition, temperature: temperature))
97        }
98        func answer(_ question: String, _ value: ResponseValue?) -> Response {
99            Response(questionID: p + question, prompt: "", value: value)
100        }
101        // Report IDs are fixed, in the order the reports are made, so every
102        // launch seeds the same reports and an export from one launch
103        // imports into another without duplicates.
104        var reportCount = 0
105        func reportID() -> UUID {
106            reportCount += 1
107            return UUID(uuidString: String(format: "DE000000-0000-4000-8000-%012d", reportCount))!
108        }
109        // Prompted reports come from a notification; the rest are started
110        // in the app.
111        func report(_ date: Date, _ kind: ReportKind, _ responses: [Response], _ context: Context) -> Report {
112            let isPrompted = kind == .random
113            return Report(
114                id: reportID(), date: date, timeZone: TimeZone.current.identifier, kind: kind,
115                trigger: isPrompted ? .notification : .app, state: .complete, promptedAt: isPrompted ? date : nil,
116                completedAt: date.addingTimeInterval(40), context: context, responses: responses, modifiedAt: now)
117        }
118        func answered(
119            _ date: Date, _ kind: ReportKind, doing: [String], at place: String, _ coordinate: Coordinate,
120            with people: [String], working: Bool, mood: String, _ temperature: Double, _ condition: String
121        ) -> Report {
122            report(
123                date, kind,
124                [
125                    answer("activity", .tokens(doing)),
126                    answer("location", .place(PlaceAnswer(tokenID: place, coordinate: coordinate))),
127                    answer("people", people.isEmpty ? nil : .tokens(people)),
128                    answer("working", .options([working ? ResponseValue.yesOption : ResponseValue.noOption])),
129                    answer("mood", .options([mood])),
130                ],
131                context(coordinate, temperature, condition))
132        }
133        func steps(_ count: Int) -> HealthContext {
134            HealthContext(activity: ActivityHealth(steps: count))
135        }
136
137        let wake = at(0, 7, 2)
138        let night = HealthContext(
139            sleep: SleepHealth(start: at(-1, 23, 18), end: wake, asleep: 7 * 3600 + 21 * 60))
140        let reports: [(Report, HealthContext)] = [
141            (
142                report(
143                    at(-1, 22, 48), .bedtime,
144                    [
145                        answer("coffee", .number(2)),
146                        answer("learned", .text("Ginkgo trees are older than the dinosaurs")),
147                    ],
148                    context(home, 10, "Cloudy")),
149                steps(9_412)
150            ),
151            (
152                answered(
153                    at(-1, 18, 21), .random, doing: ["demo-cooking"], at: "demo-home", home, with: ["demo-alex"],
154                    working: false, mood: "Good", 12, "Mostly Cloudy"),
155                steps(8_730)
156            ),
157            (report(wake, .wake, [answer("sleep-quality", .options(["Well"]))], context(home, 8, "Drizzle")), night),
158            (
159                answered(
160                    at(0, 9, 37), .random, doing: ["demo-doors"], at: "demo-home", home, with: [],
161                    working: true, mood: "Not so self-assured", 11, "Cloudy"),
162                steps(2_140)
163            ),
164            // An Instant Report from a prompt: context and no answers.
165            (
166                Report(
167                    id: reportID(), date: at(0, 13, 4), timeZone: TimeZone.current.identifier, kind: .random,
168                    trigger: .notification, state: .passive, promptedAt: at(0, 13, 4),
169                    context: context(park, 14, "Partly Cloudy"), modifiedAt: now),
170                steps(6_318)
171            ),
172            // The detail screen's report, `detailReportID`.
173            (
174                answered(
175                    at(0, 15, 52), .manual, doing: ["demo-ground"], at: "demo-park", park, with: ["demo-paul"],
176                    working: false, mood: "Appreciative", 13, "Cloudy"),
177                steps(7_905)
178            ),
179        ]
180        let history = Self.history(
181            at: at, coordinates: ["demo-home": home, "demo-park": park, "demo-cavern": cavern,
182                "demo-strawberry": strawberry],
183            report: report, answered: answered, answer: answer, context: context, steps: steps)
184        for (index, (report, health)) in (reports + history).enumerated() {
185            try await store.insert(report, newTokens: index == 0 ? tokens : [])
186            // Settled, so the Health filler leaves it as it is.
187            try await store.setHealth(HealthRecord(health: health, derivedAt: now, isSettled: true), for: report.id)
188        }
189    }
190
191    /// Four weeks of reports before yesterday, so the charts have something
192    /// to show: a wake and bedtime report each day and a few prompted ones
193    /// between, working at the Cavern on weekdays. The answers come from a
194    /// generator with a fixed seed, so every launch seeds the same history.
195    private static func history(
196        at: (Int, Int, Int) -> Date,
197        coordinates: [String: Coordinate],
198        report: (Date, ReportKind, [Response], Context) -> Report,
199        answered: (
200            Date, ReportKind, [String], String, Coordinate, [String], Bool, String, Double, String
201        ) -> Report,
202        answer: (String, ResponseValue?) -> Response,
203        context: (Coordinate, Double, String) -> Context,
204        steps: (Int) -> HealthContext
205    ) -> [(Report, HealthContext)] {
206        var generator = SeededGenerator(seed: 1965)
207        func pick<T>(_ items: [T]) -> T { items.randomElement(using: &generator)! }
208        func roll(_ range: ClosedRange<Int>) -> Int { Int.random(in: range, using: &generator) }
209
210        let home = coordinates["demo-home"]!
211        let conditions = ["Cloudy", "Cloudy", "Mostly Cloudy", "Partly Cloudy", "Drizzle", "Rain", "Clear"]
212        // Weighted towards the better moods.
213        let moods = ["Great", "Good", "Good", "Good", "Okay", "Okay", "Bad"]
214        let band = ["demo-john", "demo-george", "demo-ringo", "demo-paul"]
215
216        var history: [(Report, HealthContext)] = []
217        for day in (-29)...(-2) {
218            let weekday = Calendar.current.component(.weekday, from: at(day, 12, 0))
219            let isWorkday = (2...6).contains(weekday)
220            let base = Double(roll(7...13))
221
222            let wake = at(day, roll(6...7), roll(0...59))
223            let asleep = roll(330...500) * 60
224            let quality = asleep >= 7 * 3600 ? "Well" : asleep >= 6 * 3600 ? "Okay" : "Poorly"
225            let night = HealthContext(
226                sleep: SleepHealth(
227                    start: wake.addingTimeInterval(-Double(asleep + roll(5...40) * 60)), end: wake,
228                    asleep: TimeInterval(asleep)))
229            history.append((
230                report(wake, .wake, [answer("sleep-quality", .options([quality]))], context(home, base - 2, pick(conditions))),
231                night
232            ))
233
234            var hours = Array(Set((0..<roll(2...3)).map { _ in roll(9...21) })).sorted()
235            if hours.isEmpty { hours = [12] }
236            for hour in hours {
237                let isWorking = isWorkday && (10...17).contains(hour)
238                let doing: [String]
239                let place: String
240                let people: [String]
241                if isWorking {
242                    doing = [pick(["demo-rehearsing", "demo-rehearsing", "demo-writing", "demo-recording"])]
243                    place = "demo-cavern"
244                    people = Array(band.shuffled(using: &generator).prefix(roll(1...3)))
245                } else if hour < 10 {
246                    doing = [pick(["demo-doors", "demo-reading", "demo-cooking"])]
247                    place = "demo-home"
248                    people = []
249                } else {
250                    let outing = pick(["demo-walking", "demo-ground", "demo-cooking", "demo-reading", "demo-writing"])
251                    doing = [outing]
252                    switch outing {
253                    case "demo-walking": place = pick(["demo-park", "demo-strawberry"])
254                    case "demo-ground": place = "demo-park"
255                    default: place = "demo-home"
256                    }
257                    people = roll(0...2) == 0 ? [] : [pick(["demo-alex", "demo-paul", "demo-alex"])]
258                }
259                let date = at(day, hour, roll(0...59))
260                history.append((
261                    answered(
262                        date, .random, doing, place, coordinates[place]!, people, isWorking, pick(moods),
263                        base + Double(min(hour, 15) - 9) / 2, pick(conditions)),
264                    steps(hour * roll(450...750))
265                ))
266            }
267
268            let bedtime = at(day, roll(22...23), roll(0...59))
269            history.append((
270                report(
271                    bedtime, .bedtime, [answer("coffee", .number(Decimal(isWorkday ? roll(1...4) : roll(0...2))))],
272                    context(home, base - 3, pick(conditions))),
273                steps(roll(4_000...13_000))
274            ))
275        }
276        return history
277    }
278    #endif
279}