Files
go-sms-V2/internal/service/openapi/service.go
T

260 lines
9.1 KiB
Go

// openapi/service.go Day 46:外部 API 提交(sendMessageMass/sendMessageOne)。
// 校验→send.Submit/SubmitPersonal 复用内部链(余额/审核分流/雪花明细)→sms-submit 事件投递。
package openapi
import (
"context"
"strconv"
"strings"
"time"
"go-sms/internal/model/entity"
"go-sms/internal/service/send"
"gorm.io/gorm"
)
// MaxScheduleAhead 定时最远时限(天)。
const MaxScheduleAhead = 15 * 24 * time.Hour
// EventProducer 事件投递接口(*queue.Producer 实现;nil=降级只落库)。
type EventProducer interface {
Send(topic string, key, value []byte) error
}
// Service 外部 API 提交服务。
type Service struct {
db *gorm.DB
submit *send.SubmitService
producer EventProducer
}
// NewService 构造(producer 可 nil:Kafka 不可用时仅落库,发送由定时调度器 DB 认领兜底)。
func NewService(db *gorm.DB, submit *send.SubmitService, producer EventProducer) *Service {
return &Service{db: db, submit: submit, producer: producer}
}
// Resp 协议响应(与 docx 示例对齐:code/message/msgId/smsCount)。
type Resp struct {
Code int `json:"code"`
Message string `json:"message"`
MsgID int64 `json:"msgId,omitempty"`
SmsCount int `json:"smsCount,omitempty"`
TaskNo string `json:"taskNo,omitempty"`
}
// okResp 成功响应(附带任务号,便于客户端查单)。
func okResp(task *entity.MessageTask) *Resp {
return &Resp{Code: CodeOK, Message: DocMsg(CodeOK),
MsgID: task.ID, SmsCount: task.MobileCount, TaskNo: task.TaskNo}
}
// failResp 失败响应(空 msg 用码表默认文案)。
func failResp(code int, msg string) *Resp {
if msg == "" {
msg = DocMsg(code)
}
return &Resp{Code: code, Message: msg}
}
// MassReq sendMessageMass 请求(docx 字段名 camelCase)。
type MassReq struct {
UserName string `json:"userName"`
Timestamp string `json:"timestamp"`
Sign string `json:"sign"`
PhoneList []string `json:"phoneList"`
Content string `json:"content"`
TemplateID string `json:"templateId"`
SignName string `json:"signName"`
SendTime string `json:"sendTime"`
ExtCode string `json:"extCode"`
CallData string `json:"callData"`
Business string `json:"business"` // Day 49:sms(默认)/video 视频短信
PresetMsgID int64 `json:"-"` // 内部:长短信聚合组ID 预置首条 DetailID(0=雪花默认;不收外部输入)
// Day 70:计费口径分流(内部,不收外部输入)——fee≡上游真实片数。
ContentEncoding int8 `json:"-"` // 0=默认 GBK 口径;1=UCS2(CMPP MsgFmt=8)
FeeSegments int `json:"-"` // 段数覆写(入向长短信聚合=客户端 pk_total;0=按口径计算)
}
// OneReq sendMessageOne 请求(phoneList 与 contentList 等长逐号配对)。
type OneReq struct {
UserName string `json:"userName"`
Timestamp string `json:"timestamp"`
Sign string `json:"sign"`
PhoneList []string `json:"phoneList"`
ContentList []string `json:"contentList"`
SignName string `json:"signName"`
SendTime string `json:"sendTime"`
ExtCode string `json:"extCode"`
CallData string `json:"callData"`
}
// SendMass 群发提交(鉴权已由中间件完成,auth 注入账号上下文)。
func (s *Service) SendMass(ctx context.Context, auth *AuthContext, req *MassReq, clientIP string) *Resp {
sub, content, code, msg := s.buildMassSubmit(ctx, auth, req)
if code != CodeOK {
return failResp(code, msg)
}
res, err := s.submit.Submit(ctx, sub, nil, content, clientIP)
if err != nil {
c, m := MapErr(err)
return failResp(c, m)
}
return okResp(res.Task)
}
// NextMsgID 预生成雪花 MsgID(转发 send;接入层长短信聚合组ID 用)。
func (s *Service) NextMsgID() int64 { return s.submit.NextMsgID() }
// SendMassFast P0-1(Day 63)接入快路径(CMPP access 专用):SubmitFast
// 零 DB 写(Validate+Redis 预扣+DetailID 预生成+Deferred 事件),拦截/落库/
// 审核/退费移消费侧补全;欠费为唯一同步拒绝,其余语义经 CMPP 状态回执告知。
// Resp.MsgID=DetailID 雪花——与 Deliver msg_id 同口径(修复旧路径 task.ID
// 口径不一致:客户端拿 resp.MsgID 配不上回执)。
func (s *Service) SendMassFast(ctx context.Context, auth *AuthContext, req *MassReq, clientIP string) *Resp {
sub, content, code, msg := s.buildMassSubmit(ctx, auth, req)
if code != CodeOK {
return failResp(code, msg)
}
res, err := s.submit.SubmitFast(ctx, sub, content, clientIP)
if err != nil {
c, m := MapErr(err)
return failResp(c, m)
}
return &Resp{Code: CodeOK, Message: DocMsg(CodeOK),
MsgID: res.MsgID, SmsCount: len(req.PhoneList), TaskNo: res.TaskNo}
}
// buildMassSubmit SendMass/SendMassFast 共用前段:公共校验+模板解析+定时解析
// (返回 nil content=校验失败,code/msg 为失败码)。
func (s *Service) buildMassSubmit(ctx context.Context, auth *AuthContext, req *MassReq) (*send.SubmitReq, string, int, string) {
if code, msg := validateCommon(req.ExtCode, req.CallData); code != CodeOK {
return nil, "", code, msg
}
if len(req.PhoneList) == 0 {
return nil, "", CodeEmptyPhones, ""
}
if len(req.PhoneList) > send.MaxMobiles {
return nil, "", CodeTooMany, ""
}
content := req.Content
if content == "" && req.TemplateID != "" {
tpl := s.loadTemplate(ctx, auth.AccountID, req.TemplateID)
if tpl == nil {
return nil, "", CodeMissingArg, "模板不存在或未过审"
}
content = tpl.Content
}
if strings.TrimSpace(content) == "" {
return nil, "", CodeEmptyBody, ""
}
scheduleAt, code, msg := parseSendTime(req.SendTime)
if code != CodeOK {
return nil, "", code, msg
}
sub := &send.SubmitReq{
AccountID: auth.AccountID,
SendType: send.SendTypeBatch,
Mobiles: req.PhoneList,
Content: content,
Sign: req.SignName,
Extend: req.ExtCode,
CallData: req.CallData,
Business: req.Business, // Day 49:sms/video(空由 Validate 规范化为 sms)
Source: send.NormalizeTaskSource(auth.Source), // Day 60:受理来源(HTTP API=1;CMPP/SMPP 由 access 传 2/3)
PresetMsgID: req.PresetMsgID, // 长短信聚合组ID 透传(0=默认雪花)
ContentEncoding: req.ContentEncoding, // Day 70:计费口径分流(CMPP MsgFmt=8→UCS2)
FeeSegments: req.FeeSegments, // Day 70:段数覆写(聚合=客户端 pk_total)
}
if scheduleAt != nil {
sub.SendType = send.SendTypeTimer
sub.SendAt = scheduleAt.Format("2006-01-02 15:04")
}
return sub, content, CodeOK, ""
}
// SendOne 个性提交(phoneList/contentList 逐号配对,单次≤1000)。
func (s *Service) SendOne(ctx context.Context, auth *AuthContext, req *OneReq, clientIP string) *Resp {
if code, msg := validateCommon(req.ExtCode, req.CallData); code != CodeOK {
return failResp(code, msg)
}
if len(req.PhoneList) == 0 {
return failResp(CodeEmptyPhones, "")
}
if len(req.PhoneList) != len(req.ContentList) {
return failResp(CodeCountDiff, "")
}
if len(req.ContentList) > send.MaxPersonalItems {
return failResp(CodeOneTooMany, "")
}
for _, c := range req.ContentList {
if strings.TrimSpace(c) == "" {
return failResp(CodeEmptyBody, "")
}
}
scheduleAt, code, msg := parseSendTime(req.SendTime)
if code != CodeOK {
return failResp(code, msg)
}
items := make([]send.PersonalItem, 0, len(req.PhoneList))
for i, m := range req.PhoneList {
items = append(items, send.PersonalItem{Mobile: m, Content: req.ContentList[i]})
}
res, err := s.submit.SubmitPersonal(ctx, auth.AccountID, items, scheduleAt, req.ExtCode, req.CallData, clientIP,
send.NormalizeTaskSource(auth.Source)) // Day 60:受理来源打标
if err != nil {
c, m := MapErr(err)
return failResp(c, m)
}
return okResp(res.Task)
}
// validateCommon 扩展码/callData 长度校验(9/10)。
func validateCommon(extCode, callData string) (int, string) {
if len(extCode) > 32 {
return CodeExtTooLong, ""
}
if len(callData) > 64 {
return CodeCallLong, ""
}
return CodeOK, ""
}
// parseSendTime 定时解析(docx yyyy-MM-dd HH:mm:ss;过去/超 15 天→12;空=立即)。
func parseSendTime(v string) (*time.Time, int, string) {
v = strings.TrimSpace(v)
if v == "" {
return nil, CodeOK, ""
}
at, err := time.ParseInLocation("2006-01-02 15:04:05", v, time.Local)
if err != nil {
at, err = time.ParseInLocation("2006-01-02 15:04", v, time.Local) // 兼容分钟精度
if err != nil {
return nil, CodeBadSchedule, "sendTime 格式须为 yyyy-MM-dd HH:mm:ss"
}
}
now := time.Now()
if !at.After(now) {
return nil, CodeBadSchedule, "定时时刻须在未来"
}
if at.Sub(now) > MaxScheduleAhead {
return nil, CodeBadSchedule, "定时时刻不能超过 15 天"
}
return &at, CodeOK, ""
}
// loadTemplate 加载本账号可用模板(通过态;不存在/未过审/越权均 nil)。
func (s *Service) loadTemplate(ctx context.Context, accountID int64, idStr string) *entity.TemplateSMS {
id, err := strconv.ParseInt(strings.TrimSpace(idStr), 10, 64)
if err != nil || id <= 0 {
return nil
}
var tpl entity.TemplateSMS
if err := s.db.WithContext(ctx).
Where("id = ? AND account_id = ? AND status = 1", id, accountID).
First(&tpl).Error; err != nil {
return nil
}
return &tpl
}