scrm-go

activity_short_url_job.go 4.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. package jobcron
  2. import (
  3. "SCRM/service"
  4. "SCRM/utils"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. "time"
  12. "github.com/astaxie/beego"
  13. "github.com/robfig/cron"
  14. )
  15. // cron表达式 https://www.cnblogs.com/zuxingyu/p/6023919.html
  16. var activityShortUrlCronJob *cron.Cron
  17. func init() {
  18. activityShortUrlCronJob = cron.New()
  19. spec := "0 0 0 * * ?" // 每天晚上12点整检查活动短链接库存充不充足
  20. activityShortUrlCronJob.AddFunc(spec, func() {
  21. CreateActivityShortURLIfNeeded()
  22. })
  23. }
  24. type CreateShortURLServiceMaxId struct {
  25. Value int
  26. }
  27. func CreateActivityShortURLIfNeeded() {
  28. var maxActivityId CreateShortURLServiceMaxId
  29. service.PatientReadDB().Raw("SELECT MAX(id) AS value FROM sgj_patient_activity").Scan(&maxActivityId)
  30. utils.TraceLog("当前最大的活动 ID 为:%v", maxActivityId)
  31. var maxShortURLId CreateShortURLServiceMaxId
  32. service.PatientReadDB().Raw("SELECT MAX(id) AS value FROM sgj_patient_activity_wx_share").Scan(&maxShortURLId)
  33. utils.TraceLog("当前最大的活动短链接 ID 为:%v", maxShortURLId)
  34. if maxShortURLId.Value-maxActivityId.Value <= 300 {
  35. utils.TraceLog("即将生成更多活动短链接")
  36. go CreateMoreActivityShortURL(maxShortURLId.Value)
  37. } else {
  38. utils.TraceLog("活动短链接充足,无需生成")
  39. }
  40. }
  41. // 新浪短链接服务示例 https://www.cnblogs.com/azure/archive/2012/08/29/WeiboAPI.html
  42. func CreateMoreActivityShortURL(lastShortURLID int) {
  43. var maxUrlCountPerRequest int = 20
  44. createCount, _ := beego.AppConfig.Int("create_short_url_count_every_time")
  45. pageCount := createCount / maxUrlCountPerRequest
  46. tx := service.PatientWriteDB().Begin()
  47. for i := 0; i < pageCount; i++ {
  48. longURLParams := make([]string, 0, maxUrlCountPerRequest)
  49. for longURLIndex := 1; longURLIndex < maxUrlCountPerRequest+1; longURLIndex++ {
  50. id := lastShortURLID + i*maxUrlCountPerRequest + longURLIndex
  51. param := fmt.Sprintf("url_long=%v", fmt.Sprintf("%v/weixin/activity/%v", beego.AppConfig.String("weixinwebdomain"), id))
  52. longURLParams = append(longURLParams, param)
  53. }
  54. urlStr := fmt.Sprintf("http://api.weibo.com/2/short_url/shorten.json?source=2849184197&%v", strings.Join(longURLParams, "&"))
  55. u, _ := url.Parse(urlStr)
  56. u.RawQuery = u.Query().Encode()
  57. // fmt.Println(u.String())
  58. resp, requestErr := http.Get(u.String())
  59. if requestErr != nil {
  60. utils.ErrorLog("http.Get error: %v", requestErr)
  61. continue
  62. }
  63. result, readErr := ioutil.ReadAll(resp.Body)
  64. resp.Body.Close()
  65. if readErr != nil {
  66. utils.ErrorLog("ioutil.ReadAll error: %v", readErr)
  67. continue
  68. }
  69. // fmt.Println(string(result))
  70. var respJSON map[string]interface{}
  71. if err := json.Unmarshal([]byte(string(result)), &respJSON); err != nil {
  72. utils.ErrorLog("json.Unmarshal error: %v\n", err)
  73. continue
  74. }
  75. // fmt.Printf("resp: %v\n", respJSON)
  76. if respJSON["error"] != nil {
  77. utils.ErrorLog("request error: %v\n", respJSON)
  78. continue
  79. }
  80. urlJSONs := respJSON["urls"].([]interface{})
  81. now := time.Now().Unix()
  82. valueStrs := make([]string, 0, len(urlJSONs))
  83. values := make([]interface{}, 0, len(urlJSONs)*9)
  84. for index, url := range urlJSONs {
  85. urlJSON := url.(map[string]interface{})
  86. shortURL := urlJSON["url_short"].(string)
  87. fmt.Println("shortURL是什么")
  88. id := lastShortURLID + i*maxUrlCountPerRequest + (index + 1)
  89. // CreateActivityWxShareWithShortURL(id, shortURL)
  90. // (`id`,`activity_id`,`title`,`subtitle`,`image`,`status`,`ctime`,`mtime`,`short_url`)
  91. valueStrs = append(valueStrs, "(?, ?, ?, ?, ?, ?, ?, ?, ?)")
  92. values = append(values, id)
  93. values = append(values, id)
  94. values = append(values, "")
  95. values = append(values, "")
  96. values = append(values, "")
  97. values = append(values, 1)
  98. values = append(values, now)
  99. values = append(values, now)
  100. values = append(values, shortURL)
  101. }
  102. sql := fmt.Sprintf("INSERT INTO sgj_patient_activity_wx_share (id, activity_id, title, subtitle, image, status, ctime, mtime, short_url) VALUES %v;", strings.Join(valueStrs, ", "))
  103. if err := tx.Exec(sql, values...).Error; err != nil {
  104. utils.ErrorLog("插入活动短链接失败: %v", err)
  105. tx.Rollback()
  106. break
  107. }
  108. }
  109. tx.Commit()
  110. utils.TraceLog("完成生成更多活动短链接")
  111. }
  112. func BeginCreateActivityShortURLCronJob() {
  113. activityShortUrlCronJob.Start()
  114. }