1
0
Fork 0
mirror of https://github.com/diamondburned/cchat-gtk.git synced 2024-09-28 21:18:56 +00:00
cchat-gtk/internal/keyring/keyring.go

73 lines
1.8 KiB
Go
Raw Normal View History

2020-06-04 23:00:41 +00:00
package keyring
import (
2020-06-07 07:06:13 +00:00
"github.com/diamondburned/cchat"
"github.com/diamondburned/cchat-gtk/internal/keyring/driver"
"github.com/diamondburned/cchat-gtk/internal/keyring/driver/json"
"github.com/diamondburned/cchat-gtk/internal/keyring/driver/keyring"
2020-06-04 23:00:41 +00:00
"github.com/diamondburned/cchat-gtk/internal/log"
"github.com/diamondburned/cchat-gtk/internal/ui/config"
2020-06-04 23:00:41 +00:00
"github.com/pkg/errors"
)
// Declare a keyring store with fallbacks.
var store = driver.NewStore(
keyring.NewProvider(),
json.NewProvider(config.DirPath()), // fallback
)
2020-06-04 23:00:41 +00:00
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
// ConvertSession attempts to get the session data from the given cchat session.
// It returns nil if it can't do it.
func ConvertSession(ses cchat.Session) *Session {
var name = ses.Name().Content
2020-10-15 06:32:11 +00:00
saver := ses.AsSessionSaver()
if saver == nil {
2020-06-07 07:06:13 +00:00
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,
2020-10-15 06:32:11 +00:00
Data: saver.SaveSession(),
2020-06-07 07:06:13 +00:00
}
}
func SaveSessions(service cchat.Service, sessions []Session) {
if err := store.Set(service.Name().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(service cchat.Service) (sessions []Session) {
2020-06-04 23:00:41 +00:00
// Ignore the error, it's not important.
if err := store.Get(service.Name().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(service cchat.Service, id string) *Session {
var sessions = RestoreSessions(service)
for _, session := range sessions {
if session.ID == id {
return &session
}
}
return nil
}