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"
|
|
|
|
"github.com/n1try/wakapi/models"
|
|
|
|
)
|
|
|
|
|
|
|
|
type AliasService struct {
|
|
|
|
Config *models.Config
|
|
|
|
Db *gorm.DB
|
|
|
|
}
|
|
|
|
|
2019-10-10 17:47:19 +03:00
|
|
|
var userAliases sync.Map
|
2019-07-06 18:53:20 +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
|
|
|
|
}
|
|
|
|
return "", errors.New("User aliases not initialized")
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|