image_record.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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/service/cache"
  15. "net/http"
  16. "net/url"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. type ImageRecordService struct {
  22. cache cache.Cache
  23. }
  24. //创建图片记录
  25. func (s *ImageRecordService) CreateImageRecord(record levelMonitor.ImageRecord) (err error) {
  26. //获取今日日期
  27. date := time.Now().Format("2006-01-02")
  28. key := fmt.Sprintf(cache.UploadImageNum, date, record.TaskId)
  29. ctx := context.Background()
  30. num, _ := s.cache.GetCacheNum(ctx, key)
  31. if num > 50 {
  32. return errors.New("数据上传已到上限")
  33. }
  34. var entity levelMonitor.ImageRecord
  35. //创建日期赋值
  36. record.CreateDate = date
  37. record.Status = 2
  38. //查找数据库是否存在此账号此游戏今日记录
  39. err = global.GVA_DB.Model(&levelMonitor.ImageRecord{}).Where("task_id = ? and account = ? and create_date = ?", record.TaskId, record.Account, date).First(&entity).Error
  40. if !errors.Is(err, gorm.ErrRecordNotFound) {
  41. return errors.New("此记录已存在,请勿重复添加")
  42. }
  43. err = global.GVA_DB.Model(&levelMonitor.ImageRecord{}).Omit("create_time", "update_time").Create(&record).Error
  44. if err != nil {
  45. return err
  46. }
  47. s.cache.SetCacheNum(ctx, key)
  48. go s.ImageIdentify(record)
  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.Model(&levelMonitor.ImageRecord{}).Delete("create_date < ?", markTime).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) {
  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)
  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)
  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)
  149. return
  150. }
  151. s.UpdateImageRecordStatus(record.Id, string(body), 1)
  152. identify := 0
  153. if data.WordsResultNum == 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. return
  170. }
  171. UpdateGameAccountIdentify(record.Account, record.TaskId, identify)
  172. return
  173. }
  174. func (s *ImageRecordService) UpdateImageRecordStatus(id int, result string, status int) {
  175. update := map[string]interface{}{
  176. "result": result,
  177. "status": status,
  178. }
  179. global.GVA_DB.Model(&levelMonitor.ImageRecord{}).Where("id", id).Updates(update)
  180. }
  181. func Request(baiduToken, content string) (body []byte, err error) {
  182. reqUrl := "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + baiduToken
  183. var (
  184. params = url.Values{}
  185. )
  186. params.Set("image", content)
  187. requestData := params.Encode()
  188. payload := strings.NewReader(requestData)
  189. client := &http.Client{}
  190. req, err := http.NewRequest("POST", reqUrl, payload)
  191. if err != nil {
  192. fmt.Println(err)
  193. return
  194. }
  195. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  196. req.Header.Add("Accept", "application/json")
  197. res, err := client.Do(req)
  198. if err != nil {
  199. global.GVA_LOG.Error("request Identify fail", zap.Error(err))
  200. return
  201. }
  202. defer res.Body.Close()
  203. body, err = ioutil.ReadAll(res.Body)
  204. if err != nil {
  205. global.GVA_LOG.Error("Read Body Fail", zap.Error(err))
  206. return
  207. }
  208. fmt.Println(string(body))
  209. return
  210. }
  211. // 更新game_acount
  212. func UpdateGameAccountIdentify(account string, gameId int, identify int) {
  213. global.GVA_DB.Table("game_account").Where("game_id", gameId).Where("account", account).Update("identify", identify)
  214. }
  215. /**
  216. * 使用 AK,SK 生成鉴权签名(Access Token)
  217. * @return string 鉴权签名信息(Access Token)
  218. */
  219. func GetAccessToken() (string, error) {
  220. ctx := context.Background()
  221. token, err := global.GVA_REDIS.Get(ctx, BAIDU_IDENTIFY).Result()
  222. if err != nil || token == "" {
  223. reqUrl := "https://aip.baidubce.com/oauth/2.0/token"
  224. postData := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s", API_KEY, SECRET_KEY)
  225. resp, err := http.Post(reqUrl, "application/x-www-form-urlencoded", strings.NewReader(postData))
  226. if err != nil {
  227. fmt.Println(err)
  228. return "", err
  229. }
  230. defer resp.Body.Close()
  231. body, err := ioutil.ReadAll(resp.Body)
  232. if err != nil {
  233. fmt.Println(err)
  234. return "", err
  235. }
  236. accessTokenObj := map[string]string{}
  237. json.Unmarshal(body, &accessTokenObj)
  238. global.GVA_REDIS.Set(ctx, BAIDU_IDENTIFY, accessTokenObj["access_token"], time.Hour*24*29)
  239. return accessTokenObj["access_token"], err
  240. }
  241. return token, err
  242. }