Skip to content

Commit

Permalink
Merge branch 'dn2_cleaning' into unstable
Browse files Browse the repository at this point in the history
  • Loading branch information
davidnewhall committed Jul 21, 2024
2 parents 38f920f + a6f807d commit 3c40118
Show file tree
Hide file tree
Showing 17 changed files with 389 additions and 287 deletions.
18 changes: 10 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/Notifiarr/notifiarr/pkg/ui"
)

// @title Notifiarr Client API Docs
// @title Notifiarr Client API Documentation
// @version 1.0
// @description Notifiarr Client monitors local services and sends notifications.
// @termsOfService https://notifiarr.com
Expand All @@ -27,14 +27,16 @@ func main() {
log.SetFlags(log.LstdFlags)
log.SetPrefix("[ERROR] ")

defer func() {
if r := recover(); r != nil {
log.Printf("Go Panic! %s\n%v\n%s", mnd.BugIssue, r, string(debug.Stack()))
}
}()
defer logPanic()

if err := client.Start(); err != nil {
_, _ = ui.Error(mnd.Title, err.Error())
log.Fatal(err) //nolint:gocritic // defer does not need to run if we have an error.
_, _ = ui.Error(err.Error())
defer log.Fatal(err)
}
}

func logPanic() {
if r := recover(); r != nil {
log.Printf("Go Panic! %s\n%v\n%s", mnd.BugIssue, r, string(debug.Stack()))
}
}
2 changes: 1 addition & 1 deletion pkg/bindata/templates/includes/footer.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
</div> <!-- index :: content-wrapper -->
</div> <!-- index :: ts-main-content -->
</div> <!-- index :: page-body -->
<div class="page-footer {{if not .Flags.ConfigFile}}bk-danger{{end}}">
<div class="page-footer{{if not .Flags.ConfigFile}} bk-danger{{end}}">
{{- if not .Flags.ConfigFile}}
<div style="display:none;" class="dialogText">
The application is currently running without a config file. Saving changes is disabled.
Expand Down
15 changes: 1 addition & 14 deletions pkg/client/client_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,17 @@ package client

import (
"context"
"fmt"
"os"
"os/signal"
"syscall"

"github.com/Notifiarr/notifiarr/pkg/website"
)

/*
func (c *Client) handleAptHook() error {
return fmt.Errorf("this feature is not supported on this platform") //nolint:goerr113
}
*/

func (c *Client) handleAptHook(_ context.Context) error {
return fmt.Errorf("this feature is not supported on this platform") //nolint:goerr113
return ErrUnsupport
}

func (c *Client) printUpdateMessage() {}

func (c *Client) upgradeWindows(_, _ interface{}) {}

func (c *Client) AutoWatchUpdate(_ interface{}) {}

func (c *Client) checkReloadSignal(ctx context.Context, sigc os.Signal) error {
return c.reloadConfiguration(ctx, website.EventSignal, "Caught Signal: "+sigc.String())
}
Expand Down
6 changes: 0 additions & 6 deletions pkg/client/client_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,6 @@ func (c *Client) handleAptHook(ctx context.Context) error {
return nil
}

func (c *Client) printUpdateMessage() {}
func (c *Client) upgradeWindows(_, _ interface{}) {}

// AutoWatchUpdate is not used on this OS.
func (c *Client) AutoWatchUpdate(_ interface{}) {}

func (c *Client) checkReloadSignal(ctx context.Context, sigc os.Signal) error {
return c.reloadConfiguration(ctx, website.EventSignal, "Caught Signal: "+sigc.String())
}
Expand Down
19 changes: 7 additions & 12 deletions pkg/client/client_other.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ package client

import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
Expand All @@ -13,26 +12,22 @@ import (
)

// If you need more fake methods, add them.
//

//nolint:gochecknoglobals
var menu = make(map[string]*fakeMenu)

type fakeMenu struct{}

func (f *fakeMenu) Uncheck() {}
func (f *fakeMenu) Check() {}
func (f *fakeMenu) SetTooltip(interface{}) {}
func (f *fakeMenu) Uncheck() {}
func (f *fakeMenu) Check() {}
func (f *fakeMenu) SetTooltip(any) {}

func (c *Client) printUpdateMessage() {}
func (c *Client) setupMenus(interface{}) {}
func (c *Client) startTray(_, _ interface{}) {}
func (c *Client) setupMenus(any) {}
func (c *Client) startTray(_, _ any) {}
func (c *Client) handleAptHook(_ context.Context) error {
return fmt.Errorf("this feature is not supported on this platform") //nolint:goerr113
return ErrUnsupport
}

// AutoWatchUpdate is not used on this OS.
func (c *Client) AutoWatchUpdate(_ interface{}) {}

func (c *Client) checkReloadSignal(ctx context.Context, sigc os.Signal) error {
return c.reloadConfiguration(ctx, website.EventSignal, "Caught Signal: "+sigc.String())
}
Expand Down
146 changes: 2 additions & 144 deletions pkg/client/client_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,157 +2,15 @@ package client

import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"time"

"github.com/Notifiarr/notifiarr/pkg/mnd"
"github.com/Notifiarr/notifiarr/pkg/ui"
"github.com/Notifiarr/notifiarr/pkg/update"
"github.com/Notifiarr/notifiarr/pkg/website"
"github.com/hako/durafmt"
"github.com/kardianos/osext"
"golift.io/version"
)

// WaitTime is how long we wait, after startup, before doing an update check.
const WaitTime = 10 * time.Minute

// This is the pop-up a user sees when they click update in the menu.
func (c *Client) upgradeWindows(ctx context.Context, update *update.Update) {
yes, _ := ui.Question(mnd.Title, "An Update is available! Upgrade Now?\n\n"+
"Your Version: "+version.Version+"-"+version.Revision+"\n"+
"New Version: "+update.Current+"\n"+
"Date: "+update.RelDate.Format("Jan 2, 2006")+mnd.DurationAge(update.RelDate), false)
if yes {
if err := c.updateNow(ctx, update, "user requested"); err != nil {
c.Errorf("Update Failed: %v", err)
_, _ = ui.Error(mnd.Title+" ERROR", "Updating Notifiarr:\n"+err.Error()+"\n")
}
}
}

func (c *Client) printUpdateMessage() {
if !c.Flags.Updated {
return
}

err := ui.Notify(mnd.Title + " updated to version " + version.Version)
if err != nil {
c.Error("Creating Toast Notification:", err)
}
}

func (c *Client) AutoWatchUpdate(ctx context.Context) {
defer c.CapturePanic()

var dur time.Duration

switch c.Config.AutoUpdate {
case "off", "no", "disabled", "disable", "false", "", "-", "0", "0s":
return
case "hourly":
dur = time.Hour
case "daily":
dur = mnd.OneDay
default:
var err error
if dur, err = time.ParseDuration(c.Config.AutoUpdate); err != nil {
dur = mnd.OneDay
break
}

if dur < time.Hour {
dur = time.Hour
}
}

c.startAutoUpdater(ctx, dur)
}

func (c *Client) startAutoUpdater(ctx context.Context, dur time.Duration) {
pfx := ""
if c.Config.UnstableCh {
pfx = "Unstable Channel "
}

time.Sleep(WaitTime)
c.Print(pfx+"Auto-updater started. Check interval:", durafmt.Parse(dur).LimitFirstN(3)) //nolint:mnd

// Check for update on startup.
if err := c.checkAndUpdate(ctx, "startup check"); err != nil {
c.Errorf("Startup-Update Failed: %v", err)
}

ticker := time.NewTicker(dur)
for range ticker.C { // This is a never-ending loop.
if err := c.checkAndUpdate(ctx, "automatic"); err != nil {
c.Errorf("Auto-Update Failed: %v", err)
}
}
}

func (c *Client) checkAndUpdate(ctx context.Context, how string) error {
var (
data *update.Update
err error
)

//nolint:wsl
if c.Config.UnstableCh {
c.Debugf("[cron requested] Checking Unstable website for Update.")
data, err = update.CheckUnstable(ctx, mnd.DefaultName, version.Revision)
} else {
c.Debugf("[cron requested] Checking GitHub for Update.")
data, err = update.CheckGitHub(ctx, mnd.UserRepo, version.Version)
}

if err != nil {
return fmt.Errorf("checking for update: %w", err)
} else if !data.Outdate {
return nil
} else if err = c.updateNow(ctx, data, how); err != nil {
return err
}

return nil
}

func (c *Client) updateNow(ctx context.Context, u *update.Update, msg string) error {
c.Printf("[UPDATE] Downloading and installing update! %s-%s => %s: %s",
version.Version, version.Revision, u.Current, u.CurrURL)

cmd := &update.Command{
URL: u.CurrURL,
Logger: c.Logger.DebugLog,
Args: []string{"--restart", "--config", c.Flags.ConfigFile},
Path: os.Args[0],
}

if path, err := osext.Executable(); err == nil {
cmd.Path = path
}

// This downloads the new file to a temp name in the same folder as the running file.
// Moves the running file to a backup name in the same folder.
// Moves the new file to the same location that the running file was at.
// Triggers another invocation of the app that sleeps 5 seconds then restarts.
backupFile, err := update.Now(ctx, cmd)
if err != nil {
return fmt.Errorf("installing update: %w", err)
}

c.Printf("Update installed to %s restarting! Backup: %s", cmd.Path, backupFile)
// And exit, so we can restart.
c.sigkil <- &update.Signal{Text: "upgrade request: " + msg}

return nil
}

func (c *Client) handleAptHook(_ interface{}) error {
return fmt.Errorf("this feature is not supported on this platform") //nolint:goerr113
func (c *Client) handleAptHook(_ any) error {
return ErrUnsupport
}

func (c *Client) checkReloadSignal(ctx context.Context, sigc os.Signal) error {
Expand Down
23 changes: 12 additions & 11 deletions pkg/client/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ type customReload struct {

// Errors returned by this package.
var (
ErrNilAPIKey = fmt.Errorf("API key may not be empty: set a key in config file, OR with environment variable")
ErrUnsupport = errors.New("this feature is not supported on this platform")
ErrNilAPIKey = errors.New("API key may not be empty: set a key in config file, OR with environment variable")
)

// newDefaults returns a new Client pointer with default settings.
Expand Down Expand Up @@ -160,7 +161,10 @@ func (c *Client) start(ctx context.Context, msg, newPassword string) error {
os.Getpid(), os.Getuid(), os.Getgid(),
version.Started.Format("Mon, Jan 2, 2006 @ 3:04:05 PM MST -0700"))
c.Printf("==> %s", msg)
c.printUpdateMessage()

if c.Flags.Updated {
go ui.Notify(mnd.Title + " updated to version " + version.Version) //nolint:errcheck
}

if err := c.loadAssetsTemplates(ctx); err != nil {
return err
Expand All @@ -171,9 +175,6 @@ func (c *Client) start(ctx context.Context, msg, newPassword string) error {
if newPassword != "" {
// If newPassword is set it means we need to write out a new config file for a new installation. Do that now.
c.makeNewConfigFile(ctx, newPassword)
} else if c.Config.AutoUpdate != "" {
// do not run updater if there's a brand new config file.
go c.AutoWatchUpdate(ctx)
}

if ui.HasGUI() {
Expand All @@ -191,11 +192,11 @@ func (c *Client) makeNewConfigFile(ctx context.Context, newPassword string) {

_, _ = c.Config.Write(ctx, c.Flags.ConfigFile, false)
_ = ui.OpenFile(c.Flags.ConfigFile)
_, _ = ui.Warning(mnd.Title, "A new configuration file was created @ "+
c.Flags.ConfigFile+" - it should open in a text editor. "+
"Please edit the file and reload this application using the tray menu. "+
"Your Web UI password was set to "+newPassword+
" and was also printed in the log file '"+c.Config.LogFile+"' and/or app ouptput.")
_, _ = ui.Warning("A new configuration file was created @ " +
c.Flags.ConfigFile + " - it should open in a text editor. " +
"Please edit the file and reload this application using the tray menu. " +
"Your Web UI password was set to " + newPassword +
" and was also printed in the log file '" + c.Config.LogFile + "' and/or app output.")
}

// loadConfiguration brings in, and sometimes creates, the initial running configuration.
Expand Down Expand Up @@ -259,7 +260,7 @@ func (c *Client) configureServices(ctx context.Context) *clientinfo.ClientInfo {
c.configureServicesPlex(ctx)
c.Config.Snapshot.Validate()
c.PrintStartupInfo(ctx, clientInfo)
c.triggers.Start(ctx, c.sighup)
c.triggers.Start(ctx, c.sighup, c.sigkil)
c.Config.Services.Start(ctx)

return clientInfo
Expand Down
6 changes: 3 additions & 3 deletions pkg/client/tray.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,11 @@ func (c *Client) makeMenus(ctx context.Context, clientInfo *clientinfo.ClientInf
c.debugMenu()

menu["update"] = systray.AddMenuItem("Update", "check GitHub for updated version")
menu["update"].Click(func() { go c.checkForUpdate(ctx, false) })
menu["update"].Click(func() { go c.triggers.AutoUpdate.CheckForUpdate(ctx, false) })

if mnd.IsUnstable || (clientInfo != nil && clientInfo.User.DevAllowed) {
menu["unstable"] = systray.AddMenuItem("Unstable", "check Unstable website for updated version")
menu["unstable"].Click(func() { go c.checkForUpdate(ctx, true) })
menu["unstable"].Click(func() { go c.triggers.AutoUpdate.CheckForUpdate(ctx, true) })
}

menu["gui"] = systray.AddMenuItem("Open WebUI", "open the web page for this Notifiarr client")
Expand All @@ -149,7 +149,7 @@ func (c *Client) configMenu(ctx context.Context) {

menu["view"] = conf.AddSubMenuItem("View", "show configuration")
menu["view"].Click(func() {
go ui.Info(mnd.Title+": Configuration", c.displayConfig())
go ui.Info(c.displayConfig())
})

menu["edit"] = conf.AddSubMenuItem("Edit", "edit configuration")
Expand Down
Loading

0 comments on commit 3c40118

Please sign in to comment.