11package main
22
33import (
4+ "io/ioutil"
45 "os"
6+ "os/user"
7+ "path/filepath"
8+
9+ yaml "gopkg.in/yaml.v1"
510
611 "github.com/gotk3/gotk3/gtk"
712 "github.com/mcuadros/OctoPrint-TFT/ui"
813)
914
1015const (
11- EnvStylePath = "OCTOPRINT_TFT_STYLE_PATH"
12- EnvBaseURL = "OCTOPRINT_HOST"
13- EnvAPIKey = "OCTOPRINT_APIKEY"
16+ EnvStylePath = "OCTOPRINT_TFT_STYLE_PATH"
17+ EnvBaseURL = "OCTOPRINT_HOST"
18+ EnvAPIKey = "OCTOPRINT_APIKEY"
19+ EnvConfigFile = "OCTOPRINT_CONFIG_FILE"
1420
15- DefaultBaseURL = "http://127.0.0.1 "
21+ DefaultBaseURL = "http://localhost "
1622)
1723
1824var (
19- BaseURL string
20- APIKey string
25+ BaseURL string
26+ APIKey string
27+ ConfigFile string
2128)
2229
2330func init () {
2431 ui .StylePath = os .Getenv (EnvStylePath )
25- BaseURL = os .Getenv (EnvBaseURL )
2632 APIKey = os .Getenv (EnvAPIKey )
33+
34+ BaseURL = os .Getenv (EnvBaseURL )
2735 if BaseURL == "" {
2836 BaseURL = DefaultBaseURL
2937 }
38+
39+ ConfigFile = os .Getenv (EnvConfigFile )
40+ if ConfigFile == "" {
41+ ConfigFile = findConfigFile ()
42+ }
43+
44+ if APIKey != "" && ConfigFile != "" {
45+ APIKey = readAPIKey (ConfigFile )
46+ ui .Logger .Infof ("Found API key at %q file" , ConfigFile )
47+ }
3048}
3149
3250func main () {
@@ -38,3 +56,48 @@ func main() {
3856 ui .New (BaseURL , APIKey )
3957 gtk .Main ()
4058}
59+
60+ var (
61+ configLocation = ".octoprint/config.yaml"
62+ homeOctoPi = "/home/pi/"
63+ )
64+
65+ func readAPIKey (config string ) string {
66+ var cfg struct { API struct { Key string } }
67+
68+ data , err := ioutil .ReadFile (config )
69+ if err != nil {
70+ ui .Logger .Fatal (err )
71+ return ""
72+ }
73+
74+ if err := yaml .Unmarshal ([]byte (data ), & cfg ); err != nil {
75+ ui .Logger .Fatalf ("Error decoding YAML config file %q: %s" , config , err )
76+ return ""
77+ }
78+
79+ return cfg .API .Key
80+ }
81+
82+ func findConfigFile () string {
83+ if file := doFindConfigFile (homeOctoPi ); file != "" {
84+ return file
85+ }
86+
87+ usr , err := user .Current ()
88+ if err != nil {
89+ return ""
90+ }
91+
92+ return doFindConfigFile (usr .HomeDir )
93+ }
94+
95+ func doFindConfigFile (home string ) string {
96+ path := filepath .Join (home , configLocation )
97+
98+ if _ , err := os .Stat (path ); err == nil {
99+ return path
100+ }
101+
102+ return ""
103+ }
0 commit comments