2019-11-10 23:50:50 +00:00
|
|
|
package persistence
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"io/ioutil"
|
|
|
|
|
|
|
|
"dev.narayana.im/narayana/telegabber/yamldb"
|
|
|
|
|
2019-11-19 20:25:14 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
2019-11-10 23:50:50 +00:00
|
|
|
"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"`
|
|
|
|
}
|
|
|
|
|
2019-12-04 15:55:15 +00:00
|
|
|
var sessionDB *SessionsYamlDB
|
2019-11-10 23:50:50 +00:00
|
|
|
|
2019-11-12 15:50:25 +00:00
|
|
|
// SessionMarshaller implementation for YamlDB
|
|
|
|
func SessionMarshaller() ([]byte, error) {
|
2019-11-10 23:50:50 +00:00
|
|
|
return yaml.Marshal(sessionDB.Data)
|
|
|
|
}
|
|
|
|
|
|
|
|
// LoadSessions restores TDlib sessions from the previous run
|
2019-12-04 15:55:15 +00:00
|
|
|
func LoadSessions(path string) (*SessionsYamlDB, error) {
|
2019-11-10 23:50:50 +00:00
|
|
|
var sessionData SessionsMap
|
2019-12-04 15:55:15 +00:00
|
|
|
var err error
|
2019-11-10 23:50:50 +00:00
|
|
|
|
2019-12-04 15:55:15 +00:00
|
|
|
sessionDB, err = initYamlDB(path, &sessionData)
|
2019-11-10 23:50:50 +00:00
|
|
|
if err != nil {
|
|
|
|
return sessionDB, errors.Wrap(err, "Sessions restore error")
|
|
|
|
}
|
|
|
|
|
|
|
|
return sessionDB, nil
|
|
|
|
}
|
|
|
|
|
2019-11-19 20:25:14 +00:00
|
|
|
func emptySessionsMap(dataPtr *SessionsMap) {
|
|
|
|
dataPtr.Sessions = make(map[string]Session)
|
|
|
|
}
|
|
|
|
|
2019-12-04 15:55:15 +00:00
|
|
|
func initYamlDB(path string, dataPtr *SessionsMap) (*SessionsYamlDB, error) {
|
2019-11-10 23:50:50 +00:00
|
|
|
file, err := ioutil.ReadFile(path)
|
|
|
|
if err == nil {
|
|
|
|
err = yaml.Unmarshal(file, dataPtr)
|
|
|
|
if err != nil {
|
2019-12-04 15:55:15 +00:00
|
|
|
return nil, errors.Wrap(err, "YamlDB is corrupted")
|
2019-11-10 23:50:50 +00:00
|
|
|
}
|
2019-11-19 20:25:14 +00:00
|
|
|
|
|
|
|
if dataPtr.Sessions == nil {
|
|
|
|
emptySessionsMap(dataPtr)
|
|
|
|
}
|
|
|
|
log.Debugf("Unmarshalled YAML: %#v", *dataPtr)
|
2019-11-10 23:50:50 +00:00
|
|
|
} else {
|
|
|
|
// DB file does not exist, create an empty DB
|
2019-11-19 20:25:14 +00:00
|
|
|
emptySessionsMap(dataPtr)
|
2019-11-10 23:50:50 +00:00
|
|
|
}
|
|
|
|
|
2019-12-04 15:55:15 +00:00
|
|
|
return &SessionsYamlDB{
|
2019-11-10 23:50:50 +00:00
|
|
|
YamlDB: yamldb.YamlDB{
|
|
|
|
Path: path,
|
|
|
|
PathNew: path + ".new",
|
|
|
|
},
|
|
|
|
Data: dataPtr,
|
|
|
|
}, nil
|
|
|
|
}
|