-
-
Notifications
You must be signed in to change notification settings - Fork 58
/
updater.go
590 lines (551 loc) · 14.2 KB
/
updater.go
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
package main
import (
"archive/zip"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
lm "github.com/hrfee/jfa-go/logmessages"
"github.com/hrfee/jfa-go/common"
)
const (
baseURL = "https://builds.hrfee.pw"
namespace = "hrfee"
repo = "jfa-go"
)
var buildTime time.Time = func() time.Time {
i, _ := strconv.ParseInt(buildTimeUnix, 10, 64)
return time.Unix(i, 0)
}()
type GHRelease struct {
HTMLURL string `json:"html_url"`
ID int `json:"id"`
TagName string `json:"tag_name"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
PublishedAt time.Time `json:"published_at"`
Assets []GHAsset `json:"assets"`
Body string `json:"body"`
}
type GHAsset struct {
Name string `json:"name"`
State string `json:"state"`
UpdatedAt time.Time `json:"updated_at"`
BrowserDownloadURL string `json:"browser_download_url"`
}
type UnixTime struct {
time.Time
}
func (t *UnixTime) UnmarshalJSON(b []byte) (err error) {
unix, err := strconv.ParseInt(strings.TrimPrefix(strings.TrimSuffix(string(b), "\""), "\""), 10, 64)
if err != nil {
return
}
t.Time = time.Unix(unix, 0)
return
}
func (t UnixTime) MarshalJSON() ([]byte, error) {
if t.Time == (time.Time{}) {
return []byte("\"\""), nil
}
return []byte("\"" + strconv.FormatInt(t.Time.Unix(), 10) + "\""), nil
}
var updater string
type BuildType int
const (
off BuildType = iota
internal // Internal assets through go:embed, no data/.
external // External assets in data/, accesses through app.localFS.
docker // Only notify of new updates, no self-updating.
)
type ApplyUpdate func() error
type Update struct {
Version string `json:"version"` // vX.X.X or git
Commit string `json:"commit"`
ReleaseDate int64 `json:"date"` // unix time
Description string `json:"description"` // Commit Name/Release title.
Changelog string `json:"changelog"` // Changelog, if applicable
Link string `json:"link"` // Link to commit/release page,
DownloadLink string `json:"download_link"` // Optional link to download page.
CanUpdate bool `json:"can_update"` // Whether or not update can be done automatically.
update ApplyUpdate `json:"-"` // Function to apply update if possible.
}
type Tag struct {
Ready bool `json:"ready"` // Whether or not build on this tag has completed.
Version string `json:"version,omitempty"` // Version/Commit
ReleaseDate UnixTime `json:"date"`
}
var goos = map[string]string{
"darwin": "macOS",
"linux": "Linux",
"windows": "Windows",
}
var goarch = map[string]string{
"amd64": "x86_64",
"arm64": "arm64",
"arm": "armv6",
}
// func newDockerBuild() Update {
// var tag string
// if version == "git" {
// tag = "docker-unstable"
// } else {
// tag = "docker-latest"
// }
// }
type Updater struct {
version, commit, tag, url, namespace, name string
stable bool
buildType BuildType
httpClient *http.Client
timeoutHandler common.TimeoutHandler
binary string
}
func newUpdater(buildroneURL, namespace, repo, version, commit, buildType string) *Updater {
// fmt.Printf(`Updater intializing with "%s", "%s", "%s", "%s", "%s", "%s"\n`, buildroneURL, namespace, repo, version, commit, buildType)
bType := off
tag := ""
switch buildType {
case "binary":
if binaryType == "internal" {
bType = internal
tag = "internal"
} else {
bType = external
tag = "external"
}
case "docker":
bType = docker
if version == "git" {
tag = "docker-unstable"
} else {
tag = "docker-latest"
}
default:
bType = off
}
if commit == "unknown" {
bType = off
}
if version == "git" && bType != docker {
tag += "-git"
}
binary := "jfa-go"
if runtime.GOOS == "windows" {
binary += ".exe"
}
return &Updater{
httpClient: &http.Client{Timeout: 10 * time.Second},
timeoutHandler: common.NewTimeoutHandler("updater", buildroneURL, true),
version: version,
commit: commit,
buildType: bType,
tag: tag,
url: buildroneURL,
namespace: namespace,
name: repo,
binary: binary,
}
}
type BuildDTO struct {
ID int64 // `json:"id"`
Name string // `json:"name"`
Date time.Time // `json:"date"`
Link string // `json:"link"`
Message string
Branch string // `json:"branch"`
Tags map[string]Tag
}
// SetTransport sets the http.Transport to use for requests. Can be used to set a proxy.
func (ud *Updater) SetTransport(t *http.Transport) {
ud.httpClient.Transport = t
}
func (ud *Updater) GetTag() (Tag, int, error) {
if ud.buildType == off {
return Tag{}, -1, nil
}
url := fmt.Sprintf("%s/repo/%s/%s/tag/latest/%s", ud.url, ud.namespace, ud.name, ud.tag)
// fmt.Printf("Pinging URL \"%s\" for updates\n", url)
req, _ := http.NewRequest("GET", url, nil)
resp, err := ud.httpClient.Do(req)
defer ud.timeoutHandler()
if err != nil || resp.StatusCode != 200 {
return Tag{}, resp.StatusCode, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return Tag{}, -1, err
}
var tag Tag
err = json.Unmarshal(body, &tag)
if tag.Version == "" {
err = errors.New("Tag at \"" + url + "\" was empty")
}
return tag, resp.StatusCode, err
}
func (t *Tag) IsNew() bool {
// fmt.Printf("Build Time: %+v, Release Date: %+v", buildTime, t.ReleaseDate)
// Add 20 minutes to account for build time
return t.Version[:7] != commit && t.Ready && t.ReleaseDate.After(buildTime.Add(time.Duration(20)*time.Minute))
}
func (ud *Updater) getRelease() (release GHRelease, status int, err error) {
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/latest", ud.namespace, ud.name)
req, _ := http.NewRequest("GET", url, nil)
resp, err := ud.httpClient.Do(req)
status = resp.StatusCode
defer ud.timeoutHandler()
if err != nil || resp.StatusCode != 200 {
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return
}
err = json.Unmarshal(body, &release)
return
}
func (ud *Updater) GetUpdate(tag Tag) (update Update, status int, err error) {
switch ud.buildType {
case internal:
if ud.tag == "internal-git" {
update, status, err = ud.getUpdateInternalGit(tag)
} else if ud.tag == "internal" {
update, status, err = ud.getUpdateInternal(tag)
}
case external, docker:
if strings.Contains(ud.tag, "git") || ud.tag == "docker-unstable" {
update, status, err = ud.getCommitGit(tag)
} else {
var release GHRelease
release, status, err = ud.getRelease()
if err != nil {
return
}
update = Update{
Changelog: release.Body,
Description: release.Name,
Version: release.TagName,
Commit: tag.Version,
Link: release.HTMLURL,
ReleaseDate: release.PublishedAt.Unix(),
}
}
if ud.buildType == docker {
update.DownloadLink = fmt.Sprintf("https://hub.docker.com/r/%s/%s/tags", ud.namespace, ud.name)
}
}
return
}
func (ud *Updater) getUpdateInternal(tag Tag) (update Update, status int, err error) {
release, status, err := ud.getRelease()
update = Update{
Changelog: release.Body,
Description: release.Name,
Version: release.TagName,
Commit: tag.Version,
Link: release.HTMLURL,
ReleaseDate: release.PublishedAt.Unix(),
}
if err != nil || status != 200 {
return
}
updateFunc, status, err := ud.downloadInternal(&release.Assets, tag)
if err == nil && status == 200 {
update.CanUpdate = true
update.update = updateFunc
}
return
}
func (ud *Updater) getCommitGit(tag Tag) (update Update, status int, err error) {
url := fmt.Sprintf("%s/repo/%s/%s/build/%s", ud.url, ud.namespace, ud.name, tag.Version)
req, _ := http.NewRequest("GET", url, nil)
resp, err := ud.httpClient.Do(req)
status = resp.StatusCode
defer ud.timeoutHandler()
if err != nil || resp.StatusCode != 200 {
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return
}
var build BuildDTO
err = json.Unmarshal(body, &build)
if err != nil {
return
}
update = Update{
Description: build.Name,
Version: "git",
Commit: tag.Version,
Link: build.Link,
ReleaseDate: tag.ReleaseDate.Unix(),
}
return
}
func (ud *Updater) getUpdateInternalGit(tag Tag) (update Update, status int, err error) {
update, status, err = ud.getCommitGit(tag)
if err != nil || status != 200 {
return
}
updateFunc, status, err := ud.downloadInternalGit()
if err == nil && status == 200 {
update.CanUpdate = true
update.update = updateFunc
}
return
}
func getBuildName() string {
operatingSystem, ok := goos[runtime.GOOS]
if !ok {
for _, v := range goos {
if strings.Contains(v, runtime.GOOS) {
operatingSystem = v
break
}
}
}
if operatingSystem == "" {
return ""
}
arch, ok := goarch[runtime.GOARCH]
if !ok {
for _, v := range goarch {
if strings.Contains(v, runtime.GOARCH) {
arch = v
break
}
}
}
if arch == "" {
return ""
}
// Tray builds always have E2EE but aren't labelled as so,
// hence the specific ordering here.
subtype := ""
if MatrixE2EE() {
subtype = "MatrixE2EE_"
}
if TRAY {
subtype = "TrayIcon_"
}
return subtype + operatingSystem + "_" + arch
}
func (ud *Updater) downloadInternal(assets *[]GHAsset, tag Tag) (applyUpdate ApplyUpdate, status int, err error) {
return ud.pullInternal(ud.getInternalURL(assets, tag))
}
func (ud *Updater) downloadInternalGit() (applyUpdate ApplyUpdate, status int, err error) {
return ud.pullInternal(ud.getInternalGitURL())
}
func (ud *Updater) getInternalURL(assets *[]GHAsset, tag Tag) string {
buildName := getBuildName()
if buildName == "" {
return ""
}
url := ""
for _, asset := range *assets {
if strings.Contains(asset.Name, buildName) {
url = asset.BrowserDownloadURL
break
}
}
return url
}
func (ud *Updater) getInternalGitURL() string {
buildName := getBuildName()
if buildName == "" {
return ""
}
return fmt.Sprintf("%s/repo/%s/%s/latest/file/%s", ud.url, ud.namespace, ud.name, buildName)
}
func (ud *Updater) pullInternal(url string) (applyUpdate ApplyUpdate, status int, err error) {
if url == "" {
return
}
req, _ := http.NewRequest("GET", url, nil)
resp, err := ud.httpClient.Do(req)
status = resp.StatusCode
if err != nil || resp.StatusCode != 200 {
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
status = -1
return
}
zp, err := zip.NewReader(bytes.NewReader(body), int64(len(body)))
if err != nil {
status = -1
return
}
for _, zf := range zp.File {
if zf.Name != ud.binary {
continue
}
var file string
file, err = os.Executable()
if err != nil {
return
}
var path string
path, err = filepath.EvalSymlinks(file)
if err != nil {
return
}
var info fs.FileInfo
info, err = os.Stat(path)
if err != nil {
return
}
mode := info.Mode()
var unzippedFile io.ReadCloser
unzippedFile, err = zf.Open()
if err != nil {
return
}
defer unzippedFile.Close()
var f *os.File
f, err = os.OpenFile(path+"_", os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode)
if err != nil {
return
}
defer f.Close()
_, err = io.Copy(f, unzippedFile)
if err != nil {
return
}
applyUpdate = func() error {
oldName := path + "-" + version + "-" + commit
err := os.Rename(path, oldName)
if err != nil {
return err
}
err = os.Rename(path+"_", path)
if err != nil {
return err
}
return os.Remove(oldName)
}
return
}
// gz, err := gzip.NewReader(resp.Body)
// if err != nil {
// status = -1
// return
// }
// defer gz.Close()
// tarReader := tar.NewReader(gz)
// var header *tar.Header
// for {
// header, err = tarReader.Next()
// if err == io.EOF {
// break
// }
// if err != nil {
// status = -1
// return
// }
// switch header.Typeflag {
// case tar.TypeReg:
// // Search only for file named ud.binary
// if header.Name == ud.binary {
// var file string
// file, err = os.Executable()
// if err != nil {
// return
// }
// var path string
// path, err = filepath.EvalSymlinks(file)
// if err != nil {
// return
// }
// var info fs.FileInfo
// info, err = os.Stat(path)
// if err != nil {
// return
// }
// mode := info.Mode()
// var f *os.File
// f, err = os.OpenFile(path+"_", os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode)
// if err != nil {
// return
// }
// defer f.Close()
// _, err = io.Copy(f, tarReader)
// if err != nil {
// return
// }
// applyUpdate = func() error {
// oldName := path + "-" + version + "-" + commit
// err := os.Rename(path, oldName)
// if err != nil {
// return err
// }
// err = os.Rename(path+"_", path)
// if err != nil {
// return err
// }
// return os.Remove(oldName)
// }
// return
// }
// }
// }
err = errors.New("Couldn't find file: " + ud.binary)
return
}
// func newInternalBuild() Update {
// tag := "internal"
// func update(path string) err {
// if
// fp, err := os.Executable()
// if err != nil {
// return err
// }
// fullPath, err := filepath.EvalSymlinks(fp)
// if err != nil {
// return err
// }
// newBinary,
// }
func (app *appContext) checkForUpdates() {
for {
go func() {
tag, status, err := app.updater.GetTag()
if status != 200 || err != nil {
if err != nil && strings.Contains(err.Error(), "strconv.ParseInt") {
app.err.Println("No new updates available.")
} else if status != -1 { // -1 means updates disabled, we don't need to log it.
app.err.Printf(lm.FailedGetUpdateTag, err)
}
return
}
if tag != app.tag && tag.IsNew() {
app.info.Println(lm.FoundUpdate)
app.debug.Printf(lm.UpdateTagDetails, tag)
update, status, err := app.updater.GetUpdate(tag)
if status != 200 || err != nil {
app.err.Printf(lm.FailedGetUpdate, err)
return
}
app.tag = tag
app.update = update
app.newUpdate = true
}
}()
time.Sleep(30 * time.Minute)
}
}