1
0
Fork 0
mirror of https://github.com/diamondburned/cchat-gtk.git synced 2024-11-01 03:54:16 +00:00
cchat-gtk/internal/keyring/keyring.go

81 lines
1.7 KiB
Go
Raw Normal View History

2020-06-04 23:00:41 +00:00
package keyring
import (
"bytes"
"encoding/gob"
"strings"
2020-06-07 07:06:13 +00:00
"github.com/diamondburned/cchat"
2020-06-04 23:00:41 +00:00
"github.com/diamondburned/cchat-gtk/internal/log"
"github.com/pkg/errors"
"github.com/zalando/go-keyring"
)
2020-06-07 04:27:28 +00:00
func get(service string, v interface{}) error {
2020-06-04 23:00:41 +00:00
s, err := keyring.Get("cchat-gtk", service)
if err != nil {
return err
}
// Deleting immediately does not work on a successful start-up.
// keyring.Delete("cchat-gtk", service)
return gob.NewDecoder(strings.NewReader(s)).Decode(v)
}
func set(service string, v interface{}) error {
var b bytes.Buffer
if err := gob.NewEncoder(&b).Encode(v); err != nil {
return err
}
return keyring.Set("cchat-gtk", service, b.String())
}
2020-06-07 04:27:28 +00:00
type Session struct {
ID string
Name string
Data map[string]string
}
2020-06-04 23:00:41 +00:00
2020-06-07 07:06:13 +00:00
func GetSession(ses cchat.Session, name string) *Session {
saver, ok := ses.(cchat.SessionSaver)
if !ok {
return nil
}
s, err := saver.Save()
if err != nil {
log.Error(errors.Wrapf(err, "Failed to save session ID %s (%s)", ses.ID(), name))
return nil
}
// Treat the ID as name if none is provided. This is a shitty hack around
// backends that only set the name after returning.
if name == "" {
name = ses.ID()
}
return &Session{
ID: ses.ID(),
Name: name,
Data: s,
}
}
2020-06-07 04:27:28 +00:00
func SaveSessions(serviceName string, sessions []Session) {
if err := set(serviceName, sessions); err != nil {
2020-06-04 23:00:41 +00:00
log.Warn(errors.Wrap(err, "Error saving session"))
}
}
// RestoreSessions restores all sessions of the service asynchronously, then
// calls the auth callback inside the Gtk main thread.
2020-06-07 04:27:28 +00:00
func RestoreSessions(serviceName string) (sessions []Session) {
2020-06-04 23:00:41 +00:00
// Ignore the error, it's not important.
2020-06-07 04:27:28 +00:00
if err := get(serviceName, &sessions); err != nil {
2020-06-04 23:00:41 +00:00
log.Warn(err)
}
2020-06-07 04:27:28 +00:00
return
2020-06-04 23:00:41 +00:00
}