Skip to content

Commit

Permalink
[FEATURE] Add auto updating
Browse files Browse the repository at this point in the history
  • Loading branch information
Sharrnah committed Dec 13, 2022
1 parent 40c5e33 commit 327a2ee
Show file tree
Hide file tree
Showing 9 changed files with 413 additions and 9 deletions.
2 changes: 1 addition & 1 deletion FyneApp.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ Website = "https://github.com/Sharrnah/whispering"
Name = "Whispering Tiger"
ID = "tiger.whispering"
Version = "1.0.0"
Build = 16
Build = 17
10 changes: 6 additions & 4 deletions Pages/Profiles.go
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@ func CreateProfileWindow(onClose func()) fyne.CanvasObject {
println(err)
}
for _, file := range files {
if !file.IsDir() && (strings.HasSuffix(file.Name(), ".yaml") || strings.HasSuffix(file.Name(), ".yml")) {
if !file.IsDir() && !strings.HasPrefix(file.Name(), ".") && (strings.HasSuffix(file.Name(), ".yaml") || strings.HasSuffix(file.Name(), ".yml")) {
settingsFiles = append(settingsFiles, file.Name())
}
}
Expand Down Expand Up @@ -454,9 +454,11 @@ func CreateProfileWindow(onClose func()) fyne.CanvasObject {
Pause: 0.8,
Energy: 300,
}
err = profileSettings.LoadYamlSettings(settingsFiles[id])
if err != nil {
dialog.ShowError(err, fyne.CurrentApp().Driver().AllWindows()[1])
if Utilities.FileExists(settingsFiles[id]) {
err = profileSettings.LoadYamlSettings(settingsFiles[id])
if err != nil {
dialog.ShowError(err, fyne.CurrentApp().Driver().AllWindows()[1])
}
}
profileForm := profileListContent.Content.(*widget.Form)
profileForm.SubmitText = "Save and Load Profile"
Expand Down
69 changes: 69 additions & 0 deletions Updater/Downloader.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package Updater

import (
"fmt"
"io"
"net/http"
"os"
)

type OnProgress func(bytesWritten, contentLength uint64)

type WriteCounter struct {
Total uint64
ContentLength uint64
OnProgress OnProgress
}

type Download struct {
Url string
Filepath string
WriteCounter WriteCounter
}

func (wc *WriteCounter) Write(p []byte) (int, error) {
n := len(p)
wc.Total += uint64(n)
wc.OnProgress(wc.Total, wc.ContentLength)
return n, nil
}

// DownloadFile will download a url to a local file. It's efficient because it will
// write as it downloads and not load the whole file into memory. We pass an io.TeeReader
// into Copy() to report progress on the download.
func (d *Download) DownloadFile() error {

// Create the file, but give it a tmp file extension, this means we won't overwrite a
// file until it's downloaded, but we'll remove the tmp extension once downloaded.
out, err := os.Create(d.Filepath + ".tmp")
if err != nil {
return err
}

// Get the data
resp, err := http.Get(d.Url)
if err != nil {
out.Close()
return err
}
defer resp.Body.Close()

d.WriteCounter.ContentLength = uint64(resp.ContentLength)

// Create our progress reporter and pass it to be used alongside our writer
if _, err = io.Copy(out, io.TeeReader(resp.Body, &d.WriteCounter)); err != nil {
out.Close()
return err
}

// The progress use the same line so print a new line once it's finished downloading
fmt.Print("\n")

// Close the file without defer so it can happen before Rename()
out.Close()

if err = os.Rename(d.Filepath+".tmp", d.Filepath); err != nil {
return err
}
return nil
}
74 changes: 74 additions & 0 deletions Updater/Unzip.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package Updater

import (
"archive/zip"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)

func Unzip(src, dest string) error {
r, err := zip.OpenReader(src)
if err != nil {
return err
}
defer func() {
if err := r.Close(); err != nil {
panic(err)
}
}()

os.MkdirAll(dest, 0755)

// Closure to address file descriptors issue with all the deferred .Close() methods
extractAndWriteFile := func(f *zip.File) error {
rc, err := f.Open()
if err != nil {
return err
}
defer func() {
if err := rc.Close(); err != nil {
panic(err)
}
}()

path := filepath.Join(dest, f.Name)

// Check for ZipSlip (Directory traversal)
if !strings.HasPrefix(path, filepath.Clean(dest)+string(os.PathSeparator)) {
return fmt.Errorf("illegal file path: %s", path)
}

if f.FileInfo().IsDir() {
os.MkdirAll(path, f.Mode())
} else {
os.MkdirAll(filepath.Dir(path), f.Mode())
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer func() {
if err := f.Close(); err != nil {
panic(err)
}
}()

_, err = io.Copy(f, rc)
if err != nil {
return err
}
}
return nil
}

for _, f := range r.File {
err := extractAndWriteFile(f)
if err != nil {
return err
}
}

return nil
}
104 changes: 104 additions & 0 deletions Updater/UpdateInfo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package Updater

import (
"fmt"
"gopkg.in/yaml.v3"
"io"
"log"
"net/http"
"os"
)

/* example yaml
packages:
app:
version: 1.0.0.16
urls:
- https://eu2.someurl.com/app1.0.0.16_win.zip
data:
version: 1.0.0.3
urls:
- https://eu2.someurl.com/data1.0.0.3_win.zip
- https://usc1.someurl.com/data1.0.0.3_win.zip
*/

type UpdateInfo struct {
Version string `yaml:"version"`
Urls []string `yaml:"urls"`
}

func (i *UpdateInfo) WriteYaml(fileName string) {
// marshal the struct to yaml and save as file
yamlFile, err := yaml.Marshal(i)
if err != nil {
log.Printf("error: %v", err)
}
err = os.WriteFile(fileName, yamlFile, 0644)
if err != nil {
log.Printf("error: %v", err)
}
}

func (i *UpdateInfo) ReadYaml(data []byte) error {
// read the yaml file and unmarshal it to the struct
var err error
err = yaml.Unmarshal(data, i)
if err != nil {
log.Printf("Unmarshal: %v", err)
}
return err
}

type UpdatePackages struct {
Packages map[string]UpdateInfo `yaml:"packages"`
//DoNotAskAgain bool `yaml:"doNotAskAgain,omitempty"`
}

func (u *UpdatePackages) parsePackagesFromYaml(data []byte) error {
var err error
err = yaml.Unmarshal(data, u)
if err != nil {
log.Printf("Unmarshal: %v", err)
}
return err
}

func (u *UpdatePackages) getYaml(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return []byte{}, fmt.Errorf("GET error: %v", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return []byte{}, fmt.Errorf("status error: %v", resp.StatusCode)
}

data, err := io.ReadAll(resp.Body)
if err != nil {
return []byte{}, fmt.Errorf("read body: %v", err)
}

return data, nil
}

func (u *UpdatePackages) WriteYaml(fileName string) {
// marshal the struct to yaml and save as file
yamlFile, err := yaml.Marshal(u)
if err != nil {
log.Printf("error: %v", err)
}
err = os.WriteFile(fileName, yamlFile, 0644)
if err != nil {
log.Printf("error: %v", err)
}
}

func (u *UpdatePackages) GetUpdateInfo(url string) error {
data, err := u.getYaml(url)
if err != nil {
return err
}
return u.parsePackagesFromYaml(data)
}
12 changes: 8 additions & 4 deletions Websocket/messageHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,15 @@ func (c *MessageStruct) HandleReceiveMessage() {
case "processing_start":
var processingStarted = false
err = json.Unmarshal(c.Data, &processingStarted)
Fields.Field.ProcessingStatus.Start()
go func() {
time.Sleep(5 * time.Second)
if processingStarted {
Fields.Field.ProcessingStatus.Start()
go func() {
time.Sleep(10 * time.Second)
Fields.Field.ProcessingStatus.Stop()
}()
} else {
Fields.Field.ProcessingStatus.Stop()
}()
}
}
if err != nil {
log.Printf("Unmarshal: %v", err)
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.18

require (
fyne.io/fyne/v2 v2.2.4
github.com/dustin/go-humanize v1.0.0
github.com/gen2brain/malgo v0.11.10
github.com/gorilla/websocket v1.5.0
github.com/hajimehoshi/oto/v2 v2.3.1
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46t
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
Expand Down
Loading

0 comments on commit 327a2ee

Please sign in to comment.