summaryrefslogtreecommitdiff
path: root/DomainDig/SweepActivityController.swift
blob: 26fcb2d117771cc6133095d627e62765a94af9b8 (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
import ActivityKit
import Foundation

/// Starts, updates, and ends the sweep Live Activity around a batch run.
@MainActor
final class SweepActivityController {
    static let shared = SweepActivityController()

    private var activity: Activity<SweepActivityAttributes>?

    private init() {}

    func begin(title: String, total: Int) {
        guard ActivityAuthorizationInfo().areActivitiesEnabled else { return }
        // A previous activity that never ended (e.g. app killed mid-sweep)
        // would otherwise linger; replace it.
        end(changed: 0, warnings: 0, immediately: true)

        let state = SweepActivityAttributes.ContentState(
            completed: 0,
            total: total,
            currentDomain: nil,
            changed: 0,
            warnings: 0
        )
        activity = try? Activity.request(
            attributes: SweepActivityAttributes(title: title, startedAt: Date()),
            content: ActivityContent(state: state, staleDate: nil)
        )
    }

    func update(completed: Int, total: Int, currentDomain: String?) {
        guard let activity else { return }
        let state = SweepActivityAttributes.ContentState(
            completed: completed,
            total: total,
            currentDomain: currentDomain,
            changed: 0,
            warnings: 0
        )
        Task {
            await activity.update(ActivityContent(state: state, staleDate: nil))
        }
    }

    func end(changed: Int, warnings: Int, immediately: Bool = false) {
        guard let activity else { return }
        self.activity = nil
        let state = SweepActivityAttributes.ContentState(
            completed: activity.content.state.total,
            total: activity.content.state.total,
            currentDomain: nil,
            changed: changed,
            warnings: warnings
        )
        Task {
            await activity.end(
                ActivityContent(state: state, staleDate: nil),
                dismissalPolicy: immediately ? .immediate : .after(Date().addingTimeInterval(60))
            )
        }
    }
}