2019-12-02 16:24:19 +00:00
|
|
|
package koushin
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
"encoding/base64"
|
|
|
|
"errors"
|
2019-12-02 16:40:53 +00:00
|
|
|
"sync"
|
2019-12-02 16:24:19 +00:00
|
|
|
|
|
|
|
imapclient "github.com/emersion/go-imap/client"
|
|
|
|
)
|
|
|
|
|
|
|
|
func generateToken() (string, error) {
|
|
|
|
b := make([]byte, 32)
|
|
|
|
_, err := rand.Read(b)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return base64.URLEncoding.EncodeToString(b), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var ErrSessionExpired = errors.New("session expired")
|
|
|
|
|
|
|
|
// TODO: expiration timer
|
|
|
|
type ConnPool struct {
|
2019-12-02 16:40:53 +00:00
|
|
|
locker sync.Mutex
|
2019-12-02 16:24:19 +00:00
|
|
|
conns map[string]*imapclient.Client
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewConnPool() *ConnPool {
|
|
|
|
return &ConnPool{
|
|
|
|
conns: make(map[string]*imapclient.Client),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (pool *ConnPool) Get(token string) (*imapclient.Client, error) {
|
2019-12-02 16:40:53 +00:00
|
|
|
pool.locker.Lock()
|
|
|
|
defer pool.locker.Unlock()
|
|
|
|
|
2019-12-02 16:24:19 +00:00
|
|
|
conn, ok := pool.conns[token]
|
|
|
|
if !ok {
|
|
|
|
return nil, ErrSessionExpired
|
|
|
|
}
|
|
|
|
return conn, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (pool *ConnPool) Put(conn *imapclient.Client) (token string, err error) {
|
2019-12-02 16:40:53 +00:00
|
|
|
pool.locker.Lock()
|
|
|
|
defer pool.locker.Unlock()
|
|
|
|
|
2019-12-02 16:24:19 +00:00
|
|
|
for {
|
|
|
|
var err error
|
|
|
|
token, err = generateToken()
|
|
|
|
if err != nil {
|
|
|
|
conn.Logout()
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, ok := pool.conns[token]; !ok {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pool.conns[token] = conn
|
2019-12-02 16:36:43 +00:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
<-conn.LoggedOut()
|
2019-12-02 16:40:53 +00:00
|
|
|
|
|
|
|
pool.locker.Lock()
|
2019-12-02 16:36:43 +00:00
|
|
|
delete(pool.conns, token)
|
2019-12-02 16:40:53 +00:00
|
|
|
pool.locker.Unlock()
|
2019-12-02 16:36:43 +00:00
|
|
|
}()
|
|
|
|
|
2019-12-02 16:24:19 +00:00
|
|
|
return token, nil
|
|
|
|
}
|