material_controller.go 4.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. package mpwechat
  2. import (
  3. base_ctl "SCRM/controllers"
  4. "SCRM/enums"
  5. "SCRM/models"
  6. "SCRM/service/wechat_service"
  7. "bytes"
  8. "encoding/json"
  9. "mime/multipart"
  10. "sync"
  11. "time"
  12. "io"
  13. "io/ioutil"
  14. "github.com/astaxie/beego"
  15. "github.com/astaxie/beego/httplib"
  16. )
  17. func MpMaterialCtlRegistRouters() {
  18. beego.Router("/api/mpwechat/media/add_material", &MpMaterialAPIController{}, "Post:AddMaterial")
  19. beego.Router("/api/mpwechat/media/material", &MpMaterialAPIController{}, "Get:GetMaterials")
  20. }
  21. type MpMaterialAPIController struct {
  22. base_ctl.BaseAuthAPIController
  23. }
  24. type MultipartFormField struct {
  25. IsFile bool
  26. Name string
  27. FileName string
  28. Value io.Reader
  29. }
  30. var mediaBufferPool = sync.Pool{
  31. New: func() interface{} {
  32. return bytes.NewBuffer(make([]byte, 0, 10<<20)) // 10MB
  33. },
  34. }
  35. func (c MpMaterialAPIController) AddMaterial() {
  36. adminUserInfo := c.GetAdminUserInfo()
  37. authorization, err := wechat_service.GetAuthorizationByOrgID(adminUserInfo.CurrentOrgId)
  38. if err != nil {
  39. c.ServeFailJsonSend(enums.ErrorCodeDataException, "上传失败:("+err.Error()+")")
  40. return
  41. }
  42. if authorization == nil || authorization.AuthorizerStatus != 1 {
  43. c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:(公众号未授权)")
  44. return
  45. }
  46. file, head, err := c.GetFile("file")
  47. if err != nil {
  48. c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err.Error()+")")
  49. return
  50. }
  51. defer file.Close()
  52. var fields = []MultipartFormField{
  53. {
  54. IsFile: true,
  55. Name: "media",
  56. FileName: head.Filename,
  57. Value: file,
  58. },
  59. }
  60. buffer := mediaBufferPool.Get().(*bytes.Buffer)
  61. buffer.Reset()
  62. defer mediaBufferPool.Put(buffer)
  63. multipartWriter := multipart.NewWriter(buffer)
  64. for i := 0; i < len(fields); i++ {
  65. if field := &fields[i]; field.IsFile {
  66. partWriter, err3 := multipartWriter.CreateFormFile(field.Name, field.FileName)
  67. if err3 != nil {
  68. c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err3.Error()+")")
  69. return
  70. }
  71. if _, err3 = io.Copy(partWriter, field.Value); err3 != nil {
  72. c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err3.Error()+")")
  73. return
  74. }
  75. } else {
  76. partWriter, err3 := multipartWriter.CreateFormField(field.Name)
  77. if err3 != nil {
  78. c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err3.Error()+")")
  79. return
  80. }
  81. if _, err3 = io.Copy(partWriter, field.Value); err3 != nil {
  82. c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err3.Error()+")")
  83. return
  84. }
  85. }
  86. }
  87. if err = multipartWriter.Close(); err != nil {
  88. c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err.Error()+")")
  89. return
  90. }
  91. requestBodyBytes := buffer.Bytes()
  92. requestBodyType := multipartWriter.FormDataContentType()
  93. url := "https://api.weixin.qq.com/cgi-bin/material/add_material?type=image&access_token=" + authorization.AuthorizerAccessToken
  94. res := httplib.Post(url)
  95. res.Header("Content-Type", requestBodyType)
  96. response, err := res.Body(requestBodyBytes).Response()
  97. if err != nil {
  98. c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err.Error()+")")
  99. return
  100. }
  101. respBody, err := ioutil.ReadAll(response.Body)
  102. if err != nil {
  103. c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err.Error()+")")
  104. return
  105. }
  106. var resMaterial wechat_service.ResAddMaterial
  107. err = json.Unmarshal(respBody, &resMaterial)
  108. if err != nil {
  109. c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err.Error()+")")
  110. return
  111. }
  112. if resMaterial.ErrCode != 0 {
  113. c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+resMaterial.ErrMsg+")")
  114. return
  115. }
  116. mediaID := resMaterial.MediaID
  117. mediaUrl := resMaterial.URL
  118. var media models.WechatMedias
  119. media.UserOrgId = adminUserInfo.CurrentOrgId
  120. media.MediaId = mediaID
  121. media.MediaUrl = mediaUrl
  122. media.Msgtype = "image"
  123. media.MediaTitle = head.Filename
  124. media.CreatedTime = time.Now().Unix()
  125. media.UpdatedTime = time.Now().Unix()
  126. media.MediaStatus = 1
  127. err = wechat_service.SaveMaterial(&media)
  128. if err != nil {
  129. c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err.Error()+")")
  130. return
  131. }
  132. returnData := make(map[string]interface{}, 0)
  133. returnData["media"] = media
  134. c.ServeSuccessJSON(returnData)
  135. return
  136. }
  137. func (c *MpMaterialAPIController) GetMaterials() {
  138. page, _ := c.GetInt64("page", 1)
  139. limit, _ := c.GetInt64("limit", 10)
  140. mediaType := c.GetString("media_type")
  141. if page <= 0 {
  142. page = 1
  143. }
  144. if limit <= 0 {
  145. limit = 10
  146. }
  147. adminUserInfo := c.GetAdminUserInfo()
  148. medias, total, err := wechat_service.GetPageMaterials(adminUserInfo.CurrentOrgId, page, limit, mediaType)
  149. if err != nil {
  150. c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "拉取失败:("+err.Error()+")")
  151. return
  152. }
  153. returnData := make(map[string]interface{}, 0)
  154. returnData["medias"] = medias
  155. returnData["total"] = total
  156. c.ServeSuccessJSON(returnData)
  157. return
  158. }