Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .idea/dictionaries/project.xml

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

15 changes: 14 additions & 1 deletion .idea/inspectionProfiles/Project_Default.xml

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

142 changes: 142 additions & 0 deletions cmd/fhome/cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// Package main provides the implementation of the fhome CLI.
package main

import (
"context"
"encoding/json"
"fmt"
"log/slog"
"os"
"path/filepath"

"github.com/bartekpacia/fhome/api"
)

// cacheDir returns the path to the cache directory.
func cacheDir() (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("failed to get user home directory: %w", err)
}

cacheDir := filepath.Join(homeDir, ".cache", "fhome")
err = os.MkdirAll(cacheDir, 0o755)
if err != nil {
return "", fmt.Errorf("failed to create cache directory: %w", err)
}

return cacheDir, nil
}

// userConfigCachePath returns the path to the user config cache file.
func userConfigCachePath() (string, error) {
dir, err := cacheDir()
if err != nil {
return "", err
}

return filepath.Join(dir, "user_config.json"), nil
}

// readUserConfigFromCache reads the user config from the cache file.
// If the cache file doesn't exist or is invalid, it returns nil and an error.
func readUserConfigFromCache() (*api.UserConfig, error) {
path, err := userConfigCachePath()
if err != nil {
return nil, fmt.Errorf("failed to get cache path: %w", err)
}

data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read cache file: %w", err)
}

var userConfig api.UserConfig
err = json.Unmarshal(data, &userConfig)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal cache file: %w", err)
}

return &userConfig, nil
}

// writeUserConfigToCache writes the user config to the cache file.
func writeUserConfigToCache(userConfig *api.UserConfig) error {
path, err := userConfigCachePath()
if err != nil {
return err
}

data, err := json.Marshal(userConfig)
if err != nil {
return fmt.Errorf("failed to marshal user config: %w", err)
}

err = os.WriteFile(path, data, 0o644)
if err != nil {
return fmt.Errorf("failed to write cache file: %w", err)
}

return nil
}

// updateCache updates the cache in a non-blocking way.
// It returns immediately and updates the cache in a goroutine.
func updateCache(ctx context.Context, createClient func() (*api.Client, error)) {
client, err := createClient()
if err != nil {
slog.Error("failed to create API client: ", slog.Any("error", err))
return
}

userConfig, err := client.GetUserConfig(ctx)
if err != nil {
slog.Error("failed to get user config for cache update", slog.Any("error", err))
return
}

err = writeUserConfigToCache(userConfig)
if err != nil {
slog.Error("failed to write user config to cache", slog.Any("error", err))
return
}

slog.Debug("updated user config cache")
}

// getUserConfig returns the user config, either from cache or from the server.
//
// If the cache exists and is valid, it returns the cached config and updates the cache in the background.
//
// If the cache doesn't exist or is invalid, it calls the provided userConfigGetter to fetch the config
// and updates the cache.
//
// The userConfigGetter is a function that retrieves the user configuration when called.
func getUserConfig(ctx context.Context, createClient func() (*api.Client, error)) (*api.UserConfig, error) {
slog.Debug("getting user config from cache")
userConfig, err := readUserConfigFromCache()
if err == nil {
slog.Debug("cache hit! Starting background update and returning")
go updateCache(ctx, createClient)
return userConfig, nil
}

slog.Debug("cache miss or error, fetching new user config", slog.Any("error", err))
client, err := createClient()
if err != nil {
return nil, fmt.Errorf("failed to create new client: %w", err)
}
userConfig, err = client.GetUserConfig(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get user config: %w", err)
}

// Write to cache
err = writeUserConfigToCache(userConfig)
if err != nil {
slog.Error("failed to write user config to cache", slog.Any("error", err))
// Continue even if cache write fails
}

return userConfig, nil
}
20 changes: 12 additions & 8 deletions cmd/fhome/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -319,14 +319,7 @@ var objectCommand = cli.Command{
}
},
ShellComplete: func(ctx context.Context, cmd *cli.Command) {
config := loadConfig()
client, err := highlevel.Connect(ctx, config, nil)
if err != nil {
panic(err)
}

// TODO: Save to cache because it's slow
userConfig, err := client.GetUserConfig(ctx)
userConfig, err := getUserConfig(ctx, createClientGetter(ctx))
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -414,3 +407,14 @@ var objectCommand = cli.Command{
},
},
}

func createClientGetter(ctx context.Context) func() (*api.Client, error) {
return func() (*api.Client, error) {
config := loadConfig()
client, err := highlevel.Connect(ctx, config, nil)
if err != nil {
return nil, fmt.Errorf("failed to create api client: %v", err)
}
return client, nil
}
}
22 changes: 15 additions & 7 deletions cmd/fhome/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,17 @@ import (
var version = "dev"

func main() {
// Maybe slog setup has to happen outside of Before(), because then it's not run during ShellComplete?
var logLevel slog.Level
if os.Getenv("FHOME_DEBUG") != "" {
logLevel = slog.LevelDebug
} else {
logLevel = slog.LevelInfo
}
handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: logLevel})
_ = slog.New(handler)
// slog.SetDefault(logger)

app := &cli.Command{
Name: "fhome",
Usage: "Interact with smart home devices connected to F&Home",
Expand All @@ -40,20 +51,17 @@ func main() {
},
},
Before: func(ctx context.Context, cmd *cli.Command) (context.Context, error) {
var level slog.Level
if cmd.Bool("debug") || os.Getenv("FHOME_DEBUG") != "" {
level = slog.LevelDebug
} else {
level = slog.LevelInfo
if cmd.Bool("debug") {
logLevel = slog.LevelDebug
}

if cmd.Bool("json") {
opts := slog.HandlerOptions{Level: level}
opts := slog.HandlerOptions{Level: logLevel}
handler := slog.NewJSONHandler(os.Stdout, &opts)
logger := slog.New(handler)
slog.SetDefault(logger)
} else {
opts := tint.Options{Level: level, TimeFormat: time.TimeOnly}
opts := tint.Options{Level: logLevel, TimeFormat: time.TimeOnly}
handler := tint.NewHandler(os.Stdout, &opts)
logger := slog.New(handler)
slog.SetDefault(logger)
Expand Down
3 changes: 2 additions & 1 deletion highlevel/connect.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Package highlevel provides convenient wrappers around some common functionality
// in the api package.
// in the [api] package.
package highlevel

import (
Expand Down Expand Up @@ -46,6 +46,7 @@ func Connect(ctx context.Context, config *Config, dialer *websocket.Dialer) (*ap
slog.String("type", myResources.ResourceType0),
)

slog.Debug("opening client to resource session")
Copy link

Copilot AI Apr 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Consider including additional context details (e.g., resource identifiers) in the debug log to aid troubleshooting.

Suggested change
slog.Debug("opening client to resource session")
slog.Debug("opening client to resource session", slog.String("resourcePassword", config.ResourcePassword))

Copilot uses AI. Check for mistakes.
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

XDD

err = client.OpenResourceSession(ctx, config.ResourcePassword)
if err != nil {
slog.Error("failed to open client to resource session", slog.Any("error", err))
Expand Down