2022-03-24 22:48:51 +00:00
|
|
|
package components
|
|
|
|
|
|
|
|
import (
|
2022-04-07 03:43:09 +00:00
|
|
|
"bytes"
|
2022-03-24 22:48:51 +00:00
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/maxence-charriere/go-app/v9/pkg/app"
|
|
|
|
"go.mills.io/saltyim"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
saltyIdentityKey = "salty-identity"
|
2022-04-07 03:43:09 +00:00
|
|
|
saltyStateKey = "salty-state"
|
2022-03-24 22:48:51 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func GetIdentityFromState(ctx app.Context) (identity *saltyim.Identity, err error) {
|
|
|
|
var identityString string
|
|
|
|
ctx.GetState(saltyIdentityKey, &identityString)
|
|
|
|
if identityString != "" {
|
2022-03-25 05:28:44 +00:00
|
|
|
return saltyim.GetIdentity(saltyim.WithIdentityBytes([]byte(identityString)))
|
2022-03-24 22:48:51 +00:00
|
|
|
}
|
|
|
|
return nil, fmt.Errorf("missing state at key %q", saltyIdentityKey)
|
|
|
|
}
|
|
|
|
|
|
|
|
func SetIdentityToState(ctx app.Context, identity *saltyim.Identity) (err error) {
|
|
|
|
if identity == nil || identity.Contents() == nil || len(identity.Contents()) == 0 {
|
|
|
|
return fmt.Errorf("no identity contents")
|
|
|
|
}
|
|
|
|
ctx.SetState(saltyIdentityKey, string(identity.Contents()), app.Persist, app.Encrypt)
|
|
|
|
return
|
|
|
|
}
|
2022-04-07 03:43:09 +00:00
|
|
|
|
|
|
|
func GetStateFromState(ctx app.Context) (state *saltyim.State, err error) {
|
|
|
|
var stateJson string
|
|
|
|
ctx.GetState(saltyStateKey, &stateJson)
|
|
|
|
if stateJson == "" {
|
|
|
|
return nil, fmt.Errorf("no state found")
|
|
|
|
}
|
|
|
|
return saltyim.LoadState(bytes.NewBufferString(stateJson))
|
|
|
|
}
|
|
|
|
|
|
|
|
func SetStateToState(ctx app.Context, state *saltyim.State) (err error) {
|
|
|
|
jsonBytes, err := state.Bytes()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error serializing state: %w", err)
|
|
|
|
}
|
|
|
|
ctx.SetState(saltyStateKey, string(jsonBytes), app.Persist, app.Encrypt)
|
|
|
|
return
|
|
|
|
}
|