2019-07-06 18:53:20 +03:00
|
|
|
package services
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2019-10-10 17:47:19 +03:00
|
|
|
"sync"
|
2019-07-06 18:53:20 +03:00
|
|
|
|
|
|
|
"github.com/jinzhu/gorm"
|
2020-03-31 13:22:17 +03:00
|
|
|
"github.com/muety/wakapi/models"
|
2019-07-06 18:53:20 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type AliasService struct {
|
|
|
|
Config *models.Config
|
|
|
|
Db *gorm.DB
|
|
|
|
}
|
|
|
|
|
2020-05-24 18:32:26 +03:00
|
|
|
func NewAliasService(db *gorm.DB) *AliasService {
|
|
|
|
return &AliasService{
|
|
|
|
Config: models.GetConfig(),
|
|
|
|
Db: db,
|
|
|
|
}
|
|
|
|
}
|
2019-07-06 18:53:20 +03:00
|
|
|
|
2020-05-24 18:32:26 +03:00
|
|
|
var userAliases sync.Map
|
2020-02-20 16:28:55 +03:00
|
|
|
|
2019-07-07 11:32:28 +03:00
|
|
|
func (srv *AliasService) LoadUserAliases(userId string) error {
|
2019-07-06 18:53:20 +03:00
|
|
|
var aliases []*models.Alias
|
|
|
|
if err := srv.Db.
|
|
|
|
Where(&models.Alias{UserID: userId}).
|
|
|
|
Find(&aliases).Error; err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-10-10 17:47:19 +03:00
|
|
|
userAliases.Store(userId, aliases)
|
2019-07-06 18:53:20 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (srv *AliasService) GetAliasOrDefault(userId string, summaryType uint8, value string) (string, error) {
|
2019-10-10 17:47:19 +03:00
|
|
|
if ua, ok := userAliases.Load(userId); ok {
|
|
|
|
for _, a := range ua.([]*models.Alias) {
|
2019-07-06 18:53:20 +03:00
|
|
|
if a.Type == summaryType && a.Value == value {
|
|
|
|
return a.Key, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return value, nil
|
|
|
|
}
|
2019-11-08 01:11:19 +03:00
|
|
|
return "", errors.New("user aliases not initialized")
|
2019-07-06 18:53:20 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (src *AliasService) IsInitialized(userId string) bool {
|
2019-10-10 17:47:19 +03:00
|
|
|
if _, ok := userAliases.Load(userId); ok {
|
2019-07-06 18:53:20 +03:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|