mirror of
https://git.mills.io/saltyim/saltyim.git
synced 2024-06-30 18:51:03 +00:00
![James Mills](/assets/img/avatar_default.png)
Co-authored-by: James Mills <1290234+prologic@users.noreply.github.com> Reviewed-on: https://git.mills.io/saltyim/saltyim/pulls/180
99 lines
2.0 KiB
Go
99 lines
2.0 KiB
Go
package saltyim
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"os"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
// WithClientIdentity sets the client's identity
|
|
func WithClientIdentity(options ...IdentityOption) ClientOption {
|
|
return func(cli *Client) error {
|
|
id, err := GetIdentity(options...)
|
|
if err != nil {
|
|
return fmt.Errorf("error loading identity: %w", err)
|
|
}
|
|
cli.id = id
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// WithStateFromFile sets the client's state from a file on disk
|
|
func WithStateFromFile(fn string) ClientOption {
|
|
return func(cli *Client) error {
|
|
f, err := os.Open(fn)
|
|
if err != nil {
|
|
log.WithError(err).Warnf("error opening state file %s, creating an empty state", fn)
|
|
cli.state = NewState()
|
|
return nil
|
|
}
|
|
defer f.Close()
|
|
|
|
s, err := LoadState(f)
|
|
if err != nil {
|
|
return fmt.Errorf("error loading state: %w", err)
|
|
}
|
|
cli.state = s
|
|
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// WithStateFromBytes sets the client's state from a byte array
|
|
func WithStateFromBytes(data []byte) ClientOption {
|
|
return func(cli *Client) error {
|
|
s, err := LoadState(bytes.NewBuffer(data))
|
|
if err != nil {
|
|
return fmt.Errorf("error loading state: %w", err)
|
|
}
|
|
cli.state = s
|
|
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// WithIdentity sets the client's identity from an identity object
|
|
func WithIdentity(id *Identity) ClientOption {
|
|
return func(cli *Client) error {
|
|
cli.id = id
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// WithState sets the client's state from a state object
|
|
func WithState(state *State) ClientOption {
|
|
return func(cli *Client) error {
|
|
cli.state = state
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// WithAddr sets the client's `me` Salty Address
|
|
func WithAddr(me Addr) ClientOption {
|
|
return func(cli *Client) error {
|
|
cli.me = me
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// WithUser sets the client's `me` Salty Address if a non-nil or non-empty and valid
|
|
// Salty Address for `user` is supplifed, otherwise the user in the client's identity
|
|
// is used.
|
|
func WithUser(user string) ClientOption {
|
|
return func(cli *Client) error {
|
|
if user == "" {
|
|
return nil
|
|
}
|
|
|
|
addr, err := ParseAddr(user)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cli.me = addr
|
|
|
|
return nil
|
|
}
|
|
}
|