image_record.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. package levelMonitor
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "go.uber.org/zap"
  8. "gorm.io/gorm"
  9. "io/ioutil"
  10. "log-server/global"
  11. "log-server/model/common/request"
  12. "log-server/model/levelMonitor"
  13. levelRequest "log-server/model/levelMonitor/request"
  14. "log-server/model/log"
  15. "log-server/service/cache"
  16. "net/http"
  17. "net/url"
  18. "strconv"
  19. "strings"
  20. "time"
  21. )
  22. type ImageRecordService struct {
  23. cache cache.Cache
  24. }
  25. //创建图片记录
  26. func (s *ImageRecordService) CreateImageRecord(record levelMonitor.ImageRecord) (err error) {
  27. //获取今日日期
  28. date := time.Now().Format("2006-01-02")
  29. key := fmt.Sprintf(cache.UploadImageNum, date, record.TaskId)
  30. ctx := context.Background()
  31. num, _ := s.cache.GetCacheNum(ctx, key)
  32. if num > 50 {
  33. return errors.New("数据上传已到上限")
  34. }
  35. var entity levelMonitor.ImageRecord
  36. //创建日期赋值
  37. record.CreateDate = date
  38. record.Status = 2
  39. //查找数据库是否存在此账号此游戏今日记录
  40. err = global.GVA_DB.Model(&levelMonitor.ImageRecord{}).Where("task_id = ? and account = ? and create_date = ?", record.TaskId, record.Account, date).First(&entity).Error
  41. if !errors.Is(err, gorm.ErrRecordNotFound) {
  42. return errors.New("此记录已存在,请勿重复添加")
  43. }
  44. err = global.GVA_DB.Model(&levelMonitor.ImageRecord{}).Omit("create_time", "update_time").Create(&record).Error
  45. if err != nil {
  46. return err
  47. }
  48. go s.ImageIdentify(record, key)
  49. return
  50. }
  51. func (s *ImageRecordService) UploadOrNot(record levelMonitor.ImageRecord) (err error) {
  52. date := time.Now().Format("2006-01-02")
  53. key := fmt.Sprintf(cache.UploadImageNum, date, record.TaskId)
  54. ctx := context.Background()
  55. num, _ := s.cache.GetCacheNum(ctx, key)
  56. if num > 50 {
  57. return errors.New("数据上传已到上限")
  58. }
  59. return nil
  60. }
  61. //删除三日前的图片记录
  62. func (s *ImageRecordService) DeleteExpireImageRecord() {
  63. markTime := time.Now().Add(-time.Hour * 48).Format("2006-01-02")
  64. err := global.GVA_DB.Where("create_date < ?", markTime).Delete(&levelMonitor.ImageRecord{}).Error
  65. if err != nil {
  66. global.GVA_LOG.Info("删除图片信息失败:" + err.Error() + time.Now().Format("2006-01-02 15:04:05"))
  67. }
  68. return
  69. }
  70. //获取图片记录列表
  71. func (s *ImageRecordService) GetImageRecordList(record levelRequest.ImageRecordRequest, info request.PageInfo, order string, desc bool) (recordList []levelMonitor.ImageRecord, total int64, err error) {
  72. limit := info.PageSize
  73. offset := info.PageSize * (info.Page - 1)
  74. db := global.GVA_DB.Model(&levelMonitor.ImageRecord{})
  75. startDate := time.Now().Format("2006-01-02")
  76. endDate := time.Now().Format("2006-01-02")
  77. if len(record.Date) == 2 {
  78. startDate = record.Date[0]
  79. endDate = record.Date[1]
  80. }
  81. //筛选日期
  82. db = db.Where("create_date >= ? and create_date <= ?", startDate, endDate)
  83. if record.TaskId != 0 {
  84. db = db.Where("task_id = ?", record.TaskId)
  85. }
  86. err = db.Count(&total).Error
  87. if err != nil {
  88. return recordList, total, err
  89. } else {
  90. db = db.Limit(limit).Offset(offset)
  91. if order != "" {
  92. var OrderStr string
  93. // 设置有效排序key 防止sql注入
  94. // 感谢 Tom4t0 提交漏洞信息
  95. orderMap := make(map[string]bool, 4)
  96. orderMap["task_id"] = true
  97. orderMap["create_date"] = true
  98. orderMap["create_time"] = true
  99. orderMap["update_time"] = true
  100. if orderMap[order] {
  101. if desc {
  102. OrderStr = order + " desc"
  103. } else {
  104. OrderStr = order
  105. }
  106. } else { // didn't matched any order key in `orderMap`
  107. global.GVA_LOG.Error("获取失败!", zap.Error(err))
  108. return recordList, total, err
  109. }
  110. err = db.Order(OrderStr).Find(&recordList).Error
  111. } else {
  112. err = db.Order("id desc").Find(&recordList).Error
  113. }
  114. }
  115. //遍历更改日期格式
  116. for i, _ := range recordList {
  117. recordList[i].CreateDate = recordList[i].CreateDate[:10]
  118. }
  119. return recordList, total, err
  120. }
  121. const API_KEY = "z9GNcyrC7VeV3g1xXEj3YL1s"
  122. const SECRET_KEY = "VASRBsEzeVsyKduSkkflfL87r5yqoqvj"
  123. const BAIDU_IDENTIFY = "baiduIdentifyToken"
  124. func (s *ImageRecordService) ImageIdentify(record levelMonitor.ImageRecord, key string) {
  125. token, err := GetAccessToken()
  126. if err != nil {
  127. global.GVA_LOG.Error("get token fail", zap.Error(err))
  128. s.UpdateImageRecordStatus(record.Id, "get token fail", -1, 0, 0)
  129. return
  130. }
  131. body, err := Request(token, record.ImageBase64)
  132. if err != nil {
  133. global.GVA_LOG.Error("Read Body Fail", zap.Error(err))
  134. s.UpdateImageRecordStatus(record.Id, err.Error(), -1, 0, 0)
  135. return
  136. }
  137. type Data struct {
  138. WordsResult []struct {
  139. Words string `json:"words"`
  140. } `json:"words_result"`
  141. WordsResultNum int `json:"words_result_num"`
  142. LogId int `json:"log_id"`
  143. }
  144. var data Data
  145. err = json.Unmarshal(body, &data)
  146. if err != nil {
  147. global.GVA_LOG.Error("Read Body Fail", zap.Error(err))
  148. s.UpdateImageRecordStatus(record.Id, "Read Body Fail", -1, 0, 0)
  149. return
  150. }
  151. identify := 0
  152. if data.WordsResultNum == 0 {
  153. s.UpdateImageRecordStatus(record.Id, string(body), -1, 0, 0)
  154. return
  155. }
  156. if len(data.WordsResult) > 1 {
  157. for _, words := range data.WordsResult {
  158. i, err := strconv.Atoi(words.Words)
  159. if err == nil {
  160. identify = i
  161. break
  162. }
  163. }
  164. } else {
  165. i, _ := strconv.Atoi(data.WordsResult[0].Words)
  166. identify = i
  167. }
  168. if identify == 0 {
  169. s.UpdateImageRecordStatus(record.Id, string(body), -1, 0, 0)
  170. return
  171. }
  172. var gameAccount log.GameAccount
  173. global.GVA_DB.Where("game_id", record.TaskId).Where("account", record.Account).First(&gameAccount)
  174. s.UpdateImageRecordStatus(record.Id, string(body), 1, gameAccount.UseNum, identify)
  175. UpdateGameAccountIdentify(record.Account, record.TaskId, identify)
  176. ctx := context.Background()
  177. s.cache.SetCacheNum(ctx, key)
  178. return
  179. }
  180. func (s *ImageRecordService) UpdateImageRecordStatus(id int, result string, status int, useNum, identify int) {
  181. update := map[string]interface{}{
  182. "result": result,
  183. "status": status,
  184. "use_num": useNum,
  185. "identify": identify,
  186. }
  187. global.GVA_DB.Model(&levelMonitor.ImageRecord{}).Where("id", id).Updates(update)
  188. }
  189. func Request(baiduToken, content string) (body []byte, err error) {
  190. reqUrl := "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + baiduToken
  191. var (
  192. params = url.Values{}
  193. )
  194. params.Set("image", content)
  195. requestData := params.Encode()
  196. payload := strings.NewReader(requestData)
  197. client := &http.Client{}
  198. req, err := http.NewRequest("POST", reqUrl, payload)
  199. if err != nil {
  200. fmt.Println(err)
  201. return
  202. }
  203. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  204. req.Header.Add("Accept", "application/json")
  205. res, err := client.Do(req)
  206. if err != nil {
  207. global.GVA_LOG.Error("request Identify fail", zap.Error(err))
  208. return
  209. }
  210. defer res.Body.Close()
  211. body, err = ioutil.ReadAll(res.Body)
  212. if err != nil {
  213. global.GVA_LOG.Error("Read Body Fail", zap.Error(err))
  214. return
  215. }
  216. fmt.Println(string(body))
  217. return
  218. }
  219. // 更新game_acount
  220. func UpdateGameAccountIdentify(account string, gameId int, identify int) {
  221. global.GVA_DB.Table("game_account").Where("game_id", gameId).Where("account", account).Update("identify", identify)
  222. }
  223. /**
  224. * 使用 AK,SK 生成鉴权签名(Access Token)
  225. * @return string 鉴权签名信息(Access Token)
  226. */
  227. func GetAccessToken() (string, error) {
  228. ctx := context.Background()
  229. token, err := global.GVA_REDIS.Get(ctx, BAIDU_IDENTIFY).Result()
  230. if err != nil || token == "" {
  231. reqUrl := "https://aip.baidubce.com/oauth/2.0/token"
  232. postData := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s", API_KEY, SECRET_KEY)
  233. resp, err := http.Post(reqUrl, "application/x-www-form-urlencoded", strings.NewReader(postData))
  234. if err != nil {
  235. fmt.Println(err)
  236. return "", err
  237. }
  238. defer resp.Body.Close()
  239. body, err := ioutil.ReadAll(resp.Body)
  240. if err != nil {
  241. fmt.Println(err)
  242. return "", err
  243. }
  244. accessTokenObj := map[string]string{}
  245. json.Unmarshal(body, &accessTokenObj)
  246. global.GVA_REDIS.Set(ctx, BAIDU_IDENTIFY, accessTokenObj["access_token"], time.Hour*24*29)
  247. return accessTokenObj["access_token"], err
  248. }
  249. return token, err
  250. }