Skip to content

Commit

Permalink
refactor(all): ♻️ registration code clean-up
Browse files Browse the repository at this point in the history
remove unneeded interfaces; simplify registration logic
  • Loading branch information
joshuar committed Jan 12, 2024
1 parent 00dbc00 commit f8fc98d
Show file tree
Hide file tree
Showing 8 changed files with 67 additions and 278 deletions.
26 changes: 12 additions & 14 deletions internal/agent/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,14 @@ func saveRegistration(cfg config.Config, r *api.RegistrationResponse, d api.Devi
// registration details and save the results into the agent config.
func (agent *Agent) performRegistration(ctx context.Context, cfg config.Config) {
log.Info().Msg("Registration required. Starting registration process.")
if agent.options.Server != "" {
if !validateRegistrationSetting("server", agent.options.Server) {
log.Fatal().Msg("Server setting is not valid.")
} else if err := cfg.Set(config.PrefHost, agent.options.Server); err != nil {
log.Fatal().Err(err).Msg("Could not set host preference.")
}
if !validRegistrationSetting("server", agent.options.Server) || !validRegistrationSetting("token", agent.options.Token) {
log.Fatal().Msg("Cannot register, invalid host and/or token.")
}
if agent.options.Token != "" {
if !validateRegistrationSetting("token", agent.options.Token) {
log.Fatal().Msg("Token setting is not valid.")
} else if err := cfg.Set(config.PrefToken, agent.options.Token); err != nil {
log.Fatal().Err(err).Msg("Could not set token preference.")
}
if err := cfg.Set(config.PrefHost, agent.options.Server); err != nil {
log.Fatal().Err(err).Msg("Could not set host preference.")
}
if err := cfg.Set(config.PrefToken, agent.options.Token); err != nil {
log.Fatal().Err(err).Msg("Could not set token preference.")
}

device := newDevice(ctx)
Expand All @@ -76,7 +71,7 @@ func (agent *Agent) performRegistration(ctx context.Context, cfg config.Config)
agent.ui.DisplayRegistrationWindow(ctx, agent, cfg, userInputDone)
<-userInputDone
}
resp, err := api.RegisterWithHass(ctx, cfg, device)
resp, err := api.RegisterWithHass(ctx, agent.options.Server, agent.options.Token, device)
if err != nil {
log.Fatal().Err(err).Msg("Could not register with Home Assistant.")
}
Expand Down Expand Up @@ -104,7 +99,10 @@ func (agent *Agent) checkRegistration(t *tracker.SensorTracker, c config.Config)
}
}

func validateRegistrationSetting(key, value string) bool {
func validRegistrationSetting(key, value string) bool {
if value == "" {
return false
}
validate := validator.New()
check := func(value string, validation string) bool {
if err := validate.Var(value, validation); err != nil {
Expand Down
10 changes: 5 additions & 5 deletions internal/agent/ui/fyneUI/fyneUI.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ func (i *fyneUI) DisplayRegistrationWindow(ctx context.Context, agent ui.Agent,

var allFormItems []*widget.FormItem

allFormItems = append(allFormItems, i.serverConfigItems(ctx, agent, cfg, i.text)...)
allFormItems = append(allFormItems, serverConfigItems(ctx, agent, cfg, i.text)...)
registrationForm := widget.NewForm(allFormItems...)
registrationForm.OnSubmit = func() {
w.Close()
Expand Down Expand Up @@ -297,13 +297,13 @@ func (i *fyneUI) agentSettingsWindow(agent ui.Agent, t *translations.Translator)

// serverConfigItems generates a list of form item widgets for selecting a
// server to register the agent against.
func (i *fyneUI) serverConfigItems(ctx context.Context, agent ui.Agent, cfg config.Config, t *translations.Translator) []*widget.FormItem {
func serverConfigItems(ctx context.Context, agent ui.Agent, cfg config.Config, t *translations.Translator) []*widget.FormItem {
allServers := hass.FindServers(ctx)

tokenEntry := configEntry(agent, cfg, config.PrefToken, "ASecretLongLivedToken", false)
tokenEntry := configEntry(cfg, config.PrefToken, "ASecretLongLivedToken", false)
tokenEntry.Validator = validation.NewRegexp("[A-Za-z0-9_\\.]+", "Invalid token format")

serverEntry := configEntry(agent, cfg, config.PrefHost, allServers[0], false)
serverEntry := configEntry(cfg, config.PrefHost, allServers[0], false)
serverEntry.Validator = httpValidator()
serverEntry.Disable()

Expand Down Expand Up @@ -378,7 +378,7 @@ func (i *fyneUI) serverConfigItems(ctx context.Context, agent ui.Agent, cfg conf
// configEntry creates a form entry widget that is tied to the given config
// value of the given agent. When the value of the entry widget changes, the
// corresponding config value will be updated.
func configEntry(agent ui.Agent, cfg config.Config, name, placeholder string, secret bool) *widget.Entry {
func configEntry(cfg config.Config, name, placeholder string, secret bool) *widget.Entry {
var entry *widget.Entry
if secret {
entry = widget.NewPasswordEntry()
Expand Down
11 changes: 0 additions & 11 deletions internal/hass/api/config.go

This file was deleted.

80 changes: 0 additions & 80 deletions internal/hass/api/mock_AgentConfig_test.go

This file was deleted.

80 changes: 0 additions & 80 deletions internal/hass/api/mock_Agent_test.go

This file was deleted.

6 changes: 3 additions & 3 deletions internal/hass/api/mock_DeviceInfo_test.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 8 additions & 17 deletions internal/hass/api/registration.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,18 @@ package api

import (
"context"
"errors"
"net/url"
"time"

"github.com/carlmjohnson/requests"
"github.com/joshuar/go-hass-agent/internal/agent/config"
"github.com/rs/zerolog/log"
)

const (
websocketPath = "/api/websocket"
webHookPath = "/api/webhook/"
websocketPath = "/api/websocket"
webHookPath = "/api/webhook/"
registrationPath = "/api/mobile_app/registrations"
authHeader = "Authorization"
)

//go:generate moq -out mock_RegistrationInfo_test.go . RegistrationInfo
Expand Down Expand Up @@ -86,33 +86,24 @@ type RegistrationRequest struct {
SupportsEncryption bool `json:"supports_encryption"`
}

func RegisterWithHass(ctx context.Context, cfg config.Config, device DeviceInfo) (*RegistrationResponse, error) {
func RegisterWithHass(ctx context.Context, server, token string, device DeviceInfo) (*RegistrationResponse, error) {
request, err := device.MarshalJSON()
if err != nil {
return nil, err
}
var u string
if err = cfg.Get(config.PrefHost, &u); err != nil {
return nil, errors.New("invalid host")
}

serverURL, err := url.Parse(u)
serverURL, err := url.Parse(server)
if err != nil {
return nil, err
}
serverURL = serverURL.JoinPath("/api/mobile_app/registrations")

var token string
if err = cfg.Get(config.PrefToken, &token); err != nil || token == "" {
return nil, errors.New("invalid token")
}
serverURL = serverURL.JoinPath(registrationPath)

var response *RegistrationResponse
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
err = requests.
URL(serverURL.String()).
Header("Authorization", "Bearer "+token).
Header(authHeader, "Bearer "+token).
BodyBytes(request).
ToJSON(&response).
Fetch(ctx)
Expand Down
Loading

0 comments on commit f8fc98d

Please sign in to comment.