2022-07-17 17:22:28 -04:00
|
|
|
package matrixbotlib
|
|
|
|
|
|
|
|
import (
|
2023-10-12 20:51:08 -04:00
|
|
|
"errors"
|
2022-07-17 17:22:28 -04:00
|
|
|
"os"
|
|
|
|
|
2023-10-12 20:51:08 -04:00
|
|
|
"github.com/kelseyhightower/envconfig"
|
2022-07-17 17:22:28 -04:00
|
|
|
"gopkg.in/yaml.v2"
|
|
|
|
)
|
|
|
|
|
2023-10-12 20:51:08 -04:00
|
|
|
// MatrixClientConfig represents the config requires to log into the matrix server
|
2022-07-17 17:22:28 -04:00
|
|
|
type MatrixClientConfig struct {
|
2023-10-12 20:51:08 -04:00
|
|
|
Homeserver string `required:"true" yaml:"homeserver"`
|
|
|
|
Domain string `required:"true" yaml:"domain"`
|
2022-07-17 17:22:28 -04:00
|
|
|
Dimension string `yaml:"dimension"`
|
2023-10-12 20:51:08 -04:00
|
|
|
Username string `required:"true" yaml:"username"`
|
|
|
|
Password string `required:"true" yaml:"password"`
|
2022-07-17 17:22:28 -04:00
|
|
|
Statefile string `yaml:"statefile,omitempty"`
|
|
|
|
Token string `yaml:"token"`
|
|
|
|
filename string
|
|
|
|
}
|
|
|
|
|
2023-10-12 20:51:08 -04:00
|
|
|
// LoadMatrixClientConfig reads info from a file
|
2022-07-17 17:22:28 -04:00
|
|
|
func LoadMatrixClientConfig(filename string) (*MatrixClientConfig, error) {
|
2023-10-12 20:51:08 -04:00
|
|
|
cnf := MatrixClientConfig{}
|
|
|
|
if filename != "" {
|
|
|
|
yamlFile, err := os.ReadFile(filename)
|
|
|
|
if err == nil {
|
|
|
|
err = yaml.Unmarshal(yamlFile, &cnf)
|
|
|
|
} else {
|
|
|
|
return &cnf, err
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return &cnf, err
|
|
|
|
}
|
|
|
|
cnf.filename = filename
|
2022-07-17 17:22:28 -04:00
|
|
|
} else {
|
2023-10-12 20:51:08 -04:00
|
|
|
err := envconfig.Process("matrix", &cnf)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-07-17 17:22:28 -04:00
|
|
|
}
|
2023-10-12 20:51:08 -04:00
|
|
|
return &cnf, nil
|
2022-07-17 17:22:28 -04:00
|
|
|
}
|
|
|
|
|
2023-10-12 20:51:08 -04:00
|
|
|
// WriteMatrixClientConfig saves current running config to a file
|
2022-07-17 17:22:28 -04:00
|
|
|
func WriteMatrixClientConfig(cnf *MatrixClientConfig) error {
|
2023-10-12 20:51:08 -04:00
|
|
|
if cnf.filename == "" {
|
|
|
|
return errors.New("not loaded from config file")
|
|
|
|
}
|
|
|
|
file, err := os.OpenFile(cnf.filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
|
2022-07-17 17:22:28 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
enc := yaml.NewEncoder(file)
|
|
|
|
|
|
|
|
err = enc.Encode(cnf)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|