summaryrefslogtreecommitdiff
path: root/Hutch/Models/ContributionCalendar.swift
blob: e2942dd4a5ac41a4d86b9877c4362e0bebdcfadd (plain) (blame)
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
import Foundation

struct ContributionCalendarResponse: Decodable, Sendable, Hashable {
    let actor: String
    let from: Date
    let to: Date
    let isIndexed: Bool
    let lastPolledAt: Date?
    let indexingState: ContributionIndexingState
    let days: [ContributionDay]

    enum CodingKeys: String, CodingKey {
        case actor
        case from
        case to
        case isIndexed = "is_indexed"
        case lastPolledAt = "last_polled_at"
        case indexingState = "indexing_state"
        case days
    }

    init(
        actor: String,
        from: Date,
        to: Date,
        isIndexed: Bool,
        lastPolledAt: Date?,
        indexingState: ContributionIndexingState,
        days: [ContributionDay]
    ) {
        self.actor = actor
        self.from = from
        self.to = to
        self.isIndexed = isIndexed
        self.lastPolledAt = lastPolledAt
        self.indexingState = indexingState
        self.days = days.sorted { $0.date < $1.date }
    }

    init(from decoder: any Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        actor = try container.decode(String.self, forKey: .actor)
        from = try ContributionDateParser.decodeDateString(from: container, forKey: .from)
        to = try ContributionDateParser.decodeDateString(from: container, forKey: .to)
        isIndexed = try container.decodeIfPresent(Bool.self, forKey: .isIndexed) ?? false
        lastPolledAt = try ContributionDateParser.decodeOptionalTimestamp(from: container, forKey: .lastPolledAt)
        indexingState = try container.decodeIfPresent(ContributionIndexingState.self, forKey: .indexingState) ?? .indexed
        days = try container.decode([ContributionDay].self, forKey: .days).sorted { $0.date < $1.date }
    }

    var totalCount: Int {
        days.reduce(into: 0) { partialResult, day in
            partialResult += day.count
        }
    }

    var isEmpty: Bool {
        totalCount == 0
    }
}

struct ContributionDay: Decodable, Sendable, Hashable, Identifiable {
    var id: Date { date }

    let date: Date
    let count: Int
    let score: Double

    enum CodingKeys: String, CodingKey {
        case date
        case count
        case score
    }

    init(date: Date, count: Int, score: Double) {
        self.date = date
        self.count = count
        self.score = score
    }

    init(from decoder: any Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        date = try ContributionDateParser.decodeDateString(from: container, forKey: .date)
        count = try container.decode(Int.self, forKey: .count)
        score = try container.decode(Double.self, forKey: .score)
    }

    var intensity: ContributionIntensity {
        ContributionIntensity(count: count)
    }
}

struct ContributionStatsResponse: Decodable, Sendable, Hashable {
    let actor: String
    let from: Date
    let to: Date
    let isIndexed: Bool
    let lastPolledAt: Date?
    let indexingState: ContributionIndexingState
    let totalEvents: Int
    let totalScore: Double
    let activeDays: Int
    let longestStreak: Int
    let currentStreak: Int

    enum CodingKeys: String, CodingKey {
        case actor
        case from
        case to
        case isIndexed = "is_indexed"
        case lastPolledAt = "last_polled_at"
        case indexingState = "indexing_state"
        case totalEvents = "total_events"
        case totalScore = "total_score"
        case activeDays = "active_days"
        case longestStreak = "longest_streak"
        case currentStreak = "current_streak"
    }

    init(
        actor: String,
        from: Date,
        to: Date,
        isIndexed: Bool,
        lastPolledAt: Date?,
        indexingState: ContributionIndexingState,
        totalEvents: Int,
        totalScore: Double,
        activeDays: Int,
        longestStreak: Int,
        currentStreak: Int
    ) {
        self.actor = actor
        self.from = from
        self.to = to
        self.isIndexed = isIndexed
        self.lastPolledAt = lastPolledAt
        self.indexingState = indexingState
        self.totalEvents = totalEvents
        self.totalScore = totalScore
        self.activeDays = activeDays
        self.longestStreak = longestStreak
        self.currentStreak = currentStreak
    }

    init(from decoder: any Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        actor = try container.decode(String.self, forKey: .actor)
        from = try ContributionDateParser.decodeDateString(from: container, forKey: .from)
        to = try ContributionDateParser.decodeDateString(from: container, forKey: .to)
        isIndexed = try container.decodeIfPresent(Bool.self, forKey: .isIndexed) ?? false
        lastPolledAt = try ContributionDateParser.decodeOptionalTimestamp(from: container, forKey: .lastPolledAt)
        indexingState = try container.decodeIfPresent(ContributionIndexingState.self, forKey: .indexingState) ?? .indexed
        totalEvents = try container.decode(Int.self, forKey: .totalEvents)
        totalScore = try container.decode(Double.self, forKey: .totalScore)
        activeDays = try container.decode(Int.self, forKey: .activeDays)
        longestStreak = try container.decode(Int.self, forKey: .longestStreak)
        currentStreak = try container.decode(Int.self, forKey: .currentStreak)
    }
}

enum ContributionIndexingState: String, Codable, Sendable, Hashable {
    case pending
    case indexed
    case error
}

enum ContributionIntensity: Int, Sendable, CaseIterable {
    case empty = 0
    case level1 = 1
    case level2 = 2
    case level3 = 3
    case level4 = 4

    init(count: Int) {
        switch count {
        case ..<1:
            self = .empty
        case 1:
            self = .level1
        case 2...3:
            self = .level2
        case 4...6:
            self = .level3
        default:
            self = .level4
        }
    }
}

struct ContributionWeek: Sendable, Hashable {
    let startDate: Date
    let days: [ContributionDay]
}

enum ContributionCalendarLayout {
    static func weekColumns(
        from days: [ContributionDay],
        calendar: Calendar = .contributionCalendar
    ) -> [ContributionWeek] {
        let groupedDays = Dictionary(grouping: days) { day in
            calendar.startOfWeek(for: day.date)
        }

        return groupedDays.keys.sorted().map { weekStart in
            ContributionWeek(
                startDate: weekStart,
                days: groupedDays[weekStart, default: []].sorted { $0.date < $1.date }
            )
        }
    }

    static func recentWeeks(
        from days: [ContributionDay],
        count: Int,
        calendar: Calendar = .contributionCalendar
    ) -> [ContributionWeek] {
        Array(weekColumns(from: days, calendar: calendar).suffix(count))
    }
}

enum ContributionDateParser {
    static func parse(_ rawValue: String) -> Date? {
        let parts = rawValue.split(separator: "-", omittingEmptySubsequences: false)
        guard
            parts.count == 3,
            let year = Int(parts[0]),
            let month = Int(parts[1]),
            let day = Int(parts[2])
        else {
            return nil
        }

        var components = DateComponents()
        components.calendar = .contributionCalendar
        components.timeZone = TimeZone(secondsFromGMT: 0)
        components.year = year
        components.month = month
        components.day = day

        guard let date = components.date else {
            return nil
        }

        let resolvedComponents = Calendar.contributionCalendar.dateComponents([.year, .month, .day], from: date)
        guard
            resolvedComponents.year == year,
            resolvedComponents.month == month,
            resolvedComponents.day == day
        else {
            return nil
        }

        return date
    }

    static func decodeDateString<Key: CodingKey>(
        from container: KeyedDecodingContainer<Key>,
        forKey key: Key
    ) throws -> Date {
        let rawValue = try container.decode(String.self, forKey: key)

        guard let date = parse(rawValue) else {
            throw DecodingError.dataCorruptedError(
                forKey: key,
                in: container,
                debugDescription: "Invalid contribution date: \(rawValue)"
            )
        }

        return date
    }

    static func parseTimestamp(_ rawValue: String) -> Date? {
        let formatter = ISO8601DateFormatter()
        formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
        formatter.timeZone = TimeZone(secondsFromGMT: 0)

        if let date = formatter.date(from: rawValue) {
            return date
        }

        formatter.formatOptions = [.withInternetDateTime]
        if let date = formatter.date(from: rawValue) {
            return date
        }

        let fallbackFormats = [
            "yyyy-MM-dd'T'HH:mm:ss.SSSSSS",
            "yyyy-MM-dd'T'HH:mm:ss.SSS",
            "yyyy-MM-dd'T'HH:mm:ss"
        ]

        let dateFormatter = DateFormatter()
        dateFormatter.calendar = .contributionCalendar
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

        for format in fallbackFormats {
            dateFormatter.dateFormat = format
            if let date = dateFormatter.date(from: rawValue) {
                return date
            }
        }

        return nil
    }

    static func decodeOptionalTimestamp<Key: CodingKey>(
        from container: KeyedDecodingContainer<Key>,
        forKey key: Key
    ) throws -> Date? {
        guard let rawValue = try container.decodeIfPresent(String.self, forKey: key) else {
            return nil
        }

        guard let date = parseTimestamp(rawValue) else {
            throw DecodingError.dataCorruptedError(
                forKey: key,
                in: container,
                debugDescription: "Invalid contribution timestamp: \(rawValue)"
            )
        }

        return date
    }
}

extension Calendar {
    static var contributionCalendar: Calendar {
        var calendar = Calendar(identifier: .gregorian)
        calendar.firstWeekday = 1
        calendar.timeZone = TimeZone(secondsFromGMT: 0)!
        return calendar
    }

    func startOfWeek(for date: Date) -> Date {
        dateInterval(of: .weekOfYear, for: date)?.start ?? startOfDay(for: date)
    }
}