package session
import (
"context"
"encoding/json"
"github.com/go-faster/errors"
"github.com/gotd/td/tg"
)
type Config struct {
BlockedMode bool
ForceTryIpv6 bool
Date int
Expires int
TestMode bool
ThisDC int
DCOptions []tg .DCOption
DCTxtDomainName string
TmpSessions int
WebfileDCID int
}
func ConfigFromTG (c tg .Config ) Config {
return Config {
BlockedMode : c .BlockedMode ,
ForceTryIpv6 : c .ForceTryIpv6 ,
Date : c .Date ,
Expires : c .Expires ,
TestMode : c .TestMode ,
ThisDC : c .ThisDC ,
DCOptions : c .DCOptions ,
DCTxtDomainName : c .DCTxtDomainName ,
WebfileDCID : c .WebfileDCID ,
TmpSessions : c .TmpSessions ,
}
}
func (c Config ) TG () tg .Config {
return tg .Config {
BlockedMode : c .BlockedMode ,
ForceTryIpv6 : c .ForceTryIpv6 ,
Date : c .Date ,
Expires : c .Expires ,
TestMode : c .TestMode ,
ThisDC : c .ThisDC ,
DCOptions : c .DCOptions ,
DCTxtDomainName : c .DCTxtDomainName ,
WebfileDCID : c .WebfileDCID ,
TmpSessions : c .TmpSessions ,
}
}
type Data struct {
Config Config
DC int
Addr string
AuthKey []byte
AuthKeyID []byte
Salt int64
}
type Storage interface {
LoadSession (ctx context .Context ) ([]byte , error )
StoreSession (ctx context .Context , data []byte ) error
}
var ErrNotFound = errors .New ("session storage: not found" )
type Loader struct {
Storage Storage
}
type jsonData struct {
Version int
Data Data
}
const latestVersion = 1
func (l *Loader ) Load (ctx context .Context ) (*Data , error ) {
buf , err := l .Storage .LoadSession (ctx )
if err != nil {
return nil , errors .Wrap (err , "load" )
}
if len (buf ) == 0 {
return nil , ErrNotFound
}
var v jsonData
if err := json .Unmarshal (buf , &v ); err != nil {
return nil , errors .Wrap (err , "unmarshal" )
}
if v .Version != latestVersion {
return nil , errors .Wrapf (ErrNotFound , "version mismatch (%d != %d)" , v .Version , latestVersion )
}
return &v .Data , err
}
func (l *Loader ) Save (ctx context .Context , data *Data ) error {
v := jsonData {
Version : latestVersion ,
Data : *data ,
}
buf , err := json .Marshal (v )
if err != nil {
return errors .Wrap (err , "marshal" )
}
if err := l .Storage .StoreSession (ctx , buf ); err != nil {
return errors .Wrap (err , "store" )
}
return nil
}
The pages are generated with Golds v0.6.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds .