Files

147 lines
4.8 KiB
Go

// fileimport.go Day 44:号码文件导入服务(文件入口)——multipart 上传→解析(TXT/CSV/XLSX)
// →归一校验去重→原始文件落 MinIO→返回计数/预览/对象键。
// 与 SubmitService 解耦:导入只做「号码准备」,提交仍走 POST /send/submit(文件类型 send_type=4)。
package submit
import (
"bytes"
"context"
"io"
"strconv"
"strings"
"go-sms/internal/pkg/errors"
"go-sms/internal/pkg/storage"
"go-sms/internal/util"
"go-sms/internal/util/fileparse"
)
// PreviewLimit 预览行数(前端回显;与 D17 前端本地预览 50 行一致)。
const PreviewLimit = 50
// FileImportService 号码文件导入。
type FileImportService struct {
store storage.ObjectStore
sf *util.Snowflake
}
// NewFileImportService 构造(sf 生成对象键;store 为 nil 时拒绝装配——文件入口不可降级)。
func NewFileImportService(store storage.ObjectStore, sf *util.Snowflake) *FileImportService {
return &FileImportService{store: store, sf: sf}
}
// ImportResult 导入结果。
type ImportResult struct {
Total int `json:"total"` // 文件数据行数(含表头/非法)
Valid int `json:"valid"` // 合格去重后号码数
Duplicated int `json:"duplicated"` // 重复行数
Invalid int `json:"invalid"` // 非法行数(不含表头)
HeaderSkip bool `json:"header_skipped"` // 表头启发命中(首行非号码且后续有合法)
Mobiles []string `json:"mobiles"` // 合格号码全量(≤MaxMobiles;供直接进入 estimate/submit)
Preview []string `json:"preview"` // 合格号码预览(前 50)
ObjectKey string `json:"object_key"` // MinIO 对象键(numbers/{account}/{snowID}{ext})
}
// Import 导入:r 原始内容(调用方负责 multipart 打开);filename 决定解析器分发;size 上限校验。
func (s *FileImportService) Import(ctx context.Context, r io.Reader, filename string, size int64, accountID int64) (*ImportResult, error) {
if size <= 0 && size != -1 {
return nil, errors.InvalidParam.WithMsg("缺少文件内容")
}
if size > 10<<20 { // 10MB(万行号码文件量级,防滥用)
return nil, errors.InvalidParam.WithMsg("文件超 10MB 上限")
}
buf := new(bytes.Buffer)
if _, err := buf.ReadFrom(r); err != nil {
return nil, errors.InvalidParam.WithMsg("文件读取失败: " + err.Error())
}
raw, err := fileparse.Parse(bytes.NewReader(buf.Bytes()), filename)
if err != nil {
return nil, errors.InvalidParam.WithMsg(err.Error())
}
if len(raw.Mobiles) == 0 {
return nil, errors.InvalidParam.WithMsg("文件为空或无数据行")
}
res := &ImportResult{Total: raw.Rows, Preview: make([]string, 0, PreviewLimit)}
seen := make(map[string]struct{}, len(raw.Mobiles))
valid := 0
mobiles := make([]string, 0, 32)
headerChecked := false
for i, m := range raw.Mobiles {
n := util.NormalizeMobile(m)
if !util.IsValidMainlandMobile(n) {
// 表头启发:首行非法且后续存在合法 → 视为表头跳过(不计 invalid)
if i == 0 && !headerChecked && len(raw.Mobiles) > 1 {
headerChecked = true
if hasAnyValid(raw.Mobiles[1:]) {
res.HeaderSkip = true
continue
}
}
res.Invalid++
continue
}
if _, dup := seen[n]; dup {
res.Duplicated++
continue
}
seen[n] = struct{}{}
valid++
mobiles = append(mobiles, n)
if valid <= PreviewLimit {
res.Preview = append(res.Preview, n)
}
}
if valid == 0 {
return nil, errors.InvalidParam.WithMsg("文件中未解析到合法手机号")
}
if valid > MaxMobiles {
return nil, errors.InvalidParam.WithMsg(numberLimitMsg(valid))
}
// 原始文件落 MinIO(键含账号+雪花;内容原样,可审计可重放)
ext := extOf(filename)
res.ObjectKey = "numbers/" + int64ToString(accountID) + "/" + int64ToString(s.sf.NextID()) + ext
if err := s.store.Put(ctx, res.ObjectKey, bytes.NewReader(buf.Bytes()), int64(buf.Len()), contentTypeOf(ext)); err != nil {
return nil, errors.InternalError.WithMsg("对象存储写入失败: " + err.Error())
}
res.Valid = valid
res.Mobiles = mobiles
return res, nil
}
// hasAnyValid 任一候选为合法手机号(表头启发辅助)。
func hasAnyValid(ms []string) bool {
for _, m := range ms {
if util.IsValidMainlandMobile(util.NormalizeMobile(m)) {
return true
}
}
return false
}
func numberLimitMsg(n int) string {
return "号码 " + strconv.Itoa(n) + " 超单次上限 " + strconv.Itoa(MaxMobiles)
}
func int64ToString(n int64) string { return strconv.FormatInt(n, 10) }
func extOf(name string) string {
if i := strings.LastIndexByte(name, '.'); i >= 0 {
return strings.ToLower(name[i:])
}
return ""
}
func contentTypeOf(ext string) string {
switch ext {
case ".csv":
return "text/csv"
case ".txt":
return "text/plain"
case ".xlsx":
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
}
return "application/octet-stream"
}