diff options
Diffstat (limited to 'persistence/sessions.go')
-rw-r--r-- | persistence/sessions.go | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/persistence/sessions.go b/persistence/sessions.go new file mode 100644 index 0000000..50e3f3e --- /dev/null +++ b/persistence/sessions.go @@ -0,0 +1,69 @@ +package persistence + +import ( + "github.com/pkg/errors" + "io/ioutil" + + "dev.narayana.im/narayana/telegabber/yamldb" + + "gopkg.in/yaml.v2" +) + +// SessionsYamlDB wraps YamlDB with Session +type SessionsYamlDB struct { + yamldb.YamlDB + Data *SessionsMap +} + +// SessionsMap is for :sessions: subtree +type SessionsMap struct { + Sessions map[string]Session `yaml:":sessions"` +} + +// Session is a key-values subtree +type Session struct { + Login string `yaml:":login"` +} + +var sessionDB SessionsYamlDB + +// Marshaller implementation for YamlDB +func Marshaller() ([]byte, error) { + return yaml.Marshal(sessionDB.Data) +} + +// LoadSessions restores TDlib sessions from the previous run +func LoadSessions(path string) (SessionsYamlDB, error) { + var sessionData SessionsMap + + sessionDB, err := initYamlDB(path, &sessionData) + if err != nil { + return sessionDB, errors.Wrap(err, "Sessions restore error") + } + + sessionDB.Transaction(func() { + }, Marshaller) + + return sessionDB, nil +} + +func initYamlDB(path string, dataPtr *SessionsMap) (SessionsYamlDB, error) { + file, err := ioutil.ReadFile(path) + if err == nil { + err = yaml.Unmarshal(file, dataPtr) + if err != nil { + return SessionsYamlDB{}, errors.Wrap(err, "YamlDB is corrupted") + } + } else { + // DB file does not exist, create an empty DB + dataPtr.Sessions = make(map[string]Session) + } + + return SessionsYamlDB{ + YamlDB: yamldb.YamlDB{ + Path: path, + PathNew: path + ".new", + }, + Data: dataPtr, + }, nil +} |