diff --git a/config/config.go b/config/config.go index 8505380..ac94efe 100644 --- a/config/config.go +++ b/config/config.go @@ -1,11 +1,12 @@ package config import ( - "github.com/mitchellh/go-homedir" - "log" - "os" - "encoding/json" - "io/ioutil" + "encoding/json" + "io/ioutil" + "log" + "os" + + "github.com/mitchellh/go-homedir" ) // Config for the application @@ -18,55 +19,57 @@ var Config struct { Exclude string } -const CurrentVersion string = "0.7" +const CurrentVersion string = "0.8" // Load the current config or initialise with defaults func LoadOrInit() { - configPath := configPath() - log.Printf("Trying to load from %s\n", configPath) - _, err := os.Stat(configPath) - if os.IsNotExist(err) { - log.Printf("NOTE: No config file, writing out sample configuration") - log.Printf("You need to set the configuration via the web interface") + configPath := configPath() + log.Printf("Trying to load from %s\n", configPath) + _, err := os.Stat(configPath) + if os.IsNotExist(err) { + log.Printf("NOTE: No config file, writing out sample configuration") + log.Printf("You need to set the configuration via the web interface") - Config.WebHookURL = "" - Config.Path = homeDir() + string(os.PathSeparator) + "screenshots" - Config.Watch = 10 - SaveConfig() - } else { - LoadConfig() - } + Config.WebHookURL = "" + Config.Path = homeDir() + string(os.PathSeparator) + "screenshots" + Config.Watch = 10 + SaveConfig() + } else { + LoadConfig() + } } func LoadConfig() { - path := configPath() - data, err := ioutil.ReadFile(path) - if err != nil { - log.Fatalf("cannot read config file %s: %s", path, err.Error()) - } - err = json.Unmarshal([]byte(data), &Config) - if err != nil { - log.Fatalf("cannot decode config file %s: %s", path, err.Error()) - } + path := configPath() + data, err := ioutil.ReadFile(path) + if err != nil { + log.Fatalf("cannot read config file %s: %s", path, err.Error()) + } + err = json.Unmarshal([]byte(data), &Config) + if err != nil { + log.Fatalf("cannot decode config file %s: %s", path, err.Error()) + } } func SaveConfig() { - log.Print("saving configuration") - path := configPath() - jsonString, _ := json.Marshal(Config) - err := ioutil.WriteFile(path, jsonString, os.ModePerm) - if (err != nil) { - log.Fatalf("Cannot save config %s: %s", path, err.Error()) - } + log.Print("saving configuration") + path := configPath() + jsonString, _ := json.Marshal(Config) + err := ioutil.WriteFile(path, jsonString, os.ModePerm) + if err != nil { + log.Fatalf("Cannot save config %s: %s", path, err.Error()) + } } func homeDir() string { - dir, err := homedir.Dir() - if (err != nil) { panic (err) } - return dir; + dir, err := homedir.Dir() + if err != nil { + panic(err) + } + return dir } func configPath() string { - homeDir := homeDir() - return homeDir + string(os.PathSeparator) + ".dau.json" + homeDir := homeDir() + return homeDir + string(os.PathSeparator) + ".dau.json" } diff --git a/data/config.html b/data/config.html index 42dae1b..6a70450 100644 --- a/data/config.html +++ b/data/config.html @@ -2,7 +2,7 @@

Config

Discord-auto-upload configuration

-

(How to find your discord webhook

+

How to find your discord webhook

diff --git a/data/logs.html b/data/logs.html new file mode 100644 index 0000000..18975ba --- /dev/null +++ b/data/logs.html @@ -0,0 +1,35 @@ + +
+

Config

+

Discord-auto-upload logs

+ + + + + + + + + + +
timeentry
+ +
+ + diff --git a/data/wrapper.tmpl b/data/wrapper.tmpl index 0db420c..745b83b 100644 --- a/data/wrapper.tmpl +++ b/data/wrapper.tmpl @@ -40,6 +40,7 @@ diff --git a/dau.go b/dau.go index f92dbc4..395e961 100644 --- a/dau.go +++ b/dau.go @@ -24,6 +24,7 @@ import ( "github.com/fogleman/gg" "github.com/pborman/getopt" + // "github.com/skratchdot/open-golang/open" "golang.org/x/image/font/inconsolata" @@ -40,11 +41,11 @@ func main() { // log.Print("Opening web browser") // open.Start("http://localhost:9090") - go web.StartWebServer() + web.StartWebServer() checkUpdates() - log.Print("Waiting for images to appear in ", config.Config.Path) + sendLogToWeb(fmt.Sprintf("Waiting for images to appear in %s", config.Config.Path)) // wander the path, forever for { if checkPath(config.Config.Path) { @@ -55,7 +56,7 @@ func main() { } lastCheck = newLastCheck } - log.Printf("sleeping for %ds before next check of %s", config.Config.Watch, config.Config.Path) + sendLogToWeb(fmt.Sprintf("sleeping for %ds before next check of %s", config.Config.Watch, config.Config.Path)) time.Sleep(time.Duration(config.Config.Watch) * time.Second) } } @@ -82,10 +83,12 @@ func checkUpdates() { Body string } + sendLogToWeb("checking for new version") + client := &http.Client{Timeout: time.Second * 5} resp, err := client.Get("https://api.github.com/repos/tardisx/discord-auto-upload/releases/latest") if err != nil { - log.Print("WARNING: Update check failed: ", err) + sendLogToWeb(fmt.Sprintf("WARNING: Update check failed: %v", err)) return } defer resp.Body.Close() @@ -107,6 +110,7 @@ func checkUpdates() { fmt.Println(latest.Body) fmt.Println("------------------------------------") fmt.Println("Upgrade at https://github.com/tardisx/discord-auto-upload/releases/latest") + sendLogToWeb(fmt.Sprintf("New version available: %s - download at https://github.com/tardisx/discord-auto-upload/releases/latest")) } } @@ -136,7 +140,6 @@ func parseOptions() { } func checkFile(path string, f os.FileInfo, err error) error { - if f.ModTime().After(lastCheck) && f.Mode().IsRegular() { if fileEligible(path) { @@ -152,6 +155,13 @@ func checkFile(path string, f os.FileInfo, err error) error { return nil } +func sendLogToWeb(entry string) { + web.LogInput <- web.LogEntry{ + Timestamp: time.Now(), + Entry: entry, + } +} + func fileEligible(file string) bool { if config.Config.Exclude != "" && strings.Contains(file, config.Config.Exclude) { @@ -169,16 +179,16 @@ func fileEligible(file string) bool { func processFile(file string) { if !config.Config.NoWatermark { - log.Print("Copying to temp location and watermarking ", file) + sendLogToWeb("Copying to temp location and watermarking ") file = mungeFile(file) } if config.Config.WebHookURL == "" { - log.Print("WebHookURL is not configured - cannot upload!") + sendLogToWeb("WebHookURL is not configured - cannot upload!") return } - log.Print("Uploading ", file) + sendLogToWeb("Uploading") extraParams := map[string]string{} @@ -264,7 +274,7 @@ func processFile(file string) { } if !config.Config.NoWatermark { - log.Print("Removing temporary file ", file) + sendLogToWeb(fmt.Sprintf("Removing temporary file: %s", file)) os.Remove(file) } @@ -278,7 +288,7 @@ func sleepForRetries(retry int) { return } retryTime := (6-retry)*(6-retry) + 6 - log.Printf("Will retry in %d seconds (%d remaining attempts)", retryTime, retry) + sendLogToWeb(fmt.Sprintf("Will retry in %d seconds (%d remaining attempts)", retryTime, retry)) time.Sleep(time.Duration(retryTime) * time.Second) } diff --git a/web/server.go b/web/server.go index b1e28a7..5c9b990 100644 --- a/web/server.go +++ b/web/server.go @@ -3,8 +3,6 @@ package web import ( "encoding/json" "fmt" - "github.com/tardisx/discord-auto-upload/assets" - "github.com/tardisx/discord-auto-upload/config" "log" "mime" "net/http" @@ -13,6 +11,10 @@ import ( "regexp" "strconv" "text/template" + "time" + + "github.com/tardisx/discord-auto-upload/assets" + "github.com/tardisx/discord-auto-upload/config" ) // DAUWebServer - stuff for the web server @@ -21,23 +23,30 @@ type DAUWebServer struct { } type valueStringResponse struct { - Success bool `json: 'success'` - Value string `json: 'value'` + Success bool `json:"success"` + Value string `json:"value"` } type valueBooleanResponse struct { - Success bool `json: 'success'` - Value bool `json: 'value'` + Success bool `json:"success"` + Value bool `json:"value"` } type errorResponse struct { - Success bool `json: 'success'` - Error string `json: 'error'` + Success bool `json:"success"` + Error string `json:"error"` } +type LogEntry struct { + Timestamp time.Time `json:"ts"` + Entry string `json:"log"` +} + +var logEntries []LogEntry +var LogInput chan LogEntry + func getStatic(w http.ResponseWriter, r *http.Request) { // haha this is dumb and I should change it - // fmt.Println(r.URL) re := regexp.MustCompile(`[^a-zA-Z0-9\.]`) path := r.URL.Path[1:] sanitized_path := re.ReplaceAll([]byte(path), []byte("_")) @@ -270,8 +279,22 @@ func getSetExclude(w http.ResponseWriter, r *http.Request) { } } +func getLogs(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + js, _ := json.Marshal(logEntries) + w.Write(js) +} func StartWebServer() { + // wait for log entries + LogInput = make(chan LogEntry) + go func() { + for { + aLog := <-LogInput + logEntries = append(logEntries, aLog) + } + }() + http.HandleFunc("/", getStatic) http.HandleFunc("/rest/config/webhook", getSetWebhook) http.HandleFunc("/rest/config/username", getSetUsername) @@ -280,11 +303,12 @@ func StartWebServer() { http.HandleFunc("/rest/config/directory", getSetDirectory) http.HandleFunc("/rest/config/exclude", getSetExclude) - - log.Print("Starting web server on http://localhost:9090") - err := http.ListenAndServe(":9090", nil) // set listen port - if err != nil { - log.Fatal("ListenAndServe: ", err) - } - + http.HandleFunc("/rest/logs", getLogs) + go func() { + log.Print("Starting web server on http://localhost:9090") + err := http.ListenAndServe(":9090", nil) // set listen port + if err != nil { + log.Fatal("ListenAndServe: ", err) + } + }() }