1
0
Fork 0
mirror of https://github.com/diamondburned/cchat-gtk.git synced 2024-12-23 20:56:42 +00:00
cchat-gtk/internal/keyring/keyring.go

92 lines
2 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/diamondburned/cchat/text"
2020-06-04 23:00:41 +00:00
"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
func ConvertSession(ses cchat.Session, name string) *Session {
2020-06-07 07:06:13 +00:00
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,
}
}
func SaveSessions(serviceName text.Rich, sessions []Session) {
if err := set(serviceName.Content, 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.
func RestoreSessions(serviceName text.Rich) (sessions []Session) {
2020-06-04 23:00:41 +00:00
// Ignore the error, it's not important.
if err := get(serviceName.Content, &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
}
func RestoreSession(serviceName text.Rich, id string) *Session {
var sessions = RestoreSessions(serviceName)
for _, session := range sessions {
if session.ID == id {
return &session
}
}
return nil
}