1package coordinator
2
3import (
4 "context"
5 "fmt"
6 "sync"
7
8 "github.com/jwijenbergh/puregotk/v4/glib"
9
10 "github.com/bnema/dumber/internal/application/usecase"
11 "github.com/bnema/dumber/internal/domain/entity"
12 "github.com/bnema/dumber/internal/infrastructure/config"
13 "github.com/bnema/dumber/internal/logging"
14 "github.com/bnema/dumber/internal/ui/component"
15)
16
17// UpdateCoordinator handles update checking and notification.
18type UpdateCoordinator struct {
19 checkUC *usecase.CheckUpdateUseCase
20 applyUC *usecase.ApplyUpdateUseCase
21 toaster *component.Toaster
22 config *config.Config
23 mu sync.RWMutex // Protects status and lastInfo
24 status entity.UpdateStatus
25 lastInfo *usecase.CheckUpdateOutput
26}
27
28// NewUpdateCoordinator creates a new update coordinator.
29func NewUpdateCoordinator(
30 checkUC *usecase.CheckUpdateUseCase,
31 applyUC *usecase.ApplyUpdateUseCase,
32 toaster *component.Toaster,
33 cfg *config.Config,
34) *UpdateCoordinator {
35 return &UpdateCoordinator{
36 checkUC: checkUC,
37 applyUC: applyUC,
38 toaster: toaster,
39 config: cfg,
40 status: entity.UpdateStatusUnknown,
41 }
42}
43
44// CheckOnStartup performs an async update check if enabled in config.
45// This should be called during app initialization.
46func (c *UpdateCoordinator) CheckOnStartup(ctx context.Context) {
47 log := logging.FromContext(ctx)
48
49 if !c.config.Update.EnableOnStartup {
50 log.Debug().Msg("update check on startup disabled")
51 return
52 }
53
54 go c.checkAsync(ctx)
55}
56
57// checkAsync performs the update check in a goroutine.
58func (c *UpdateCoordinator) checkAsync(ctx context.Context) {
59 log := logging.FromContext(ctx)
60
61 result, err := c.checkUC.Execute(ctx, usecase.CheckUpdateInput{})
62 if err != nil {
63 log.Warn().Err(err).Msg("background update check failed")
64 c.mu.Lock()
65 c.status = entity.UpdateStatusFailed
66 c.mu.Unlock()
67 return
68 }
69
70 // Update both lastInfo and status atomically to avoid inconsistent reads.
71 c.mu.Lock()
72 c.lastInfo = result
73 if !result.UpdateAvailable {
74 c.status = entity.UpdateStatusUpToDate
75 c.mu.Unlock()
76 log.Debug().
77 Str("version", result.CurrentVersion).
78 Msg("already on latest version")
79 return
80 }
81 c.status = entity.UpdateStatusAvailable
82 c.mu.Unlock()
83 log.Info().
84 Str("current", result.CurrentVersion).
85 Str("latest", result.LatestVersion).
86 Bool("can_auto_update", result.CanAutoUpdate).
87 Msg("update available")
88
89 // Show notification on GTK main thread.
90 c.showUpdateNotification(ctx, result)
91
92 // Auto-download if enabled and possible.
93 if c.config.Update.AutoDownload && result.CanAutoUpdate {
94 // Spawn download in separate goroutine to not block check completion.
95 go c.downloadAsync(ctx, result.DownloadURL)
96 }
97}
98
99// showUpdateNotification displays a toast notification about the update.
100func (c *UpdateCoordinator) showUpdateNotification(ctx context.Context, result *usecase.CheckUpdateOutput) {
101 var msg string
102 if result.CanAutoUpdate && c.config.Update.AutoDownload {
103 msg = fmt.Sprintf("Downloading update %s...", result.LatestVersion)
104 } else if result.CanAutoUpdate {
105 msg = fmt.Sprintf("Update %s available", result.LatestVersion)
106 } else {
107 msg = fmt.Sprintf("Update %s available (manual install required)", result.LatestVersion)
108 }
109
110 // Dispatch to GTK main thread.
111 cb := glib.SourceFunc(func(_ uintptr) bool {
112 c.toaster.Show(ctx, msg, component.ToastInfo)
113 return false
114 })
115 glib.IdleAdd(&cb, 0)
116}
117
118// downloadAsync downloads and stages the update in the background.
119func (c *UpdateCoordinator) downloadAsync(ctx context.Context, downloadURL string) {
120 log := logging.FromContext(ctx)
121
122 c.mu.Lock()
123 c.status = entity.UpdateStatusDownloading
124 c.mu.Unlock()
125
126 result, err := c.applyUC.Execute(ctx, usecase.ApplyUpdateInput{
127 DownloadURL: downloadURL,
128 })
129 if err != nil {
130 log.Error().Err(err).Msg("update download failed")
131 c.mu.Lock()
132 c.status = entity.UpdateStatusFailed
133 c.mu.Unlock()
134 c.showToast(ctx, "Update download failed", component.ToastError)
135 return
136 }
137
138 c.mu.Lock()
139 if result.Status == entity.UpdateStatusReady {
140 c.status = entity.UpdateStatusReady
141 c.mu.Unlock()
142 log.Info().Msg("update ready, will apply on exit")
143 c.showToast(ctx, "Update ready - applies on exit", component.ToastSuccess)
144 } else {
145 c.status = entity.UpdateStatusFailed
146 c.mu.Unlock()
147 log.Warn().Str("message", result.Message).Msg("update staging failed")
148 c.showToast(ctx, result.Message, component.ToastWarning)
149 }
150}
151
152// showToast dispatches a toast notification to the GTK main thread.
153func (c *UpdateCoordinator) showToast(ctx context.Context, msg string, level component.ToastLevel) {
154 cb := glib.SourceFunc(func(_ uintptr) bool {
155 c.toaster.Show(ctx, msg, level)
156 return false
157 })
158 glib.IdleAdd(&cb, 0)
159}
160
161// FinalizeOnExit applies any staged update during shutdown.
162// This should be called from the app's shutdown handler.
163func (c *UpdateCoordinator) FinalizeOnExit(ctx context.Context) error {
164 if c.applyUC == nil {
165 return nil
166 }
167 return c.applyUC.FinalizeOnExit(ctx)
168}
169
170// Status returns the current update status.
171func (c *UpdateCoordinator) Status() entity.UpdateStatus {
172 c.mu.RLock()
173 defer c.mu.RUnlock()
174 return c.status
175}
176
177// LastCheckResult returns the result of the last update check.
178func (c *UpdateCoordinator) LastCheckResult() *usecase.CheckUpdateOutput {
179 c.mu.RLock()
180 defer c.mu.RUnlock()
181 return c.lastInfo
182}
183
184// HasPendingUpdate returns true if an update is staged for exit.
185func (c *UpdateCoordinator) HasPendingUpdate(ctx context.Context) bool {
186 if c.applyUC == nil {
187 return false
188 }
189 return c.applyUC.HasPendingUpdate(ctx)
190}