Read/Write config to $HOME

This commit is contained in:
Justin Hawkins 2021-02-07 11:42:13 +10:30
parent ec658520b7
commit 851f073e99
6 changed files with 110 additions and 31 deletions

View File

@ -1,5 +1,13 @@
package config package config
import (
"github.com/mitchellh/go-homedir"
"log"
"os"
"encoding/json"
"io/ioutil"
)
// Config for the application // Config for the application
var Config struct { var Config struct {
WebHookURL string WebHookURL string
@ -11,3 +19,52 @@ var Config struct {
} }
const CurrentVersion string = "0.6" const CurrentVersion string = "0.6"
// 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("Initialising empty config")
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())
}
}
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())
}
}
func homeDir() string {
dir, err := homedir.Dir()
if (err != nil) { panic (err) }
return dir;
}
func configPath() string {
homeDir := homeDir()
return homeDir + string(os.PathSeparator) + ".dau.json"
}

View File

@ -70,8 +70,9 @@
</div> </div>
<div class="col-sm-4 my-1"> <div class="col-sm-4 my-1">
<div class="custom-control custom-switch"> <div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input rest-field rest-field-boolean" id="customSwitch1"> <input type="checkbox" class="custom-control-input rest-field rest-field-boolean" id="input-nowatermark">
<label class="custom-control-label" for="customSwitch1"><span style="display: none;">😭</span></label> <label class="custom-control-label" for="input-nowatermark">&nbsp;</label>
<span id="sadness" style="">😭</span>
</div> </div>
</div> </div>
<div class="col-auto my-1"> <div class="col-auto my-1">
@ -87,7 +88,18 @@
<script> <script>
function update_sadness () {
if ($('#input-nowatermark').prop('checked')) {
$('#sadness').css('visibility','');
}
else {
$('#sadness').css('visibility','hidden');
}
}
$(document).ready(function() { $(document).ready(function() {
$('#input-nowatermark').on('click', function() { update_sadness(); });
// populate each field // populate each field
$('.config-item').each(function() { $('.config-item').each(function() {
let el = $(this); let el = $(this);
@ -102,6 +114,8 @@ $(document).ready(function() {
else { else {
this_el.val(data.Value); this_el.val(data.Value);
} }
update_sadness();
}); });
}); });
@ -109,7 +123,7 @@ $(document).ready(function() {
$('.config-item button').on('click', function(e,f) { $('.config-item button').on('click', function(e,f) {
key = $(this).parents('.config-item').data('key'); key = $(this).parents('.config-item').data('key');
val = $(this).parents('.config-item').find('.rest-field').val(); val = $(this).parents('.config-item').find('.rest-field').val();
if ($(this).parents('.config-item').find('.rest-field-boolean')) { if ($(this).parents('.config-item').find('.rest-field-boolean').length) {
val = $(this).parents('.config-item').find('.rest-field').prop('checked') ? 1 : 0; val = $(this).parents('.config-item').find('.rest-field').prop('checked') ? 1 : 0;
} }
$.post('/rest/config/'+key, { value: val }) $.post('/rest/config/'+key, { value: val })

52
dau.go
View File

@ -37,7 +37,6 @@ var newLastCheck = time.Now()
func main() { func main() {
parseOptions() parseOptions()
checkPath(config.Config.Path)
// log.Print("Opening web browser") // log.Print("Opening web browser")
// open.Start("http://localhost:9090") // open.Start("http://localhost:9090")
@ -48,26 +47,30 @@ func main() {
log.Print("Waiting for images to appear in ", config.Config.Path) log.Print("Waiting for images to appear in ", config.Config.Path)
// wander the path, forever // wander the path, forever
for { for {
err := filepath.Walk(config.Config.Path, if checkPath(config.Config.Path) {
func(path string, f os.FileInfo, err error) error { return checkFile(path, f, err) }) err := filepath.Walk(config.Config.Path,
if err != nil { func(path string, f os.FileInfo, err error) error { return checkFile(path, f, err) })
log.Fatal("could not watch path", err) if err != nil {
log.Fatal("could not watch path", err)
}
lastCheck = newLastCheck
} }
lastCheck = newLastCheck
log.Print("sleeping before next check") log.Print("sleeping before next check")
time.Sleep(time.Duration(config.Config.Watch) * time.Second) time.Sleep(time.Duration(config.Config.Watch) * time.Second)
} }
} }
func checkPath(path string) { func checkPath(path string) bool {
src, err := os.Stat(path) src, err := os.Stat(path)
if err != nil { if err != nil {
log.Fatal(err) log.Println("path problem: ", err)
return false
} }
if !src.IsDir() { if !src.IsDir() {
log.Fatal(path, " is not a directory") log.Println(path, " is not a directory")
os.Exit(1) return false
} }
return true
} }
func checkUpdates() { func checkUpdates() {
@ -111,12 +114,7 @@ func checkUpdates() {
func parseOptions() { func parseOptions() {
// Declare the flags to be used // Declare the flags to be used
webhookFlag := getopt.StringLong("webhook", 'w', "", "discord webhook URL")
pathFlag := getopt.StringLong("directory", 'd', "", "directory to scan, optional, defaults to current directory")
watchFlag := getopt.Int16Long("watch", 's', 10, "time between scans")
usernameFlag := getopt.StringLong("username", 'u', "", "username for the bot upload")
excludeFlag := getopt.StringLong("exclude", 'x', "", "exclude files containing this string") excludeFlag := getopt.StringLong("exclude", 'x', "", "exclude files containing this string")
noWatermarkFlag := getopt.BoolLong("no-watermark", 'n', "do not put a watermark on images before uploading")
helpFlag := getopt.BoolLong("help", 'h', "help") helpFlag := getopt.BoolLong("help", 'h', "help")
versionFlag := getopt.BoolLong("version", 'v', "show version") versionFlag := getopt.BoolLong("version", 'v', "show version")
getopt.SetParameters("") getopt.SetParameters("")
@ -134,22 +132,15 @@ func parseOptions() {
os.Exit(0) os.Exit(0)
} }
if !getopt.IsSet("directory") { // if !getopt.IsSet("webhook") {
*pathFlag = "./" // log.Fatal("ERROR: You must specify a --webhook URL")
log.Println("Defaulting to current directory") // }
}
if !getopt.IsSet("webhook") { // grab the config
log.Fatal("ERROR: You must specify a --webhook URL") config.LoadOrInit()
}
config.Config.Path = *pathFlag // overrides from command line
config.Config.WebHookURL = *webhookFlag
config.Config.Watch = int(*watchFlag)
config.Config.Username = *usernameFlag
config.Config.NoWatermark = *noWatermarkFlag
config.Config.Exclude = *excludeFlag config.Config.Exclude = *excludeFlag
} }
func checkFile(path string, f os.FileInfo, err error) error { func checkFile(path string, f os.FileInfo, err error) error {
@ -190,6 +181,11 @@ func processFile(file string) {
file = mungeFile(file) file = mungeFile(file)
} }
if config.Config.WebHookURL == "" {
log.Print("WebHookURL is not configured - cannot upload!")
return
}
log.Print("Uploading ", file) log.Print("Uploading ", file)
extraParams := map[string]string{} extraParams := map[string]string{}

1
go.mod
View File

@ -5,6 +5,7 @@ go 1.15
require ( require (
github.com/fogleman/gg v1.3.0 github.com/fogleman/gg v1.3.0
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
github.com/mitchellh/go-homedir v1.1.0
github.com/pborman/getopt v1.1.0 github.com/pborman/getopt v1.1.0
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966
golang.org/x/image v0.0.0-20201208152932-35266b937fa6 golang.org/x/image v0.0.0-20201208152932-35266b937fa6

2
go.sum
View File

@ -2,6 +2,8 @@ github.com/fogleman/gg v1.3.0 h1:/7zJX8F6AaYQc57WQCyN9cAIz+4bCJGO9B+dyW29am8=
github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/pborman/getopt v1.1.0 h1:eJ3aFZroQqq0bWmraivjQNt6Dmm5M0h2JcDW38/Azb0= github.com/pborman/getopt v1.1.0 h1:eJ3aFZroQqq0bWmraivjQNt6Dmm5M0h2JcDW38/Azb0=
github.com/pborman/getopt v1.1.0/go.mod h1:FxXoW1Re00sQG/+KIkuSqRL/LwQgSkv7uyac+STFsbk= github.com/pborman/getopt v1.1.0/go.mod h1:FxXoW1Re00sQG/+KIkuSqRL/LwQgSkv7uyac+STFsbk=
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 h1:JIAuq3EEf9cgbU6AtGPK4CTG3Zf6CKMNqf0MHTggAUA= github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 h1:JIAuq3EEf9cgbU6AtGPK4CTG3Zf6CKMNqf0MHTggAUA=

View File

@ -93,6 +93,7 @@ func getSetWebhook(w http.ResponseWriter, r *http.Request) {
log.Fatal(err) log.Fatal(err)
} }
config.Config.WebHookURL = r.PostForm.Get("value") config.Config.WebHookURL = r.PostForm.Get("value")
config.SaveConfig()
postResponse := valueStringResponse{Success: true, Value: config.Config.WebHookURL} postResponse := valueStringResponse{Success: true, Value: config.Config.WebHookURL}
js, _ := json.Marshal(postResponse) js, _ := json.Marshal(postResponse)
@ -116,6 +117,8 @@ func getSetUsername(w http.ResponseWriter, r *http.Request) {
log.Fatal(err) log.Fatal(err)
} }
config.Config.Username = r.PostForm.Get("value") config.Config.Username = r.PostForm.Get("value")
config.SaveConfig()
postResponse := valueStringResponse{Success: true, Value: config.Config.Username} postResponse := valueStringResponse{Success: true, Value: config.Config.Username}
js, _ := json.Marshal(postResponse) js, _ := json.Marshal(postResponse)
@ -155,6 +158,8 @@ func getSetWatch(w http.ResponseWriter, r *http.Request) {
} }
config.Config.Watch = i config.Config.Watch = i
config.SaveConfig()
postResponse := valueStringResponse{Success: true, Value: strconv.Itoa(config.Config.Watch)} postResponse := valueStringResponse{Success: true, Value: strconv.Itoa(config.Config.Watch)}
js, _ := json.Marshal(postResponse) js, _ := json.Marshal(postResponse)
@ -191,6 +196,8 @@ func getSetNoWatermark(w http.ResponseWriter, r *http.Request) {
} else { } else {
config.Config.NoWatermark = true config.Config.NoWatermark = true
} }
config.SaveConfig()
postResponse := valueBooleanResponse{Success: true, Value: config.Config.NoWatermark} postResponse := valueBooleanResponse{Success: true, Value: config.Config.NoWatermark}
js, _ := json.Marshal(postResponse) js, _ := json.Marshal(postResponse)
@ -232,6 +239,8 @@ func getSetDirectory(w http.ResponseWriter, r *http.Request) {
} }
config.Config.Path = newPath config.Config.Path = newPath
config.SaveConfig()
postResponse := valueStringResponse{Success: true, Value: config.Config.Path} postResponse := valueStringResponse{Success: true, Value: config.Config.Path}
js, _ := json.Marshal(postResponse) js, _ := json.Marshal(postResponse)