service.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "path"
  7. "time"
  8. "go-common/app/admin/main/member/conf"
  9. "go-common/app/admin/main/member/dao"
  10. "go-common/app/admin/main/member/model"
  11. "go-common/app/admin/main/member/service/block"
  12. acccrypto "go-common/app/interface/main/account/service/realname/crypto"
  13. account "go-common/app/service/main/account/api"
  14. coinrpc "go-common/app/service/main/coin/api/gorpc"
  15. rpcfigure "go-common/app/service/main/figure/rpc/client"
  16. memberrpc "go-common/app/service/main/member/api/gorpc"
  17. "go-common/app/service/main/member/service/crypto"
  18. rpcrelation "go-common/app/service/main/relation/rpc/client"
  19. rpcspy "go-common/app/service/main/spy/rpc/client"
  20. "go-common/library/ecode"
  21. "go-common/library/log"
  22. "go-common/library/queue/databus"
  23. "go-common/library/stat/prom"
  24. xtime "go-common/library/time"
  25. "github.com/robfig/cron"
  26. )
  27. // Service struct
  28. type Service struct {
  29. c *conf.Config
  30. dao *dao.Dao
  31. block *block.Service
  32. auditHandlers map[string]auditHandler
  33. coinRPC *coinrpc.Service
  34. memberRPC *memberrpc.Service
  35. spyRPC *rpcspy.Service
  36. figureRPC *rpcfigure.Service
  37. accountClient account.AccountClient
  38. cron *cron.Cron
  39. relationRPC *rpcrelation.Service
  40. realnameCrypto *crypto.Realname
  41. mainCryptor *acccrypto.Main
  42. }
  43. // New init
  44. func New(c *conf.Config) (s *Service) {
  45. s = &Service{
  46. c: c,
  47. dao: dao.New(c),
  48. coinRPC: coinrpc.New(c.RPCClient.Coin),
  49. memberRPC: memberrpc.New(c.RPCClient.Member),
  50. figureRPC: rpcfigure.New(c.RPCClient.Figure),
  51. spyRPC: rpcspy.New(c.RPCClient.Spy),
  52. relationRPC: rpcrelation.New(c.RPCClient.Relation),
  53. auditHandlers: make(map[string]auditHandler),
  54. cron: cron.New(),
  55. realnameCrypto: crypto.NewRealname(string(c.Realname.RsaPub), string(c.Realname.RsaPriv)),
  56. mainCryptor: acccrypto.NewMain(string(c.Realname.RsaPub), string(c.Realname.RsaPriv)),
  57. }
  58. var err error
  59. if s.accountClient, err = account.NewClient(c.RPCClient.Account); err != nil {
  60. panic(err)
  61. }
  62. s.block = block.New(c, s.dao.BlockImpl(), s.spyRPC, s.figureRPC, s.accountClient, databus.New(c.AccountNotify))
  63. s.initAuditHandler()
  64. s.initCron()
  65. s.cron.Start()
  66. return s
  67. }
  68. // Ping Service
  69. func (s *Service) Ping(c context.Context) (err error) {
  70. return s.dao.Ping(c)
  71. }
  72. // Close Service
  73. func (s *Service) Close() {
  74. s.dao.Close()
  75. s.block.Close()
  76. }
  77. func (s *Service) initCron() {
  78. s.cron.AddFunc("0 */5 * * * *", func() { s.notifyAudit(context.Background()) }) // 用于发送审核数据给目标用户
  79. s.cron.AddFunc("0 */5 * * * *", func() { s.promAuditTotal(context.Background()) }) // 用于上报审核数据给promethues
  80. s.cron.AddFunc("0 */1 * * * *", func() { s.cacheRecentRealnameImage(context.Background()) }) // 用于缓存实名认证的图片数据
  81. s.cron.AddFunc("0 */2 * * * *", func() { s.faceCheckproc(context.Background(), -10*time.Minute, "two minute") }) // 用于AI头像审核:首次:每隔2分钟审核10分钟内的头像
  82. s.cron.AddFunc("0 */60 * * * *", func() { s.faceCheckproc(context.Background(), -6*time.Hour, "per hour") }) // 用于AI头像审核:重新审核:每小时重新审核一下6小时内的头像
  83. s.cron.AddFunc("0 */5 * * * *", func() { s.faceAutoPassproc(context.Background()) }) // 头像自动审核:每隔5分钟检查一次超过48小时未处理的头像并自动通过
  84. }
  85. // notifyAudit
  86. func (s *Service) notifyAudit(ctx context.Context) {
  87. now := time.Now()
  88. log.Info("start notify audit at: %+v", now)
  89. locked, err := s.dao.TryLockReviewNotify(ctx, now)
  90. if err != nil {
  91. log.Error("Failed to lock review notify at: %+v: %+v", now, err)
  92. return
  93. }
  94. if !locked {
  95. log.Warn("Already locked by other instance at: %+v", now)
  96. return
  97. }
  98. stime := now.Add(-time.Hour * 24 * 7) // 只计算 7 天内的数据
  99. // 绝对锁上了
  100. faceNotify := func() error {
  101. total, firstAt, err := s.faceAuditNotifyContent(ctx, stime)
  102. if err != nil {
  103. log.Error("Failed to fetch face audit notify content: %+v", err)
  104. return err
  105. }
  106. log.Info("faceAuditNotifyContent success: total(%v),firstAt(%v)", total, firstAt)
  107. title := fmt.Sprintf("头像审核提醒;消息时间:%s", now.Format("2006-01-02 15:04:05"))
  108. firstAtStr := "null"
  109. if firstAt != nil {
  110. firstAtStr = firstAt.Format("2006-01-02 15:04:05")
  111. }
  112. content := fmt.Sprintf(
  113. "头像审核提醒;消息时间:%s\n头像审核积压:%d 条;最早进审时间:%s",
  114. now.Format("2006-01-02 15:04:05"),
  115. total,
  116. firstAtStr,
  117. )
  118. return s.dao.MerakNotify(ctx, title, content)
  119. }
  120. if err := faceNotify(); err != nil {
  121. log.Error("Failed to notify face review stat: %+v", err)
  122. }
  123. monitorNotify := func() error {
  124. total, firstAt, err := s.monitorAuditNotifyContent(ctx, stime)
  125. if err != nil {
  126. log.Error("Failed to fetch monitor audit notify content: %+v", err)
  127. return err
  128. }
  129. log.Info("monitorAuditNotifyContent success: total(%v),firstAt(%v)", total, firstAt)
  130. title := fmt.Sprintf("用户信息监控提醒;消息时间:%s", now.Format("2006-01-02 15:04:05"))
  131. firstAtStr := "null"
  132. if firstAt != nil {
  133. firstAtStr = firstAt.Format("2006-01-02 15:04:05")
  134. }
  135. content := fmt.Sprintf(
  136. "用户信息监控提醒;消息时间:%s\n用户信息监控积压:%d 条;最早进审时间:%s",
  137. now.Format("2006-01-02 15:04:05"),
  138. total,
  139. firstAtStr,
  140. )
  141. return s.dao.MerakNotify(ctx, title, content)
  142. }
  143. if err := monitorNotify(); err != nil {
  144. log.Error("Failed to notify monitor review stat: %+v", err)
  145. }
  146. // 实名认证待审核通知
  147. realnameNotify := func() error {
  148. total, firstAt, err := s.realnameAuditNotifyContent(ctx, stime)
  149. if err != nil {
  150. log.Error("Failed to fetch realname audit notify content: %+v", err)
  151. return err
  152. }
  153. log.Info("realnameAuditNotifyContent success: total(%v),firstAt(%v)", total, firstAt)
  154. title := fmt.Sprintf("实名认证审核提醒;消息时间:%s", now.Format("2006-01-02 15:04:05"))
  155. firstAtStr := "null"
  156. if firstAt != nil {
  157. firstAtStr = firstAt.Format("2006-01-02 15:04:05")
  158. }
  159. content := fmt.Sprintf(
  160. "实名认证审核提醒;消息时间:%s\n实名认证审核积压:%d 条;最早进审时间:%s",
  161. now.Format("2006-01-02 15:04:05"),
  162. total,
  163. firstAtStr,
  164. )
  165. return s.dao.MerakNotify(ctx, title, content)
  166. }
  167. if err := realnameNotify(); err != nil {
  168. log.Error("Failed to notify realname list stat: %+v", err)
  169. }
  170. log.Info("end notify audit at: %+v", now)
  171. }
  172. // promAuditTotal
  173. func (s *Service) promAuditTotal(ctx context.Context) {
  174. stime := time.Now().Add(-time.Hour * 24 * 7) // 只计算 7 天内的数据
  175. log.Info("promAuditTotal start %+v", time.Now())
  176. faceAudit := func() {
  177. faceTotal, _, err := s.faceAuditNotifyContent(ctx, stime)
  178. if err != nil {
  179. log.Error("Failed to fetch face audit notify content: %+v", err)
  180. return
  181. }
  182. prom.BusinessInfoCount.State("faceAudit-needAudit", int64(faceTotal))
  183. }
  184. monitorAudit := func() {
  185. monitorTotal, _, err := s.monitorAuditNotifyContent(ctx, stime)
  186. if err != nil {
  187. log.Error("Failed to fetch monitor audit notify content: %+v", err)
  188. return
  189. }
  190. prom.BusinessInfoCount.State("monitorAudit-needAudit", int64(monitorTotal))
  191. }
  192. realnameAudit := func() {
  193. realnameTotal, _, err := s.realnameAuditNotifyContent(ctx, stime)
  194. if err != nil {
  195. log.Error("Failed to fetch realname audit notify content: %+v", err)
  196. return
  197. }
  198. prom.BusinessInfoCount.State("realnameAudit-needAudit", int64(realnameTotal))
  199. }
  200. faceAudit()
  201. monitorAudit()
  202. realnameAudit()
  203. log.Info("promAuditTotal end %+v", time.Now())
  204. }
  205. func (s *Service) faceAuditNotifyContent(ctx context.Context, stime time.Time) (int, *time.Time, error) {
  206. arg := &model.ArgReviewList{
  207. State: []int8{0},
  208. IsMonitor: false,
  209. Property: []int8{model.ReviewPropertyFace},
  210. IsDesc: false,
  211. Pn: 1,
  212. Ps: 1,
  213. STime: xtime.Time(stime.Unix()),
  214. ForceDB: false,
  215. }
  216. reviews, total, err := s.Reviews(ctx, arg)
  217. if err != nil {
  218. return 0, nil, err
  219. }
  220. if len(reviews) <= 0 {
  221. return 0, nil, nil
  222. }
  223. firstAt := reviews[0].CTime.Time()
  224. return total, &firstAt, nil
  225. }
  226. func (s *Service) monitorAuditNotifyContent(ctx context.Context, stime time.Time) (int, *time.Time, error) {
  227. arg := &model.ArgReviewList{
  228. State: []int8{0},
  229. IsMonitor: true,
  230. IsDesc: false,
  231. Pn: 1,
  232. Ps: 1,
  233. STime: xtime.Time(stime.Unix()),
  234. ForceDB: false,
  235. }
  236. reviews, total, err := s.Reviews(ctx, arg)
  237. if err != nil {
  238. return 0, nil, err
  239. }
  240. if len(reviews) <= 0 {
  241. return 0, nil, nil
  242. }
  243. firstAt := reviews[0].CTime.Time()
  244. return total, &firstAt, nil
  245. }
  246. func (s *Service) realnameAuditNotifyContent(ctx context.Context, stime time.Time) (int, *time.Time, error) {
  247. arg := &model.ArgRealnameList{
  248. Channel: "main", //main : 主站 alipay : 支付宝
  249. TSFrom: stime.Unix(),
  250. State: model.RealnameApplyStatePending,
  251. IsDesc: false,
  252. PN: 1,
  253. PS: 1,
  254. }
  255. mainList, total, err := s.realnameMainList(ctx, arg)
  256. if err != nil {
  257. return 0, nil, err
  258. }
  259. if len(mainList) <= 0 {
  260. return 0, nil, nil
  261. }
  262. firstAt := time.Unix(mainList[0].CreateTS, 0)
  263. return total, &firstAt, nil
  264. }
  265. func (s *Service) faceAutoPassproc(ctx context.Context) {
  266. now := time.Now()
  267. log.Info("faceAutoPassproc start %+v", now)
  268. etime := now.AddDate(0, 0, -2)
  269. if err := s.faceAutoPass(ctx, etime); err != nil {
  270. log.Error("Failed to face auto pass, error: %+v", err)
  271. }
  272. }
  273. func (s *Service) faceAutoPass(ctx context.Context, etime time.Time) error {
  274. property := []int{model.ReviewPropertyFace}
  275. state := []int{model.ReviewStateWait, model.ReviewStateQueuing}
  276. result, err := s.dao.SearchUserPropertyReview(ctx, 0, property,
  277. state, false, false, "", "", etime.Format("2006-01-02 15:04:05"), 1, 100)
  278. if err != nil {
  279. return err
  280. }
  281. ids := result.IDs()
  282. if len(ids) == 0 {
  283. log.Info("face auto pass empty result list, end time: %v", etime)
  284. return nil
  285. }
  286. if err = s.dao.FaceAutoPass(ctx, ids, xtime.Time(etime.Unix())); err != nil {
  287. return err
  288. }
  289. return nil
  290. }
  291. func (s *Service) faceCheckproc(ctx context.Context, duration time.Duration, tag string) {
  292. now := time.Now()
  293. stime := now.Add(duration).Unix()
  294. etime := now.Unix()
  295. log.Info("faceCheckproc:%v start %+v", tag, now)
  296. if err := s.faceAuditAI(ctx, stime, etime); err != nil {
  297. log.Error("Failed to check face, error: %+v", err)
  298. }
  299. }
  300. func (s *Service) faceAuditAI(ctx context.Context, stime, etime int64) error {
  301. rws, err := s.dao.QueuingFaceReviewsByTime(ctx, xtime.Time(stime), xtime.Time(etime))
  302. if err != nil {
  303. log.Warn("Failed to get recent user_property_review image: %+v", err)
  304. return err
  305. }
  306. for _, rw := range rws {
  307. fcr, err := s.faceCheckRes(ctx, path.Base(rw.New))
  308. if err != nil {
  309. log.Error("Failed to get face check res, rw: %+v, error: %+v", rw, err)
  310. continue
  311. }
  312. state := int8(model.ReviewStateWait)
  313. if fcr.Valid() {
  314. state = model.ReviewStatePass
  315. }
  316. remark := fmt.Sprintf("AI: %s", fcr.String())
  317. if err = s.dao.AuditQueuingFace(ctx, rw.ID, remark, state); err != nil {
  318. log.Error("Failed to audit queuing face, rw: %+v, error: %+v", rw, err)
  319. continue
  320. }
  321. log.Info("face check success, rw: %+v", rw)
  322. }
  323. log.Info("faceCheckproc end")
  324. return nil
  325. }
  326. func (s *Service) faceCheckRes(ctx context.Context, fileName string) (*model.FaceCheckRes, error) {
  327. res, err := s.dao.SearchFaceCheckRes(ctx, fileName)
  328. if err != nil {
  329. return nil, err
  330. }
  331. if len(res.Result) == 0 {
  332. return nil, ecode.NothingFound
  333. }
  334. userLog := res.Result[0]
  335. fcr, err := parseFaceCheckRes(userLog.Extra)
  336. if err != nil {
  337. log.Error("Failed to parse faceCheckRes, userLog: %+v error: %+v", userLog, err)
  338. return nil, err
  339. }
  340. return fcr, nil
  341. }
  342. func parseFaceCheckRes(in string) (*model.FaceCheckRes, error) {
  343. res := &model.FaceCheckRes{}
  344. err := json.Unmarshal([]byte(in), res)
  345. if err != nil {
  346. return nil, err
  347. }
  348. return res, nil
  349. }
  350. // BlockImpl is
  351. func (s *Service) BlockImpl() *block.Service {
  352. return s.block
  353. }
  354. func (s *Service) cacheRecentRealnameImage(ctx context.Context) {
  355. images, err := s.dao.RecentRealnameApplyImg(ctx, time.Minute*2)
  356. if err != nil {
  357. log.Warn("Failed to get recent realname apply image: %+v", err)
  358. return
  359. }
  360. for _, image := range images {
  361. data, _ := s.dao.GetRealnameImageCache(ctx, image.IMGData)
  362. if len(data) > 0 {
  363. log.Info("This image has already been cached: %s", image.IMGData)
  364. continue
  365. }
  366. data, err := s.FetchRealnameImage(ctx, asIMGToken(image.IMGData))
  367. if err != nil {
  368. log.Warn("Failed to fetch realname image to cache: %s: %+v", image.IMGData, err)
  369. continue
  370. }
  371. if err := s.dao.SetRealnameImageCache(ctx, image.IMGData, data); err != nil {
  372. log.Warn("Failed to set realname image cache: %s: %+v", image.IMGData, err)
  373. continue
  374. }
  375. log.Info("Succeeded to cache realname image: %s", image.IMGData)
  376. }
  377. }