Skip to content

Commit 41bf89d

Browse files
authored
feat(update): implement release check and notification system with UI banner (#258)
* feat(update): implement release check and notification system with UI banner * feat(update): also add toggle setting to enable or disable release notifications
1 parent 4ebc83b commit 41bf89d

23 files changed

Lines changed: 618 additions & 18 deletions

File tree

‎desktop/app/main.go‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,18 +76,28 @@ func run() error {
7676
_ = os.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
7777
}
7878

79+
url := "http://" + loopbackListenAddr + ":" + strconv.Itoa(desktop.Port) + "/"
80+
// The tray exists once the app is ready; the service checks for
81+
// releases from its start, so a check can finish before.
82+
var tray *mygo.Tray
83+
var logPath string
84+
watchReleases(func() {
85+
if tray != nil {
86+
setTrayMenu(tray, url, logPath, configPath)
87+
}
88+
})
89+
7990
_, stop, err := startService(configPath)
8091
if err != nil {
8192
return err
8293
}
83-
url := "http://" + loopbackListenAddr + ":" + strconv.Itoa(desktop.Port) + "/"
8494

8595
// Quit stops the service; a crash exit leaves it to the process exit.
8696
defer func() { stop() }()
8797

8898
// The service chooses the log file while starting: the data directory's
8999
// app.log unless config.yaml says otherwise.
90-
logPath := app.Config.Log.LogFile
100+
logPath = app.Config.Log.LogFile
91101

92102
mygo.App.SetName(appName)
93103
mygo.App.SetVersion(app.Version.Version)
@@ -110,7 +120,8 @@ func run() error {
110120
}
111121
}
112122

113-
tray, err := mygo.NewTray(mygo.TrayOptions{
123+
var err error
124+
tray, err = mygo.NewTray(mygo.TrayOptions{
114125
ID: appName,
115126
Icon: trayIcon(),
116127
IconIsTemplate: runtime.GOOS == "darwin",
@@ -147,7 +158,7 @@ func run() error {
147158

148159
// setTrayMenu builds the tray menu and reflects the system autostart state.
149160
func setTrayMenu(tray *mygo.Tray, url, logPath, configPath string) {
150-
menu := mygo.NewMenu([]*mygo.MenuItem{
161+
menu := mygo.NewMenu(append(updateMenuItems(), []*mygo.MenuItem{
151162
{Label: i18n.Localize("tray.open_browser"), Click: func(*mygo.MenuItem, *mygo.Window) { openBrowser(url) }},
152163
{Label: i18n.Localize("tray.open_log"), Click: func(*mygo.MenuItem, *mygo.Window) { openLogFile(logPath) }},
153164
{Label: i18n.Localize("tray.settings"), Click: func(*mygo.MenuItem, *mygo.Window) { openSettingsDialog(configPath) }},
@@ -166,7 +177,7 @@ func setTrayMenu(tray *mygo.Tray, url, logPath, configPath string) {
166177
},
167178
mygo.Separator(),
168179
{Role: mygo.RoleQuit, Label: i18n.Localize("tray.quit")},
169-
})
180+
}...))
170181
tray.SetMenu(menu)
171182
}
172183

‎desktop/app/update.go‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package main
2+
3+
import (
4+
"errors"
5+
6+
"github.com/bitxeno/atvloadly/internal/i18n"
7+
logx "github.com/bitxeno/atvloadly/internal/log"
8+
"github.com/bitxeno/atvloadly/internal/release"
9+
"github.com/egoist/mygo"
10+
)
11+
12+
// releaseNotificationID identifies the new-release notification, also when
13+
// its click launches the app again.
14+
const releaseNotificationID = "atvloadly-release"
15+
16+
// latestReleaseURL is the page the notification opens: the release it
17+
// announced, or a newer one by the time it is clicked.
18+
const latestReleaseURL = "https://github.com/" + release.Repo + "/releases/latest"
19+
20+
// watchReleases shows the service's release checks in the app: refreshMenu
21+
// is called on the main thread after every check, and a newer release is
22+
// announced with a native notification. Call it before App.Run, so that the
23+
// click on a notification that launched the app is received.
24+
func watchReleases(refreshMenu func()) {
25+
release.OnCheck(func(release.Info) {
26+
mygo.App.WhenReady(refreshMenu)
27+
})
28+
release.OnNewRelease(func(info release.Info) {
29+
mygo.App.WhenReady(func() {
30+
// Show waits for the permission prompt of the first
31+
// notification, which must not block the main thread.
32+
go showReleaseNotification(info)
33+
})
34+
})
35+
mygo.App.OnNotificationClick(func(id string) {
36+
if id == releaseNotificationID {
37+
openBrowser(latestReleaseURL)
38+
}
39+
})
40+
}
41+
42+
func showReleaseNotification(info release.Info) {
43+
if !mygo.NotificationsSupported() {
44+
return
45+
}
46+
n := mygo.NewNotification(mygo.NotificationOptions{
47+
ID: releaseNotificationID,
48+
Title: i18n.LocalizeF("notify.release_title", map[string]any{"version": info.Latest}),
49+
Body: i18n.LocalizeF("tray.update_notification", map[string]any{"current": info.Current}),
50+
})
51+
if err := n.Show(); err != nil && !errors.Is(err, mygo.ErrNotificationsDenied) {
52+
logx.Err(err).Msg("Failed to show the release notification")
53+
}
54+
}
55+
56+
// updateMenuItems returns the tray menu items offering a newer release, or
57+
// none.
58+
func updateMenuItems() []*mygo.MenuItem {
59+
info := release.Latest()
60+
if !info.Available {
61+
return nil
62+
}
63+
return []*mygo.MenuItem{
64+
{
65+
Label: i18n.LocalizeF("tray.update_available", map[string]any{"version": info.Latest}),
66+
Click: func(*mygo.MenuItem, *mygo.Window) { openBrowser(info.URL) },
67+
},
68+
mygo.Separator(),
69+
}
70+
}

‎go.mod‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ require (
3434
github.com/smallstep/pkcs7 v0.2.3
3535
github.com/urfave/cli/v2 v2.3.0
3636
golang.org/x/image v0.41.0
37+
golang.org/x/mod v0.35.0
3738
golang.org/x/text v0.37.0
3839
gopkg.in/natefinch/lumberjack.v2 v2.0.0
3940
gorm.io/gorm v1.25.7
@@ -82,7 +83,6 @@ require (
8283
github.com/valyala/tcplisten v1.0.0 // indirect
8384
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
8485
golang.org/x/crypto v0.50.0 // indirect
85-
golang.org/x/mod v0.35.0 // indirect
8686
golang.org/x/net v0.53.0 // indirect
8787
golang.org/x/sync v0.20.0 // indirect
8888
golang.org/x/sys v0.43.0 // indirect

‎internal/app/settings.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ type SettingsConfiguration struct {
4141
// GetGitHubToken and write it with Set/DeleteGitHubToken. The
4242
// settings API only reports whether a token is configured.
4343
GitHubToken string `koanf:"github_token" json:"github_token"`
44+
// NotifiedRelease is the atvloadly release tag already notified, so
45+
// each new release is notified once across restarts.
46+
NotifiedRelease string `koanf:"notified_release" json:"notified_release"`
47+
// ReleaseNotify enables the notification of new atvloadly releases.
48+
ReleaseNotify bool `koanf:"release_notify" json:"release_notify" default:"true"`
4449
} `koanf:"update" json:"update"`
4550
Notification struct {
4651
Enabled bool `koanf:"enabled" json:"enabled"`
@@ -128,6 +133,7 @@ func printRedactedSettings() {
128133
"task": Settings.Task,
129134
"update": map[string]any{
130135
"check_interval": Settings.Update.CheckInterval,
136+
"release_notify": Settings.Update.ReleaseNotify,
131137
"github_token": redactSecret(Settings.Update.GitHubToken),
132138
},
133139
"notification": map[string]any{

‎internal/bootstrap/bootstrap.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,10 @@ func Run(opts Options) (addr string, stop func(), err error) {
8989
// start jobs
9090
_ = task.ScheduleRefreshApps()
9191
manager.StartDeviceManager()
92+
// The scheduler repeats the release check with the update check interval.
93+
if app.Settings.Update.CheckInterval > 0 {
94+
go task.CheckRelease()
95+
}
9296

9397
port := conf.Server.Port
9498
if opts.Port > 0 {

‎internal/release/release.go‎

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
// Package release checks GitHub for new atvloadly releases, keeps the latest
2+
// result for the web UI and notifies once per new version.
3+
package release
4+
5+
import (
6+
"fmt"
7+
"net/http"
8+
"strings"
9+
"sync"
10+
"time"
11+
12+
"github.com/bitxeno/atvloadly/internal/app"
13+
atvhttp "github.com/bitxeno/atvloadly/internal/http"
14+
"github.com/bitxeno/atvloadly/internal/i18n"
15+
"github.com/bitxeno/atvloadly/internal/log"
16+
"github.com/bitxeno/atvloadly/internal/notify"
17+
"golang.org/x/mod/semver"
18+
)
19+
20+
// Repo is the GitHub repository that publishes atvloadly releases.
21+
const Repo = "bitxeno/atvloadly"
22+
23+
const requestTimeout = 30 * time.Second
24+
25+
// apiBaseURL is the GitHub REST API root; tests point it to a local server.
26+
var apiBaseURL = "https://api.github.com"
27+
28+
// sendNotification is replaced in tests.
29+
var sendNotification = notify.Send
30+
31+
// Info describes the running version and the latest published release.
32+
type Info struct {
33+
Current string `json:"current"`
34+
Latest string `json:"latest"`
35+
URL string `json:"url"`
36+
PublishedAt time.Time `json:"published_at"`
37+
// Available reports whether Latest is newer than Current. It is false for
38+
// development and nightly builds, whose version is not a release tag.
39+
Available bool `json:"available"`
40+
}
41+
42+
type githubRelease struct {
43+
TagName string `json:"tag_name"`
44+
HTMLURL string `json:"html_url"`
45+
PublishedAt time.Time `json:"published_at"`
46+
}
47+
48+
var (
49+
mu sync.RWMutex
50+
latest githubRelease
51+
checked []func(Info)
52+
announced []func(Info)
53+
)
54+
55+
// OnCheck registers fn to be called with the result of every successful
56+
// check. The desktop app uses it to show the release in its tray menu.
57+
func OnCheck(fn func(Info)) {
58+
mu.Lock()
59+
checked = append(checked, fn)
60+
mu.Unlock()
61+
}
62+
63+
// OnNewRelease registers fn to be called once per newer release, together
64+
// with the configured notification. The desktop app uses it to show a
65+
// native notification.
66+
func OnNewRelease(fn func(Info)) {
67+
mu.Lock()
68+
announced = append(announced, fn)
69+
mu.Unlock()
70+
}
71+
72+
// Latest returns the result of the last successful check.
73+
func Latest() Info {
74+
mu.RLock()
75+
r := latest
76+
mu.RUnlock()
77+
return newInfo(app.Version.Version, r)
78+
}
79+
80+
// Check fetches the latest release, stores it and sends a notification the
81+
// first time a newer version is seen.
82+
func Check() error {
83+
r, err := fetchLatest()
84+
if err != nil {
85+
return err
86+
}
87+
mu.Lock()
88+
latest = r
89+
onCheck, onNew := checked, announced
90+
mu.Unlock()
91+
92+
info := newInfo(app.Version.Version, r)
93+
for _, fn := range onCheck {
94+
fn(info)
95+
}
96+
if !info.Available {
97+
return nil
98+
}
99+
log.Infof("A new atvloadly release is available: %s (running %s)", info.Latest, info.Current)
100+
announce(info, onNew)
101+
return nil
102+
}
103+
104+
// announce sends the release notification and calls the OnNewRelease
105+
// handlers unless this version was already announced, which survives
106+
// restarts through the settings file. A failed notification is retried at
107+
// the next check, unless a handler already announced the release. Nothing is
108+
// announced while release notifications are disabled.
109+
func announce(info Info, handlers []func(Info)) {
110+
if !app.Settings.Update.ReleaseNotify || app.Settings.Update.NotifiedRelease == info.Latest {
111+
return
112+
}
113+
done := false
114+
if app.Settings.Notification.Enabled {
115+
title := i18n.LocalizeF("notify.release_title", map[string]any{"version": info.Latest})
116+
message := i18n.LocalizeF("notify.release_content", map[string]any{"current": info.Current, "url": info.URL})
117+
if err := sendNotification(title, message); err != nil {
118+
log.Err(err).Msg("Failed to send the release notification")
119+
} else {
120+
done = true
121+
}
122+
}
123+
for _, fn := range handlers {
124+
fn(info)
125+
done = true
126+
}
127+
if done {
128+
app.Settings.Update.NotifiedRelease = info.Latest
129+
app.SaveSettings()
130+
}
131+
}
132+
133+
func newInfo(current string, r githubRelease) Info {
134+
info := Info{
135+
Current: current,
136+
Latest: r.TagName,
137+
URL: r.HTMLURL,
138+
PublishedAt: r.PublishedAt,
139+
}
140+
cur, next := canonical(current), canonical(r.TagName)
141+
info.Available = cur != "" && next != "" && semver.Compare(next, cur) > 0
142+
return info
143+
}
144+
145+
// canonical returns v as a "vX.Y.Z" semantic version, or "" when it is not
146+
// one. Desktop builds carry the version without the "v" prefix.
147+
func canonical(v string) string {
148+
v = strings.TrimSpace(v)
149+
if v != "" && !strings.HasPrefix(v, "v") {
150+
v = "v" + v
151+
}
152+
if !semver.IsValid(v) {
153+
return ""
154+
}
155+
return v
156+
}
157+
158+
// fetchLatest returns the latest stable release; GitHub excludes drafts and
159+
// pre-releases from this endpoint.
160+
func fetchLatest() (githubRelease, error) {
161+
var r githubRelease
162+
req := atvhttp.NewClient().SetTimeout(requestTimeout).R().
163+
SetHeader("Accept", "application/vnd.github+json").
164+
SetHeader("X-GitHub-Api-Version", "2022-11-28").
165+
SetResult(&r)
166+
if token := app.GetGitHubToken(); token != "" {
167+
req.SetHeader("Authorization", "Bearer "+token)
168+
}
169+
resp, err := req.Get(fmt.Sprintf("%s/repos/%s/releases/latest", apiBaseURL, Repo))
170+
if err != nil {
171+
return r, fmt.Errorf("failed to fetch the latest atvloadly release: %w", err)
172+
}
173+
if resp.StatusCode() != http.StatusOK {
174+
return r, fmt.Errorf("failed to fetch the latest atvloadly release: HTTP %d", resp.StatusCode())
175+
}
176+
if r.TagName == "" {
177+
return r, fmt.Errorf("the latest atvloadly release has no tag")
178+
}
179+
return r, nil
180+
}

0 commit comments

Comments
 (0)
⌂ 换网址