feat: analysis admin
This commit is contained in:
@@ -19,3 +19,17 @@ type UserCreate struct {
|
||||
IsFaceVerified uint8 `gorm:"column:is_face_verified" json:"is_face_verified"`
|
||||
IsProfileCompleted uint8 `gorm:"column:is_profile_completed" json:"is_profile_completed"`
|
||||
}
|
||||
|
||||
type AdminUserListItem struct {
|
||||
Id int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Avatar string `json:"avatar"`
|
||||
Mobile string `json:"mobile"`
|
||||
Gender uint32 `json:"gender"`
|
||||
GenderText string `json:"gender_text"`
|
||||
Birthday string `json:"birthday"`
|
||||
Age string `json:"age"`
|
||||
Status int `json:"status"`
|
||||
DetectionNumber int `json:"detection_number"`
|
||||
CreatedAt utils.CustomTime `json:"created_at"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package face
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lone-services/pkg/utils"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// PrepareImagePath 将上传字节或已有路径解析为 insightface 可读的本地路径。
|
||||
// 返回 cleanup 用于删除临时文件(共享路径不删)。
|
||||
func PrepareImagePath(file []byte, filePath string) (string, func(), error) {
|
||||
noop := func() {}
|
||||
if len(file) > utils.NumberZero {
|
||||
dir := utils.GetConfigString("file.upload_path")
|
||||
if dir == utils.StringEmpty {
|
||||
dir = os.TempDir()
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return "", noop, err
|
||||
}
|
||||
path := filepath.Join(dir, "face-login-"+uuid.NewString()+".jpg")
|
||||
if err := os.WriteFile(path, file, 0o644); err != nil {
|
||||
return "", noop, err
|
||||
}
|
||||
return path, func() { _ = os.Remove(path) }, nil
|
||||
}
|
||||
|
||||
path := strings.TrimSpace(filePath)
|
||||
if path == utils.StringEmpty {
|
||||
return "", noop, fmt.Errorf("file or file_path required")
|
||||
}
|
||||
if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
|
||||
local, err := downloadToTemp(path)
|
||||
if err != nil {
|
||||
return "", noop, err
|
||||
}
|
||||
return local, func() { _ = os.Remove(local) }, nil
|
||||
}
|
||||
if filepath.IsAbs(path) {
|
||||
return path, noop, nil
|
||||
}
|
||||
base := utils.GetConfigString("file.upload_path")
|
||||
return filepath.Join(base, strings.TrimPrefix(path, "/")), noop, nil
|
||||
}
|
||||
|
||||
func downloadToTemp(url string) (string, error) {
|
||||
client := &http.Client{Timeout: 15 * time.Second}
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("download face image status %d", resp.StatusCode)
|
||||
}
|
||||
dir := utils.GetConfigString("file.upload_path")
|
||||
if dir == utils.StringEmpty {
|
||||
dir = os.TempDir()
|
||||
}
|
||||
if err = os.MkdirAll(dir, 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
path := filepath.Join(dir, "face-dl-"+uuid.NewString()+".jpg")
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
if _, err = io.Copy(f, resp.Body); err != nil {
|
||||
_ = os.Remove(path)
|
||||
return "", err
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package face
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lone-services/pkg/utils"
|
||||
)
|
||||
|
||||
const faceEmbeddingDim = 512
|
||||
|
||||
type insightFaceResp struct {
|
||||
Embedding []float32 `json:"embedding"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
func GetFaceVector(imagePath string) ([]float32, error) {
|
||||
host := utils.GetConfigString("services.skin_py_face_host")
|
||||
apiPath := utils.GetConfigString("services.skin_py_face_path")
|
||||
if host == utils.StringEmpty || apiPath == utils.StringEmpty {
|
||||
return nil, fmt.Errorf("insightface config empty")
|
||||
}
|
||||
url := strings.TrimRight(host, "/") + apiPath
|
||||
|
||||
body, err := json.Marshal(map[string]string{"path": imagePath})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal request: %w", err)
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
var errResp insightFaceResp
|
||||
_ = json.Unmarshal(respBody, &errResp)
|
||||
return nil, fmt.Errorf("face extraction failed (status %d): %s", resp.StatusCode, errResp.Error)
|
||||
}
|
||||
|
||||
var result insightFaceResp
|
||||
if err = json.Unmarshal(respBody, &result); err != nil {
|
||||
return nil, fmt.Errorf("parse response: %w", err)
|
||||
}
|
||||
if len(result.Embedding) != faceEmbeddingDim {
|
||||
return nil, fmt.Errorf("invalid embedding dimension: %d", len(result.Embedding))
|
||||
}
|
||||
return result.Embedding, nil
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package face
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"lone-services/pkg/utils"
|
||||
|
||||
"github.com/milvus-io/milvus-sdk-go/v2/client"
|
||||
"github.com/milvus-io/milvus-sdk-go/v2/entity"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
const (
|
||||
collectionName = "face_vectors"
|
||||
faceVectorField = "face_vector"
|
||||
faceUserIDField = "user_id"
|
||||
searchTopK = 1
|
||||
similarityMin = float32(0.55)
|
||||
hnswM = 16
|
||||
hnswEfConstruct = 200
|
||||
hnswEf = 64
|
||||
collectionShards = 2
|
||||
)
|
||||
|
||||
var (
|
||||
milvusMu sync.RWMutex
|
||||
milvusClient client.Client
|
||||
)
|
||||
|
||||
func InitMilvus() error {
|
||||
ctx := context.Background()
|
||||
host := utils.GetConfigString("milvus.milvus_host")
|
||||
port := utils.GetConfigString("milvus.milvus_grpc_port")
|
||||
if host == utils.StringEmpty || port == utils.StringEmpty {
|
||||
return fmt.Errorf("milvus config empty")
|
||||
}
|
||||
address := fmt.Sprintf("%s:%s", host, port)
|
||||
c, err := client.NewGrpcClient(ctx, address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect milvus %s: %w", address, err)
|
||||
}
|
||||
if err = ensureCollection(ctx, c); err != nil {
|
||||
_ = c.Close()
|
||||
return err
|
||||
}
|
||||
if err = ensureIndex(ctx, c); err != nil {
|
||||
_ = c.Close()
|
||||
return err
|
||||
}
|
||||
if err = c.LoadCollection(ctx, collectionName, false); err != nil {
|
||||
_ = c.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
milvusMu.Lock()
|
||||
if milvusClient != nil {
|
||||
_ = milvusClient.Close()
|
||||
}
|
||||
milvusClient = c
|
||||
milvusMu.Unlock()
|
||||
logx.Infof("milvus connected: %s", address)
|
||||
return nil
|
||||
}
|
||||
|
||||
func CloseMilvus() {
|
||||
milvusMu.Lock()
|
||||
defer milvusMu.Unlock()
|
||||
if milvusClient != nil {
|
||||
_ = milvusClient.Close()
|
||||
milvusClient = nil
|
||||
}
|
||||
}
|
||||
|
||||
func getMilvus() client.Client {
|
||||
milvusMu.RLock()
|
||||
defer milvusMu.RUnlock()
|
||||
return milvusClient
|
||||
}
|
||||
|
||||
func ensureCollection(ctx context.Context, c client.Client) error {
|
||||
has, err := c.HasCollection(ctx, collectionName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if has {
|
||||
return nil
|
||||
}
|
||||
schema := &entity.Schema{
|
||||
CollectionName: collectionName,
|
||||
Description: "user face vectors (ArcFace 512d)",
|
||||
AutoID: false,
|
||||
Fields: []*entity.Field{
|
||||
{
|
||||
Name: faceUserIDField,
|
||||
DataType: entity.FieldTypeInt64,
|
||||
PrimaryKey: true,
|
||||
},
|
||||
{
|
||||
Name: faceVectorField,
|
||||
DataType: entity.FieldTypeFloatVector,
|
||||
TypeParams: map[string]string{
|
||||
"dim": fmt.Sprintf("%d", faceEmbeddingDim),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
return c.CreateCollection(ctx, schema, int32(collectionShards))
|
||||
}
|
||||
|
||||
func ensureIndex(ctx context.Context, c client.Client) error {
|
||||
indexes, err := c.DescribeIndex(ctx, collectionName, faceVectorField)
|
||||
if err != nil {
|
||||
if !strings.Contains(err.Error(), "index not found") {
|
||||
return err
|
||||
}
|
||||
} else if len(indexes) > utils.NumberZero {
|
||||
return nil
|
||||
}
|
||||
idx, err := entity.NewIndexHNSW(entity.IP, hnswM, hnswEfConstruct)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.CreateIndex(ctx, collectionName, faceVectorField, idx, false)
|
||||
}
|
||||
|
||||
func UpsertFace(userID int64, vector []float32) error {
|
||||
c := getMilvus()
|
||||
if c == nil {
|
||||
return errors.New("milvus client is nil")
|
||||
}
|
||||
if userID < utils.NumberOne || len(vector) != faceEmbeddingDim {
|
||||
return errors.New("invalid face upsert args")
|
||||
}
|
||||
ctx := context.Background()
|
||||
_ = c.Delete(ctx, collectionName, "", fmt.Sprintf("%s == %d", faceUserIDField, userID))
|
||||
_, err := c.Insert(ctx, collectionName, "",
|
||||
entity.NewColumnInt64(faceUserIDField, []int64{userID}),
|
||||
entity.NewColumnFloatVector(faceVectorField, faceEmbeddingDim, [][]float32{vector}),
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func SearchUser(vector []float32) (int64, float32, error) {
|
||||
c := getMilvus()
|
||||
if c == nil {
|
||||
return 0, 0, errors.New("milvus client is nil")
|
||||
}
|
||||
if len(vector) != faceEmbeddingDim {
|
||||
return 0, 0, errors.New("invalid face vector")
|
||||
}
|
||||
ctx := context.Background()
|
||||
searchParam, err := entity.NewIndexHNSWSearchParam(hnswEf)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
result, err := c.Search(
|
||||
ctx,
|
||||
collectionName,
|
||||
nil,
|
||||
"",
|
||||
[]string{faceUserIDField},
|
||||
[]entity.Vector{entity.FloatVector(vector)},
|
||||
faceVectorField,
|
||||
entity.IP,
|
||||
searchTopK,
|
||||
searchParam,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
if len(result) == utils.NumberZero || result[0].IDs.Len() == utils.NumberZero {
|
||||
return 0, 0, errors.New("face not found")
|
||||
}
|
||||
ids, ok := result[0].IDs.(*entity.ColumnInt64)
|
||||
if !ok {
|
||||
return 0, 0, errors.New("invalid milvus id column")
|
||||
}
|
||||
userID, err := ids.ValueByIdx(0)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
score := result[0].Scores[0]
|
||||
if score < similarityMin {
|
||||
return 0, score, errors.New("face similarity too low")
|
||||
}
|
||||
return userID, score, nil
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package analysisadminlogic
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"lone-services/pkg/modelbase"
|
||||
"lone-services/pkg/utils"
|
||||
analysis "lone-services/rpc/analysis/pb"
|
||||
"lone-services/services/analysis/internal/dao"
|
||||
"lone-services/services/analysis/internal/logic/common"
|
||||
"lone-services/services/analysis/internal/model"
|
||||
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
)
|
||||
|
||||
const adminImageTimeLayout = "2006-01-02 15:04"
|
||||
|
||||
func outParams(msg string) *analysis.Response {
|
||||
return common.OutResponse(utils.ErrorParams, msg)
|
||||
}
|
||||
|
||||
func formatGender(gender uint32) string {
|
||||
switch gender {
|
||||
case 1:
|
||||
return "男"
|
||||
case 2:
|
||||
return "女"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func userStatus(row dao.User) int {
|
||||
status := utils.NumberOne
|
||||
if row.IsRegistered == uint8(utils.StatusOk) {
|
||||
status = utils.NumberTwo
|
||||
}
|
||||
if row.IsFaceVerified == uint8(utils.StatusOk) {
|
||||
status = utils.NumberThree
|
||||
}
|
||||
if row.IsProfileCompleted == uint8(utils.StatusOk) {
|
||||
status = utils.NumberFour
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func idStrings(ids []int64) []string {
|
||||
out := make([]string, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if id < utils.NumberOne {
|
||||
continue
|
||||
}
|
||||
out = append(out, strconv.FormatInt(id, utils.NumberTen))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func loadImageLogs(userIds []int64) (map[int64]dao.UserImageLog, error) {
|
||||
out := make(map[int64]dao.UserImageLog, len(userIds))
|
||||
if len(userIds) == utils.NumberZero {
|
||||
return out, nil
|
||||
}
|
||||
var rows []dao.UserImageLog
|
||||
err := model.UserImageLogModel{}.Init().Items(modelbase.Params{
|
||||
In: map[string][]string{"user_id": idStrings(userIds)},
|
||||
Order: "detection_time desc",
|
||||
}, &rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
if _, ok := out[row.UserId]; ok {
|
||||
continue
|
||||
}
|
||||
out[row.UserId] = row
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func formatImageContents(data map[string]string) map[string]string {
|
||||
result := make(map[string]string, len(data))
|
||||
for k, v := range data {
|
||||
switch k {
|
||||
case "health_score":
|
||||
parts := strings.Split(v, "/")
|
||||
result[k] = strings.TrimSpace(parts[0])
|
||||
default:
|
||||
result[k] = strings.TrimSuffix(v, "%")
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func buildImageDetail(detail *dao.Image) dao.ImageDetailResource {
|
||||
var images map[string]interface{}
|
||||
if detail.Images != utils.StringEmpty {
|
||||
_ = jsoniter.UnmarshalFromString(detail.Images, &images)
|
||||
}
|
||||
|
||||
var contents map[string]string
|
||||
if detail.Contents != utils.StringEmpty {
|
||||
var raw map[string]string
|
||||
if err := jsoniter.UnmarshalFromString(detail.Contents, &raw); err == nil {
|
||||
contents = formatImageContents(raw)
|
||||
} else {
|
||||
contents = map[string]string{}
|
||||
}
|
||||
}
|
||||
|
||||
return dao.ImageDetailResource{
|
||||
Id: detail.Id,
|
||||
UserId: detail.UserId,
|
||||
TaskId: detail.TaskId,
|
||||
Images: images,
|
||||
Contents: contents,
|
||||
Cover: detail.Cover,
|
||||
CreateTime: detail.CreateTime.Format(adminImageTimeLayout),
|
||||
}
|
||||
}
|
||||
|
||||
func queryAdminImageLogs(userId int64, page, size int32) ([]dao.ImageLogResource, error) {
|
||||
var rows []dao.Image
|
||||
_, err := model.ImageModel{}.Init().Page(modelbase.Params{
|
||||
Eq: map[string]string{
|
||||
"user_id": strconv.FormatInt(userId, utils.NumberTen),
|
||||
"status": strconv.Itoa(utils.StatusOk),
|
||||
},
|
||||
Order: "id desc",
|
||||
Page: int(page),
|
||||
Size: int(size),
|
||||
}, &rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(rows) == utils.NumberZero {
|
||||
return nil, nil
|
||||
}
|
||||
list := make([]dao.ImageLogResource, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
contents := map[string]string{}
|
||||
if row.Contents != utils.StringEmpty {
|
||||
var raw map[string]string
|
||||
if err = jsoniter.UnmarshalFromString(row.Contents, &raw); err == nil {
|
||||
if formatted := formatImageContents(raw); formatted != nil {
|
||||
contents = formatted
|
||||
}
|
||||
}
|
||||
}
|
||||
list = append(list, dao.ImageLogResource{
|
||||
Id: row.Id,
|
||||
UserId: row.UserId,
|
||||
Cover: row.Cover,
|
||||
Contents: contents,
|
||||
TaskId: row.TaskId,
|
||||
CreateTime: row.CreateTime.Format(adminImageTimeLayout),
|
||||
})
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package analysisadminlogic
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"lone-services/pkg/utils"
|
||||
"lone-services/pkg/validate"
|
||||
analysis "lone-services/rpc/analysis/pb"
|
||||
"lone-services/services/analysis/internal/logic/common"
|
||||
"lone-services/services/analysis/internal/svc"
|
||||
"lone-services/services/analysis/validator"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
type UserArchiveLogic struct {
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
logx.Logger
|
||||
}
|
||||
|
||||
func NewUserArchiveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserArchiveLogic {
|
||||
return &UserArchiveLogic{
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
Logger: logx.WithContext(ctx),
|
||||
}
|
||||
}
|
||||
|
||||
func (l *UserArchiveLogic) UserArchive(in *analysis.AdminUserArchiveReq) (*analysis.Response, error) {
|
||||
var req validator.AdminUserArchiveValidator
|
||||
if msg := validate.ValidateFromProto(in, &req); msg != utils.StringEmpty {
|
||||
return outParams(msg), nil
|
||||
}
|
||||
if _, fail := common.RequireAdmin(l.ctx); fail != nil {
|
||||
return fail, nil
|
||||
}
|
||||
|
||||
list, err := queryAdminImageLogs(req.UserId, req.Page, req.Size)
|
||||
if err != nil {
|
||||
l.Errorf("admin user archive: %v", err)
|
||||
return common.FailResponse(utils.Fail), nil
|
||||
}
|
||||
if len(list) == utils.NumberZero {
|
||||
return common.OkResponse(nil), nil
|
||||
}
|
||||
return common.OkResponse(list), nil
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package analysisadminlogic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
|
||||
"lone-services/pkg/modelbase"
|
||||
"lone-services/pkg/utils"
|
||||
"lone-services/pkg/validate"
|
||||
analysis "lone-services/rpc/analysis/pb"
|
||||
"lone-services/services/analysis/internal/dao"
|
||||
"lone-services/services/analysis/internal/logic/common"
|
||||
"lone-services/services/analysis/internal/model"
|
||||
"lone-services/services/analysis/internal/svc"
|
||||
"lone-services/services/analysis/validator"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
type UserDetailLogic struct {
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
logx.Logger
|
||||
}
|
||||
|
||||
func NewUserDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserDetailLogic {
|
||||
return &UserDetailLogic{
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
Logger: logx.WithContext(ctx),
|
||||
}
|
||||
}
|
||||
|
||||
func (l *UserDetailLogic) UserDetail(in *analysis.AdminUserDetailReq) (*analysis.Response, error) {
|
||||
var req validator.AdminUserDetailValidator
|
||||
if msg := validate.ValidateFromProto(in, &req); msg != utils.StringEmpty {
|
||||
return outParams(msg), nil
|
||||
}
|
||||
if _, fail := common.RequireAdmin(l.ctx); fail != nil {
|
||||
return fail, nil
|
||||
}
|
||||
|
||||
var detail dao.Image
|
||||
err := model.ImageModel{}.Init().GetOne(modelbase.Params{
|
||||
Eq: map[string]string{"id": strconv.FormatInt(req.Id, utils.NumberTen)},
|
||||
}, &detail)
|
||||
if err != nil {
|
||||
l.Errorf("admin user detail: %v", err)
|
||||
return common.FailResponse(utils.Fail), nil
|
||||
}
|
||||
if detail.Id <= utils.NumberZero {
|
||||
return common.OkResponse(nil), nil
|
||||
}
|
||||
return common.OkResponse(buildImageDetail(&detail)), nil
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package analysisadminlogic
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"lone-services/pkg/modelbase"
|
||||
"lone-services/pkg/utils"
|
||||
"lone-services/pkg/validate"
|
||||
analysis "lone-services/rpc/analysis/pb"
|
||||
userpb "lone-services/rpc/user/pb"
|
||||
"lone-services/services/analysis/internal/dao"
|
||||
"lone-services/services/analysis/internal/logic/common"
|
||||
"lone-services/services/analysis/internal/model"
|
||||
"lone-services/services/analysis/internal/svc"
|
||||
"lone-services/services/analysis/validator"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type UserListLogic struct {
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
logx.Logger
|
||||
}
|
||||
|
||||
func NewUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserListLogic {
|
||||
return &UserListLogic{
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
Logger: logx.WithContext(ctx),
|
||||
}
|
||||
}
|
||||
|
||||
func (l *UserListLogic) UserList(in *analysis.AdminUserListReq) (*analysis.Response, error) {
|
||||
var req validator.AdminUserListValidator
|
||||
if msg := validate.ValidateFromProto(in, &req); msg != utils.StringEmpty {
|
||||
return outParams(msg), nil
|
||||
}
|
||||
if _, fail := common.RequireAdmin(l.ctx); fail != nil {
|
||||
return fail, nil
|
||||
}
|
||||
|
||||
params := modelbase.Params{
|
||||
Order: "id desc",
|
||||
Page: int(req.Page),
|
||||
Size: int(req.Size),
|
||||
}
|
||||
|
||||
if req.Keyword != utils.StringEmpty {
|
||||
bizIds, err := l.filterBizIds(req.Keyword)
|
||||
if err != nil {
|
||||
l.Errorf("admin user list filter: %v", err)
|
||||
return common.FailResponse(utils.Fail), nil
|
||||
}
|
||||
if len(bizIds) == utils.NumberZero {
|
||||
return common.OkResponse(modelbase.PageResult{Items: []dao.AdminUserListItem{}}), nil
|
||||
}
|
||||
params.In = map[string][]string{"id": idStrings(bizIds)}
|
||||
}
|
||||
|
||||
var users []dao.User
|
||||
page, err := model.UserModel{}.Init().Page(params, &users)
|
||||
if err != nil {
|
||||
l.Errorf("admin user list page: %v", err)
|
||||
return common.FailResponse(utils.Fail), nil
|
||||
}
|
||||
if len(users) == utils.NumberZero {
|
||||
page.Items = []dao.AdminUserListItem{}
|
||||
return common.OkResponse(page), nil
|
||||
}
|
||||
|
||||
pageIds := make([]int64, 0, len(users))
|
||||
for _, row := range users {
|
||||
pageIds = append(pageIds, row.Id)
|
||||
}
|
||||
|
||||
profiles, err := l.loadProfiles(pageIds)
|
||||
if err != nil {
|
||||
l.Errorf("admin user list profiles: %v", err)
|
||||
return common.FailResponse(utils.Fail), nil
|
||||
}
|
||||
logs, err := loadImageLogs(pageIds)
|
||||
if err != nil {
|
||||
l.Errorf("admin user list logs: %v", err)
|
||||
return common.FailResponse(utils.Fail), nil
|
||||
}
|
||||
|
||||
items := make([]dao.AdminUserListItem, 0, len(users))
|
||||
for _, row := range users {
|
||||
item := dao.AdminUserListItem{
|
||||
Id: row.Id,
|
||||
Status: userStatus(row),
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
if profile, ok := profiles[row.Id]; ok {
|
||||
item.Name = profile.GetName()
|
||||
item.Avatar = profile.GetAvatar()
|
||||
mobile, _ := utils.DecryptPhone(profile.GetMobile())
|
||||
item.Mobile = mobile
|
||||
item.Gender = profile.GetGender()
|
||||
item.GenderText = formatGender(item.Gender)
|
||||
item.Birthday = profile.GetBirthday()
|
||||
item.Age = utils.CalcAgeStr(item.Birthday)
|
||||
} else {
|
||||
item.GenderText = formatGender(utils.NumberZero)
|
||||
}
|
||||
if logRow, ok := logs[row.Id]; ok {
|
||||
item.DetectionNumber = logRow.DetectionNumber
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
|
||||
page.Items = items
|
||||
return common.OkResponse(page), nil
|
||||
}
|
||||
|
||||
func (l *UserListLogic) filterBizIds(keyword string) ([]int64, error) {
|
||||
if l.svcCtx.UserSvcName == utils.StringEmpty {
|
||||
return nil, status.Error(codes.FailedPrecondition, "user service empty")
|
||||
}
|
||||
cli, err := svc.GetRpcClient(l.svcCtx.UserSvcName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res, err := userpb.NewUserClient(cli.Conn()).InternalUsersByBiz(l.ctx, &userpb.InternalUsersByBizReq{
|
||||
ClientCode: dao.ClientCodeUserSkin,
|
||||
Keyword: keyword,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make([]int64, 0, len(res.GetItems()))
|
||||
for _, item := range res.GetItems() {
|
||||
if item.GetBizId() > utils.NumberZero {
|
||||
ids = append(ids, item.GetBizId())
|
||||
}
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func (l *UserListLogic) loadProfiles(bizIds []int64) (map[int64]*userpb.BizUserItem, error) {
|
||||
out := make(map[int64]*userpb.BizUserItem, len(bizIds))
|
||||
if len(bizIds) == utils.NumberZero {
|
||||
return out, nil
|
||||
}
|
||||
if l.svcCtx.UserSvcName == utils.StringEmpty {
|
||||
return nil, status.Error(codes.FailedPrecondition, "user service empty")
|
||||
}
|
||||
cli, err := svc.GetRpcClient(l.svcCtx.UserSvcName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res, err := userpb.NewUserClient(cli.Conn()).InternalUsersByBiz(l.ctx, &userpb.InternalUsersByBizReq{
|
||||
ClientCode: dao.ClientCodeUserSkin,
|
||||
BizIds: bizIds,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, item := range res.GetItems() {
|
||||
out[item.GetBizId()] = item
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package analysisdevicelogic
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"lone-services/pkg/utils"
|
||||
"lone-services/pkg/validate"
|
||||
analysis "lone-services/rpc/analysis/pb"
|
||||
userpb "lone-services/rpc/user/pb"
|
||||
"lone-services/services/analysis/internal/dao"
|
||||
"lone-services/services/analysis/internal/face"
|
||||
"lone-services/services/analysis/internal/logic/common"
|
||||
"lone-services/services/analysis/internal/svc"
|
||||
"lone-services/services/analysis/validator"
|
||||
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
type FaceLoginLogic struct {
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
logx.Logger
|
||||
}
|
||||
|
||||
func NewFaceLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FaceLoginLogic {
|
||||
return &FaceLoginLogic{
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
Logger: logx.WithContext(ctx),
|
||||
}
|
||||
}
|
||||
|
||||
type faceLoginResult struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
Info jsoniter.RawMessage `json:"info"`
|
||||
Status int `json:"status"`
|
||||
}
|
||||
|
||||
func (l *FaceLoginLogic) FaceLogin(in *analysis.FaceLoginReq) (*analysis.Response, error) {
|
||||
var req validator.FaceLoginValidator
|
||||
if msg := validate.ValidateFromProto(in, &req); msg != utils.StringEmpty {
|
||||
return common.OutResponse(utils.ErrorParams, msg), nil
|
||||
}
|
||||
if len(req.File) == utils.NumberZero && req.FilePath == utils.StringEmpty {
|
||||
return common.FailResponse(utils.ErrorFileUpFailed), nil
|
||||
}
|
||||
|
||||
imgPath, cleanup, err := face.PrepareImagePath(req.File, req.FilePath)
|
||||
if err != nil {
|
||||
l.Errorf("face login prepare image: %v", err)
|
||||
return common.FailResponse(utils.ErrorFileUpFailed), nil
|
||||
}
|
||||
defer cleanup()
|
||||
|
||||
vector, err := face.GetFaceVector(imgPath)
|
||||
if err != nil {
|
||||
l.Errorf("face login vector: %v", err)
|
||||
return common.FailResponse(utils.ErrorNotFace), nil
|
||||
}
|
||||
|
||||
userID, score, err := face.SearchUser(vector)
|
||||
l.Infof("face login user_id=%d score=%v err=%v", userID, score, err)
|
||||
if err != nil {
|
||||
return common.FailResponse(utils.ErrorFaceNotMatch), nil
|
||||
}
|
||||
|
||||
clientCode := req.ClientCode
|
||||
if clientCode == utils.StringEmpty {
|
||||
clientCode = dao.ClientCodeUserSkin
|
||||
}
|
||||
if l.svcCtx.UserSvcName == utils.StringEmpty {
|
||||
return common.FailResponse(utils.Fail), nil
|
||||
}
|
||||
cli, err := svc.GetRpcClient(l.svcCtx.UserSvcName)
|
||||
if err != nil {
|
||||
l.Errorf("face login user rpc: %v", err)
|
||||
return common.FailResponse(utils.Fail), nil
|
||||
}
|
||||
token, err := userpb.NewUserClient(cli.Conn()).InternalLoginByUserId(l.ctx, &userpb.InternalLoginByUserIdReq{
|
||||
UserId: userID,
|
||||
ClientCode: clientCode,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorf("face login issue token: %v", err)
|
||||
return common.FailResponse(utils.ErrorFaceNotMatch), nil
|
||||
}
|
||||
|
||||
status := utils.NumberOne
|
||||
bizId := parseSessionBizId(token.GetInfo())
|
||||
if bizId > utils.NumberZero {
|
||||
if row, loadErr := common.LoadAnalysisUser(bizId); loadErr == nil && row != nil {
|
||||
status = analysisUserStatus(*row)
|
||||
}
|
||||
}
|
||||
|
||||
var info jsoniter.RawMessage
|
||||
if token.GetInfo() != utils.StringEmpty {
|
||||
info = jsoniter.RawMessage(token.GetInfo())
|
||||
} else {
|
||||
info = jsoniter.RawMessage("{}")
|
||||
}
|
||||
return common.OkResponse(faceLoginResult{
|
||||
AccessToken: token.GetAccessToken(),
|
||||
RefreshToken: token.GetRefreshToken(),
|
||||
Info: info,
|
||||
Status: status,
|
||||
}), nil
|
||||
}
|
||||
|
||||
func parseSessionBizId(info string) int64 {
|
||||
if info == utils.StringEmpty {
|
||||
return utils.NumberZero
|
||||
}
|
||||
var sess struct {
|
||||
BizId int64 `json:"biz_id"`
|
||||
}
|
||||
if err := jsoniter.UnmarshalFromString(info, &sess); err != nil {
|
||||
return utils.NumberZero
|
||||
}
|
||||
return sess.BizId
|
||||
}
|
||||
|
||||
func analysisUserStatus(row dao.User) int {
|
||||
status := utils.NumberOne
|
||||
if row.IsRegistered == uint8(utils.StatusOk) {
|
||||
status = utils.NumberTwo
|
||||
}
|
||||
if row.IsFaceVerified == uint8(utils.StatusOk) {
|
||||
status = utils.NumberThree
|
||||
}
|
||||
if row.IsProfileCompleted == uint8(utils.StatusOk) {
|
||||
status = utils.NumberFour
|
||||
}
|
||||
return status
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"lone-services/pkg/utils"
|
||||
"lone-services/pkg/validate"
|
||||
analysis "lone-services/rpc/analysis/pb"
|
||||
"lone-services/services/analysis/internal/face"
|
||||
"lone-services/services/analysis/internal/logic/common"
|
||||
"lone-services/services/analysis/internal/model"
|
||||
"lone-services/services/analysis/internal/svc"
|
||||
@@ -36,10 +37,13 @@ func (l *FaceBindLogic) FaceBind(in *analysis.FaceBindReq) (*analysis.Response,
|
||||
return common.OutResponse(utils.ErrorParams, msg), nil
|
||||
}
|
||||
|
||||
bizId, _, fail := common.RequireBizUserId(l.ctx)
|
||||
bizId, loginUser, fail := common.RequireBizUserId(l.ctx)
|
||||
if fail != nil {
|
||||
return fail, nil
|
||||
}
|
||||
if loginUser.ID < utils.NumberOne {
|
||||
return common.FailResponse(utils.ErrorNoLoginInfo), nil
|
||||
}
|
||||
|
||||
row, err := common.LoadAnalysisUser(bizId)
|
||||
if err != nil {
|
||||
@@ -50,6 +54,23 @@ func (l *FaceBindLogic) FaceBind(in *analysis.FaceBindReq) (*analysis.Response,
|
||||
return common.FailResponse(utils.ErrorNotFund), nil
|
||||
}
|
||||
|
||||
imgPath, cleanup, err := face.PrepareImagePath(nil, req.FacePath)
|
||||
if err != nil {
|
||||
l.Errorf("face bind prepare image: %v", err)
|
||||
return common.FailResponse(utils.ErrorFileUpFailed), nil
|
||||
}
|
||||
defer cleanup()
|
||||
|
||||
vector, err := face.GetFaceVector(imgPath)
|
||||
if err != nil {
|
||||
l.Errorf("face bind vector: %v", err)
|
||||
return common.FailResponse(utils.ErrorNotFace), nil
|
||||
}
|
||||
if err = face.UpsertFace(loginUser.ID, vector); err != nil {
|
||||
l.Errorf("face bind milvus: %v", err)
|
||||
return common.FailResponse(utils.Fail), nil
|
||||
}
|
||||
|
||||
_, err = model.UserModel{}.Init().Edit(modelbase.Params{
|
||||
Eq: map[string]string{"id": strconv.FormatInt(bizId, utils.NumberTen)},
|
||||
}, map[string]interface{}{
|
||||
|
||||
@@ -11,6 +11,14 @@ import (
|
||||
"lone-services/services/analysis/internal/model"
|
||||
)
|
||||
|
||||
func RequireAdmin(ctx context.Context) (utils.UserInfo, *analysis.Response) {
|
||||
user := utils.GetUserFromCtx(ctx)
|
||||
if user.ID < utils.NumberOne {
|
||||
return user, FailResponse(utils.ErrorNoLoginInfo)
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func RequireBizUserId(ctx context.Context) (int64, utils.UserInfo, *analysis.Response) {
|
||||
user := utils.GetUserFromCtx(ctx)
|
||||
if user.BizId < utils.NumberOne {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
// Code generated by goctl. DO NOT EDIT.
|
||||
// goctl 1.10.1
|
||||
// Source: analysis.proto
|
||||
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"lone-services/rpc/analysis/pb"
|
||||
"lone-services/services/analysis/internal/logic/analysisadmin"
|
||||
"lone-services/services/analysis/internal/svc"
|
||||
)
|
||||
|
||||
type AnalysisAdminServer struct {
|
||||
svcCtx *svc.ServiceContext
|
||||
analysis.UnimplementedAnalysisAdminServer
|
||||
}
|
||||
|
||||
func NewAnalysisAdminServer(svcCtx *svc.ServiceContext) *AnalysisAdminServer {
|
||||
return &AnalysisAdminServer{
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AnalysisAdminServer) UserList(ctx context.Context, in *analysis.AdminUserListReq) (*analysis.Response, error) {
|
||||
l := analysisadminlogic.NewUserListLogic(ctx, s.svcCtx)
|
||||
return l.UserList(in)
|
||||
}
|
||||
|
||||
func (s *AnalysisAdminServer) UserArchive(ctx context.Context, in *analysis.AdminUserArchiveReq) (*analysis.Response, error) {
|
||||
l := analysisadminlogic.NewUserArchiveLogic(ctx, s.svcCtx)
|
||||
return l.UserArchive(in)
|
||||
}
|
||||
|
||||
func (s *AnalysisAdminServer) UserDetail(ctx context.Context, in *analysis.AdminUserDetailReq) (*analysis.Response, error) {
|
||||
l := analysisadminlogic.NewUserDetailLogic(ctx, s.svcCtx)
|
||||
return l.UserDetail(in)
|
||||
}
|
||||
@@ -23,6 +23,11 @@ func NewAnalysisDeviceServer(svcCtx *svc.ServiceContext) *AnalysisDeviceServer {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AnalysisDeviceServer) FaceLogin(ctx context.Context, in *analysis.FaceLoginReq) (*analysis.Response, error) {
|
||||
l := analysisdevicelogic.NewFaceLoginLogic(ctx, s.svcCtx)
|
||||
return l.FaceLogin(in)
|
||||
}
|
||||
|
||||
func (s *AnalysisDeviceServer) Policy(ctx context.Context, in *analysis.DevicePolicyReq) (*analysis.Response, error) {
|
||||
l := analysisdevicelogic.NewPolicyLogic(ctx, s.svcCtx)
|
||||
return l.Policy(in)
|
||||
|
||||
Reference in New Issue
Block a user