From 41869ac03c820c52cb49b00539006cd92f8dd040 Mon Sep 17 00:00:00 2001 From: GP Date: Fri, 28 Jun 2019 10:24:40 +1200 Subject: [PATCH 1/3] updated go-api package --- .goreleaser.yml | 2 +- Gopkg.lock | 45 +++----- downloader.go | 5 +- .../TheCacophonyProject/go-api/Gopkg.lock | 34 +++--- .../TheCacophonyProject/go-api/api.go | 108 ++++++++++-------- .../TheCacophonyProject/go-api/api_test.go | 70 ++++++------ .../TheCacophonyProject/go-api/config.go | 105 +++++++++-------- 7 files changed, 190 insertions(+), 179 deletions(-) diff --git a/.goreleaser.yml b/.goreleaser.yml index e0b9dd4..03aabf7 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -34,4 +34,4 @@ nfpm: - sox bindir: /usr/bin files: - "_release/audiobait.service": "/etc/systemd/system/audiobait.service" + "_release/audiobait.service": "/etc/systemd/system/audiobait.service" \ No newline at end of file diff --git a/Gopkg.lock b/Gopkg.lock index be565f7..82c01db 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -3,102 +3,85 @@ [[projects]] branch = "master" - digest = "1:a10b52a8de7bc2acc45d474b0cc28484be69d2e37470bf76bb20baec08357b63" name = "github.com/TheCacophonyProject/go-api" packages = ["."] - pruneopts = "" - revision = "1ccbd4981ef19335573e6a48c3d69d31fb5514c5" + revision = "f75d610181035080b5552703221d44effc22d2ce" [[projects]] branch = "master" - digest = "1:570dabd29492a1dfc9452ce02719d114570ea75cca59fe276991845a0b3ca836" name = "github.com/TheCacophonyProject/window" packages = ["."] - pruneopts = "" revision = "3a2d74f7fcf50ffc2057a83d74bcb12e0412e348" [[projects]] branch = "master" - digest = "1:c3041f49cae4ad48d7a5ad28a19b57a60e26284cff0af4d4bba3b7ec116e79da" name = "github.com/alexflint/go-arg" packages = ["."] - pruneopts = "" revision = "f7c0423bd11ee80ab81d25c6d46f492998af8547" [[projects]] branch = "master" - digest = "1:d685b3da1fa270912d06e97f577632540a52fcf26048a3a46215c3ce5218e56f" name = "github.com/alexflint/go-scalar" packages = ["."] - pruneopts = "" revision = "e80c3b7ed292b052c7083b6fd7154a8422c33f65" [[projects]] - digest = "1:56c130d885a4aacae1dd9c7b71cfe39912c7ebc1ff7d2b46083c8812996dc43b" name = "github.com/davecgh/go-spew" packages = ["spew"] - pruneopts = "" revision = "346938d642f2ec3594ed81d874461961cd0faa76" version = "v1.1.0" [[projects]] - digest = "1:e772845668c277db6fcc8c6fcf31664c74851f6cce4d225be4f4adbee3861057" name = "github.com/godbus/dbus" packages = ["."] - pruneopts = "" revision = "a389bdde4dd695d414e47b755e95e72b7826432c" version = "v4.1.0" [[projects]] - digest = "1:a4724325f1d3bd4127dac415e980c7c28f2e08f4d0ba2513e7de9980906604ef" name = "github.com/gofrs/flock" packages = ["."] - pruneopts = "" revision = "392e7fae8f1b0bdbd67dad7237d23f618feb6dbb" version = "v0.7.1" [[projects]] - digest = "1:256484dbbcd271f9ecebc6795b2df8cad4c458dd0f5fd82a8c2fa0c29f233411" name = "github.com/pmezard/go-difflib" packages = ["difflib"] - pruneopts = "" revision = "792786c7400a136282c1664665ae0a8db921c6c2" version = "v1.0.0" [[projects]] - digest = "1:c587772fb8ad29ad4db67575dad25ba17a51f072ff18a22b4f0257a4d9c24f75" + name = "github.com/spf13/afero" + packages = [".","mem"] + revision = "588a75ec4f32903aa5e39a2619ba6a4631e28424" + version = "v1.2.2" + +[[projects]] name = "github.com/stretchr/testify" packages = ["assert"] - pruneopts = "" revision = "f35b8ab0b5a2cef36673838d662e249dd9c94686" version = "v1.2.2" +[[projects]] + name = "golang.org/x/text" + packages = ["internal/gen","internal/triegen","internal/ucd","transform","unicode/cldr","unicode/norm"] + revision = "342b2e1fbaa52c93f31447ad2c6abc048c63e475" + version = "v0.3.2" + [[projects]] branch = "v1" - digest = "1:d6dfc13bd1ac289efe8d7d267ccb0d34dc6a6e55703a228cdea1848f5b2dc529" name = "gopkg.in/yaml.v1" packages = ["."] - pruneopts = "" revision = "9f9df34309c04878acc86042b16630b0f696e1de" [[projects]] - digest = "1:cedccf16b71e86db87a24f8d4c70b0a855872eb967cb906a66b95de56aefbd0d" name = "gopkg.in/yaml.v2" packages = ["."] - pruneopts = "" revision = "51d6538a90f86fe93ac480b35f37b2be17fef232" version = "v2.2.2" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - input-imports = [ - "github.com/TheCacophonyProject/go-api", - "github.com/TheCacophonyProject/window", - "github.com/alexflint/go-arg", - "github.com/godbus/dbus", - "github.com/stretchr/testify/assert", - "gopkg.in/yaml.v1", - ] + inputs-digest = "9080b6db80c85ce81a2e774b7b40ef3d31825b1d638acfa41765fc53289c62d7" solver-name = "gps-cdcl" solver-version = 1 diff --git a/downloader.go b/downloader.go index ae74ba3..ecbd097 100644 --- a/downloader.go +++ b/downloader.go @@ -28,9 +28,8 @@ import ( "strconv" "strings" - "github.com/TheCacophonyProject/go-api" - "github.com/TheCacophonyProject/audiobait/playlist" + "github.com/TheCacophonyProject/go-api" ) const scheduleFilename = "schedule.json" @@ -61,7 +60,7 @@ func createAudioPath(audioPath string) error { func tryToInitiateAPI() *api.CacophonyAPI { log.Println("Connecting with API") - api, err := api.NewAPIFromConfig("/etc/thermal-uploader.yaml") + api, err := api.NewAPI()) if err != nil { log.Printf("Failed to connect with API %s", err.Error()) } diff --git a/vendor/github.com/TheCacophonyProject/go-api/Gopkg.lock b/vendor/github.com/TheCacophonyProject/go-api/Gopkg.lock index 41503cd..6dbef57 100644 --- a/vendor/github.com/TheCacophonyProject/go-api/Gopkg.lock +++ b/vendor/github.com/TheCacophonyProject/go-api/Gopkg.lock @@ -2,56 +2,50 @@ [[projects]] - digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec" name = "github.com/davecgh/go-spew" packages = ["spew"] - pruneopts = "UT" revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73" version = "v1.1.1" [[projects]] - digest = "1:d7b2d6ad2a9768bb5c9e3bfa4d9ceaa635ca2737cca288507986f116fa4b8da2" name = "github.com/gofrs/flock" packages = ["."] - pruneopts = "UT" revision = "392e7fae8f1b0bdbd67dad7237d23f618feb6dbb" version = "v0.7.1" [[projects]] - digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe" name = "github.com/pmezard/go-difflib" packages = ["difflib"] - pruneopts = "UT" revision = "792786c7400a136282c1664665ae0a8db921c6c2" version = "v1.0.0" [[projects]] - digest = "1:5da8ce674952566deae4dbc23d07c85caafc6cfa815b0b3e03e41979cedb8750" + name = "github.com/spf13/afero" + packages = [".","mem"] + revision = "588a75ec4f32903aa5e39a2619ba6a4631e28424" + version = "v1.2.2" + +[[projects]] name = "github.com/stretchr/testify" - packages = [ - "assert", - "require", - ] - pruneopts = "UT" + packages = ["assert","require"] revision = "ffdc059bfe9ce6a4e144ba849dbedead332c6053" version = "v1.3.0" [[projects]] - digest = "1:4d2e5a73dc1500038e504a8d78b986630e3626dc027bc030ba5c75da257cdb96" + name = "golang.org/x/text" + packages = ["internal/gen","internal/triegen","internal/ucd","transform","unicode/cldr","unicode/norm"] + revision = "342b2e1fbaa52c93f31447ad2c6abc048c63e475" + version = "v0.3.2" + +[[projects]] name = "gopkg.in/yaml.v2" packages = ["."] - pruneopts = "UT" revision = "51d6538a90f86fe93ac480b35f37b2be17fef232" version = "v2.2.2" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - input-imports = [ - "github.com/gofrs/flock", - "github.com/stretchr/testify/assert", - "github.com/stretchr/testify/require", - "gopkg.in/yaml.v2", - ] + inputs-digest = "e0b0ac92fe67fefc878686b507097fe9b9449f6c81a177e9cfbbe7da42799ada" solver-name = "gps-cdcl" solver-version = 1 diff --git a/vendor/github.com/TheCacophonyProject/go-api/api.go b/vendor/github.com/TheCacophonyProject/go-api/api.go index a33621c..17cba16 100644 --- a/vendor/github.com/TheCacophonyProject/go-api/api.go +++ b/vendor/github.com/TheCacophonyProject/go-api/api.go @@ -44,6 +44,7 @@ type CacophonyDevice struct { group string name string password string + id int } type CacophonyAPI struct { @@ -85,80 +86,85 @@ func (api *CacophonyAPI) JustRegistered() bool { return api.justRegistered } -// NewAPIFromConfig prases the supplied configFile and creates a new CacophonyAPI with the configFile information -// and saves the generated password to privConfigFileName(configFile) -func NewAPIFromConfig(configFile string) (*CacophonyAPI, error) { - conf, err := ParseConfigFile(configFile) +// NewAPI parses device.yaml, and creates a new CacophonyAPI +// and saves the generated password and ID to device-priv.yaml +func NewAPI() (*CacophonyAPI, error) { + conf, err := LoadConfig() if err != nil { return nil, fmt.Errorf("configuration error: %v", err) } - privConfigFilename := privConfigFilename(configFile) - confPassword := NewConfigPassword(privConfigFilename) + return apiFromConfig(conf) +} + +// apiFromConfig creates CacophonyAPI from Config and register/authenticates +// saving the password if necessary +func apiFromConfig(conf *Config) (*CacophonyAPI, error) { - password, err := confPassword.ReadPassword() + lockSafeConfig := NewLockSafeConfig(RegisteredConfigPath) + _, err := lockSafeConfig.Read() if err != nil { return nil, err } - if password == "" { - locked, err := confPassword.GetExLock() + if lockSafeConfig.config == nil || !lockSafeConfig.config.IsValid() { + locked, err := lockSafeConfig.GetExLock() if locked == false || err != nil { return nil, err } - defer confPassword.Unlock() + defer lockSafeConfig.Unlock() - //read again incase was just written to while waiting for exlock - password, err = confPassword.ReadPassword() + //read again in case was just written to while waiting for exlock + _, err = lockSafeConfig.Read() if err != nil { return nil, err } } - api, err := NewAPI(conf.ServerURL, conf.Group, conf.DeviceName, password) - if err != nil { - return nil, err - } - - if api.JustRegistered() { - err := confPassword.WritePassword(api.Password()) - if err != nil { - return nil, err - } - } - return api, nil -} - -// createAPI creates a CacophonyAPI instance and obtains a fresh JSON Web -// Token. If no password is given then the device is registered. -func NewAPI(serverURL, group, deviceName, password string) (*CacophonyAPI, error) { - - if deviceName == "" { - return nil, errors.New("no device name") - } device := &CacophonyDevice{ - group: group, - name: deviceName, - password: password, + group: conf.Group, + name: conf.DeviceName, + } + if lockSafeConfig.config != nil { + device.password = lockSafeConfig.config.Password + device.id = lockSafeConfig.config.DeviceID } api := &CacophonyAPI{ - serverURL: serverURL, + serverURL: conf.ServerURL, device: device, httpClient: newHTTPClient(), } - if device.password == "" { + err = api.registerOrAuthenticate(lockSafeConfig) + return api, err +} + +// createAPI creates a CacophonyAPI instance and obtains a fresh JSON Web +// Token. If no password is given then the device is registered. +func (api *CacophonyAPI) registerOrAuthenticate(lockSafeConfig *LockSafeConfig) error { + if api.device.password == "" { err := api.register() if err != nil { - return nil, err + return err + } + err = lockSafeConfig.Write(api.device.id, api.Password()) + if err != nil { + return err } + } else { err := api.authenticate() if err != nil { - return nil, err + return err + } + if lockSafeConfig.config.DeviceID == 0 && api.device.id > 0 { + err = lockSafeConfig.Write(api.device.id, api.Password()) + if err != nil { + return err + } } } - return api, nil + return nil } // authenticate a device with Cacophony API and retrieves the token @@ -167,10 +173,18 @@ func (api *CacophonyAPI) authenticate() error { if api.device.password == "" { return errors.New("no password set") } - payload, err := json.Marshal(map[string]string{ - "devicename": api.device.name, - "password": api.device.password, - }) + + data := map[string]interface{}{ + "password": api.device.password, + } + if api.device.id > 0 { + data["deviceID"] = api.device.id + } else { + data["devicename"] = api.device.name + data["groupname"] = api.device.group + } + payload, err := json.Marshal(data) + if err != nil { return err } @@ -193,6 +207,7 @@ func (api *CacophonyAPI) authenticate() error { if err := d.Decode(&resp); err != nil { return fmt.Errorf("decode: %v", err) } + api.device.id = resp.ID api.token = resp.Token return nil } @@ -252,7 +267,7 @@ func (api *CacophonyAPI) register() error { if err := d.Decode(&respData); err != nil { return fmt.Errorf("decode: %v", err) } - + api.device.id = respData.ID api.device.password = password api.token = respData.Token api.justRegistered = true @@ -308,6 +323,7 @@ func (api *CacophonyAPI) UploadThermalRaw(r io.Reader) error { type tokenResponse struct { Messages []string Token string + ID int } // message gets the first message of the supplised tokenResponse if present diff --git a/vendor/github.com/TheCacophonyProject/go-api/api_test.go b/vendor/github.com/TheCacophonyProject/go-api/api_test.go index f5e0adc..6dde8ac 100644 --- a/vendor/github.com/TheCacophonyProject/go-api/api_test.go +++ b/vendor/github.com/TheCacophonyProject/go-api/api_test.go @@ -26,6 +26,7 @@ import ( "testing" "time" + "github.com/spf13/afero" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" yaml "gopkg.in/yaml.v2" @@ -78,11 +79,12 @@ func getTokenResponse() *tokenResponse { return &tokenResponse{ Messages: []string{}, Token: "tok-" + randString(20), + ID: 1, } } -func getJSONRequestMap(r *http.Request) map[string]string { - var requestJson = map[string]string{} +func getJSONRequestMap(r *http.Request) map[string]interface{} { + var requestJson map[string]interface{} decoder := json.NewDecoder(r.Body) decoder.Decode(&requestJson) return requestJson @@ -115,7 +117,7 @@ func GetNewAuthenticateServer(t *testing.T) *httptest.Server { assert.Equal(t, http.MethodPost, r.Method) assert.NotEmpty(t, requestJson["password"]) - assert.NotEmpty(t, requestJson["devicename"]) + assert.True(t, (requestJson["groupname"] != "" && requestJson["devicename"] != "") || requestJson["deviceID"] != "") w.WriteHeader(responseHeader) w.Header().Set("Content-Type", "application/json") @@ -220,7 +222,7 @@ func TestAPIReportEvent(t *testing.T) { assert.NoError(t, err) } -func getTempPasswordConfig(t *testing.T) (string, func(), *ConfigPassword, *ConfigPassword) { +func getTempPasswordConfig(t *testing.T) (string, func(), *LockSafeConfig, *LockSafeConfig) { tmpFile, err := ioutil.TempFile("", "test-password") require.NoError(t, err, "Must be able to create test password file") tmpFile.Close() @@ -228,8 +230,8 @@ func getTempPasswordConfig(t *testing.T) (string, func(), *ConfigPassword, *Conf _ = os.Remove(tmpFile.Name()) } - confPassword := NewConfigPassword(tmpFile.Name()) - anotherConfPassword := NewConfigPassword(tmpFile.Name()) + confPassword := NewLockSafeConfig(tmpFile.Name()) + anotherConfPassword := NewLockSafeConfig(tmpFile.Name()) return tmpFile.Name(), cleanUpFunc, confPassword, anotherConfPassword } @@ -239,7 +241,7 @@ func TestPasswordLock(t *testing.T) { defer cleanUp() tempPassword := randString(20) - err := confPassword.WritePassword(tempPassword) + err := confPassword.Write(1, tempPassword) assert.Error(t, err) locked, err := confPassword.GetExLock() @@ -247,20 +249,20 @@ func TestPasswordLock(t *testing.T) { require.True(t, locked, "File lock must succeed") require.NoError(t, err, "must be able to get lock "+filename) - err = confPassword.WritePassword(tempPassword) + err = confPassword.Write(2, tempPassword) require.NoError(t, err, "must be able to write to"+filename) locked, err = anotherConfPassword.GetExLock() assert.Error(t, err) assert.False(t, locked) - err = anotherConfPassword.WritePassword(randString(20)) + err = anotherConfPassword.Write(3, randString(20)) assert.Error(t, err) confPassword.Unlock() - currentPassword, err := confPassword.ReadPassword() + conf, err := confPassword.Read() assert.NoError(t, err) - assert.Equal(t, tempPassword, currentPassword) + assert.Equal(t, tempPassword, conf.Password) tempPassword = randString(20) locked, err = anotherConfPassword.GetExLock() @@ -268,17 +270,18 @@ func TestPasswordLock(t *testing.T) { assert.NoError(t, err) assert.True(t, locked) - err = anotherConfPassword.WritePassword(tempPassword) + err = anotherConfPassword.Write(1, tempPassword) assert.NoError(t, err) - currentPassword, err = anotherConfPassword.ReadPassword() + conf, err = anotherConfPassword.Read() assert.NoError(t, err) - assert.Equal(t, tempPassword, currentPassword) + assert.Equal(t, tempPassword, conf.Password) err = os.Remove(filename) } -func createTestConfig(t *testing.T) (string, func()) { +//createTestConfig creates device.yaml +func createTestConfig(t *testing.T) string { conf := &Config{ ServerURL: apiURL, Group: defaultGroup, @@ -287,16 +290,25 @@ func createTestConfig(t *testing.T) (string, func()) { d, err := yaml.Marshal(conf) require.NoError(t, err, "Must be able to make Config yaml") - tmpFile, err := ioutil.TempFile("", "test-config") - require.NoError(t, err, "Must be able to make test-config") + Fs = afero.NewMemMapFs() + afero.WriteFile(Fs, DeviceConfigPath, d, 0600) - _, err = tmpFile.Write(d) - require.NoError(t, err, "Must be able to write to "+tmpFile.Name()) + return DeviceConfigPath +} - cleanUpFunc := func() { - removeTestConfig(tmpFile.Name()) - } - return tmpFile.Name(), cleanUpFunc +// TestConfigFile test registered config is created with deviceid and password +func TestConfigFile(t *testing.T) { + _ = createTestConfig(t) + _, err := NewAPI() + assert.NoError(t, err) + lockSafeConfig := NewLockSafeConfig(RegisteredConfigPath) + config, err := lockSafeConfig.Read() + require.NoError(t, err, "Must be able to read "+RegisteredConfigPath) + assert.NotEmpty(t, config.Password) + + api, err := NewAPI() + assert.NoError(t, err) + assert.False(t, api.JustRegistered()) } // runMultipleRegistrations registers supplied count APIs with configFile on multiple threads @@ -306,7 +318,7 @@ func runMultipleRegistrations(configFile string, count int) (int, chan string) { for i := 0; i < count; i++ { go func() { - api, err := NewAPIFromConfig(configFile) + api, err := NewAPI() if err != nil { messages <- err.Error() } else { @@ -317,15 +329,8 @@ func runMultipleRegistrations(configFile string, count int) (int, chan string) { return count, messages } -func removeTestConfig(configFile string) { - _ = os.Remove(configFile) - _ = os.Remove(privConfigFilename(configFile)) -} - func TestMultipleRegistrations(t *testing.T) { - configFile, cleanUp := createTestConfig(t) - defer cleanUp() - + configFile := createTestConfig(t) count, passwords := runMultipleRegistrations(configFile, 4) password := <-passwords for i := 1; i < count; i++ { @@ -353,6 +358,7 @@ func getAPI(url, password string, register bool) *CacophonyAPI { api.device.password = randString(20) api.token = "tok-" + randString(20) api.justRegistered = true + api.device.id = 1 } return api } diff --git a/vendor/github.com/TheCacophonyProject/go-api/config.go b/vendor/github.com/TheCacophonyProject/go-api/config.go index b7b489f..45048a2 100644 --- a/vendor/github.com/TheCacophonyProject/go-api/config.go +++ b/vendor/github.com/TheCacophonyProject/go-api/config.go @@ -19,24 +19,40 @@ import ( "context" "errors" "fmt" - "io/ioutil" "os" - "path/filepath" - "strings" "time" "github.com/gofrs/flock" + "github.com/spf13/afero" yaml "gopkg.in/yaml.v2" ) +const ( + DeviceConfigPath = "/etc/cacophony/device.yaml" + RegisteredConfigPath = "/etc/cacophony/device-priv.yaml" +) + type Config struct { - ServerURL string `yaml:"server-url"` - Group string `yaml:"group"` - DeviceName string `yaml:"device-name"` + ServerURL string `yaml:"server-url" json:"serverURL"` + Group string `yaml:"group" json:"groupname"` + DeviceName string `yaml:"device-name" json:"devicename"` } type PrivateConfig struct { Password string `yaml:"password"` + DeviceID int `yaml:"device-id" json:"deviceID"` +} + +//Validate checks supplied Config contains the required data +func (conf *PrivateConfig) IsValid() bool { + if conf.Password == "" { + return false + } + + if conf.DeviceID == 0 { + return false + } + return true } //Validate checks supplied Config contains the required data @@ -44,18 +60,16 @@ func (conf *Config) Validate() error { if conf.ServerURL == "" { return errors.New("server-url missing") } - if conf.Group == "" { - return errors.New("group missing") - } + if conf.DeviceName == "" { return errors.New("device-name missing") } return nil } -//ParseConfig takes supplied filename and returns a parsed Config struct -func ParseConfigFile(filename string) (*Config, error) { - buf, err := ioutil.ReadFile(filename) +// LoadConfig from deviceConfigPath with a read lock +func LoadConfig() (*Config, error) { + buf, err := afero.ReadFile(Fs, DeviceConfigPath) if err != nil { return nil, err } @@ -76,33 +90,39 @@ func ParseConfig(buf []byte) (*Config, error) { } const ( - lockfile = "/var/lock/go-api-config.lock" + lockfile = "/var/lock/go-api-priv.lock" lockRetryDelay = 678 * time.Millisecond lockTimeout = 5 * time.Second ) -type ConfigPassword struct { +// LoadPrivateConfig acquires a readlock and reads private config +func LoadPrivateConfig() (*PrivateConfig, error) { + lockSafeConfig := NewLockSafeConfig(RegisteredConfigPath) + return lockSafeConfig.Read() +} + +type LockSafeConfig struct { fileLock *flock.Flock filename string - password string + config *PrivateConfig } -func NewConfigPassword(filename string) *ConfigPassword { - return &ConfigPassword{ +func NewLockSafeConfig(filename string) *LockSafeConfig { + return &LockSafeConfig{ filename: filename, fileLock: flock.New(lockfile), } } -func (confPassword *ConfigPassword) Unlock() { - confPassword.fileLock.Unlock() +func (lockSafeConfig *LockSafeConfig) Unlock() { + lockSafeConfig.fileLock.Unlock() } // GetExLock acquires an exclusive lock on confPassword -func (confPassword *ConfigPassword) GetExLock() (bool, error) { +func (lockSafeConfig *LockSafeConfig) GetExLock() (bool, error) { lockCtx, cancel := context.WithTimeout(context.Background(), lockTimeout) defer cancel() - locked, err := confPassword.fileLock.TryLockContext(lockCtx, lockRetryDelay) + locked, err := lockSafeConfig.fileLock.TryLockContext(lockCtx, lockRetryDelay) return locked, err } @@ -114,49 +134,42 @@ func getReadLock(fileLock *flock.Flock) (bool, error) { return locked, err } -// ReadPassword acquires a readlock and reads the password -func (confPassword *ConfigPassword) ReadPassword() (string, error) { - locked := confPassword.fileLock.Locked() +// ReadPassword acquires a readlock and reads the config +func (lockSafeConfig *LockSafeConfig) Read() (*PrivateConfig, error) { + locked := lockSafeConfig.fileLock.Locked() if locked == false { - locked, err := getReadLock(confPassword.fileLock) + locked, err := getReadLock(lockSafeConfig.fileLock) if locked == false || err != nil { - return "", err + return nil, err } - defer confPassword.Unlock() + defer lockSafeConfig.Unlock() } - buf, err := ioutil.ReadFile(confPassword.filename) + buf, err := afero.ReadFile(Fs, lockSafeConfig.filename) if os.IsNotExist(err) { - return "", nil + return nil, nil } else if err != nil { - return "", err + return nil, err } - var conf PrivateConfig - if err := yaml.Unmarshal(buf, &conf); err != nil { - return "", err + if err := yaml.Unmarshal(buf, &lockSafeConfig.config); err != nil { + return nil, err } - return conf.Password, nil + return lockSafeConfig.config, nil } // WritePassword checks the file is locked and writes the password -func (confPassword *ConfigPassword) WritePassword(password string) error { - conf := PrivateConfig{Password: password} +func (lockSafeConfig *LockSafeConfig) Write(deviceID int, password string) error { + conf := PrivateConfig{DeviceID: deviceID, Password: password} buf, err := yaml.Marshal(&conf) if err != nil { return err } - if confPassword.fileLock.Locked() { - err = ioutil.WriteFile(confPassword.filename, buf, 0600) + if lockSafeConfig.fileLock.Locked() { + err = afero.WriteFile(Fs, lockSafeConfig.filename, buf, 0600) } else { - return fmt.Errorf("WritePassword could not get file lock %v", confPassword.filename) + return fmt.Errorf("WritePassword could not get file lock %v", lockSafeConfig.filename) } return err } -// privConfigFilename take a configFile and creates an associated -// file to store the password in with suffix -priv.yaml -func privConfigFilename(configFile string) string { - dirname, filename := filepath.Split(configFile) - bareFilename := strings.TrimSuffix(filename, ".yaml") - return filepath.Join(dirname, bareFilename+"-priv.yaml") -} +var Fs = afero.NewOsFs() From b4b2799b1d451647c89ef0b9717f98488f86fcab Mon Sep 17 00:00:00 2001 From: GP Date: Fri, 28 Jun 2019 10:25:46 +1200 Subject: [PATCH 2/3] added missing line in goreleaser.yml --- .goreleaser.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.goreleaser.yml b/.goreleaser.yml index 03aabf7..e0b9dd4 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -34,4 +34,4 @@ nfpm: - sox bindir: /usr/bin files: - "_release/audiobait.service": "/etc/systemd/system/audiobait.service" \ No newline at end of file + "_release/audiobait.service": "/etc/systemd/system/audiobait.service" From b373e7f594643ab8698331b26f558eaeefba78be Mon Sep 17 00:00:00 2001 From: GP Date: Fri, 28 Jun 2019 10:35:27 +1200 Subject: [PATCH 3/3] removed extra ) --- downloader.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/downloader.go b/downloader.go index ecbd097..6e37c26 100644 --- a/downloader.go +++ b/downloader.go @@ -60,7 +60,7 @@ func createAudioPath(audioPath string) error { func tryToInitiateAPI() *api.CacophonyAPI { log.Println("Connecting with API") - api, err := api.NewAPI()) + api, err := api.NewAPI() if err != nil { log.Printf("Failed to connect with API %s", err.Error()) }