bfs.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. package dao
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/hmac"
  6. "crypto/sha1"
  7. "encoding/base64"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "mime/multipart"
  12. "net/http"
  13. "net/url"
  14. "path"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "go-common/app/interface/main/upload/conf"
  19. "go-common/library/ecode"
  20. "go-common/library/log"
  21. )
  22. // Bfs .
  23. type Bfs struct {
  24. bfsURL string
  25. waterMarkURL string
  26. imageGenURL string
  27. client *http.Client
  28. wmClient *http.Client
  29. imageGenClient *http.Client
  30. }
  31. // NewBfs .
  32. func NewBfs(c *conf.Config) *Bfs {
  33. return &Bfs{
  34. bfsURL: c.Bfs.BfsURL,
  35. waterMarkURL: c.Bfs.WaterMarkURL,
  36. imageGenURL: c.Bfs.ImageGenURL,
  37. client: &http.Client{
  38. Timeout: time.Duration(c.Bfs.TimeOut),
  39. },
  40. wmClient: &http.Client{
  41. Timeout: time.Duration(c.Bfs.WmTimeOut),
  42. },
  43. imageGenClient: &http.Client{
  44. Timeout: time.Duration(c.Bfs.ImageGenTimeOut),
  45. },
  46. }
  47. }
  48. // GenImage gen a image.
  49. func (b *Bfs) GenImage(ctx context.Context, wmKey, wmText string, distance int, vertical bool) (res []byte, height, width int, hasher string, err error) {
  50. var (
  51. params = url.Values{}
  52. resp *http.Response
  53. )
  54. params.Set("wm_key", wmKey)
  55. params.Set("wm_text", wmText)
  56. params.Set("distance", strconv.Itoa(distance))
  57. params.Set("vertical", strconv.FormatBool(vertical))
  58. if resp, err = b.imageGenClient.PostForm(b.imageGenURL, params); err != nil {
  59. return
  60. }
  61. defer resp.Body.Close()
  62. if resp.StatusCode != http.StatusOK {
  63. log.Error("bfs.genImage.status(%v)", resp.StatusCode)
  64. }
  65. switch resp.StatusCode {
  66. case http.StatusOK:
  67. case http.StatusBadRequest:
  68. err = ecode.RequestErr
  69. return
  70. case http.StatusMethodNotAllowed:
  71. err = ecode.MethodNotAllowed
  72. return
  73. case http.StatusInternalServerError:
  74. err = ecode.ServerErr
  75. return
  76. default:
  77. err = ecode.ServerErr
  78. return
  79. }
  80. if height, err = strconv.Atoi(resp.Header.Get("O-Height")); err != nil {
  81. log.Error("bfs.genImage.O-Height,err(%v)", err)
  82. return
  83. }
  84. if width, err = strconv.Atoi(resp.Header.Get("O-Width")); err != nil {
  85. log.Error("bfs.genImage.O-Width,err(%v)", err)
  86. return
  87. }
  88. hasher = resp.Header.Get("Md5")
  89. res, err = ioutil.ReadAll(resp.Body)
  90. return
  91. }
  92. // Watermark generate watermark image by key and text.
  93. func (b *Bfs) Watermark(ctx context.Context, data []byte, contentType, wmKey, wmText string, paddingX, paddingY int, wmScale float64) (res []byte, err error) {
  94. var (
  95. resp *http.Response
  96. bw io.Writer
  97. req *http.Request
  98. ext string
  99. )
  100. buf := new(bytes.Buffer)
  101. w := multipart.NewWriter(buf)
  102. if bw, err = w.CreateFormFile("file", "1.jpg"); err != nil {
  103. return
  104. }
  105. if _, err = bw.Write(data); err != nil {
  106. return
  107. }
  108. w.WriteField("wm_key", wmKey)
  109. w.WriteField("wm_text", wmText)
  110. w.WriteField("padding_x", strconv.Itoa(paddingX))
  111. w.WriteField("padding_y", strconv.Itoa(paddingY))
  112. w.WriteField("wm_scale", strconv.FormatFloat(wmScale, 'f', 2, 64))
  113. if ext = path.Base(contentType); ext == "jpeg" {
  114. ext = "jpg"
  115. }
  116. w.WriteField("ext", fmt.Sprintf(".%s", ext))
  117. if err = w.Close(); err != nil {
  118. return
  119. }
  120. if req, err = http.NewRequest(http.MethodPost, b.waterMarkURL, buf); err != nil {
  121. return
  122. }
  123. req.Header.Set("Content-Type", w.FormDataContentType())
  124. if resp, err = b.wmClient.Do(req); err != nil {
  125. return
  126. }
  127. defer resp.Body.Close()
  128. if resp.StatusCode != http.StatusOK {
  129. log.Error("bfs.waterMark.status(%v)", resp.StatusCode)
  130. err = ecode.ServerErr
  131. return
  132. }
  133. res, err = ioutil.ReadAll(resp.Body)
  134. return
  135. }
  136. // Upload upload file to bfs.
  137. func (b *Bfs) Upload(ctx context.Context, key, secret, contentType, bucket, dir, filename string, data []byte) (location, etag string, err error) {
  138. dir = strings.Trim(dir, "/")
  139. var (
  140. buf = new(bytes.Buffer)
  141. fname = path.Join(dir, filename)
  142. )
  143. // 多级目录上传,request url必须以 / 结尾
  144. if filename == "" && dir != "" {
  145. fname = fname + "/"
  146. }
  147. reqURL := fmt.Sprintf("http://%s/bfs/%s/%s", b.bfsURL, bucket, fname)
  148. if _, err = buf.Write(data); err != nil {
  149. log.Error("Upload.buf.Write.error(%v)", err)
  150. err = ecode.ServerErr
  151. return
  152. }
  153. req, err := http.NewRequest(http.MethodPut, reqURL, buf)
  154. if err != nil {
  155. err = ecode.ServerErr
  156. return
  157. }
  158. auth := b.authorize(key, secret, http.MethodPut, bucket, fname, time.Now().Unix())
  159. req.Header.Add("Content-Type", contentType)
  160. req.Header.Add("Authorization", auth)
  161. resp, err := b.client.Do(req)
  162. if err != nil {
  163. log.Error("Upload.client.Do.error(%v)", err)
  164. err = ecode.ServerErr
  165. return
  166. }
  167. if resp.StatusCode != http.StatusOK {
  168. log.Error("bucket:%s,filename:%s,response code:%+v", bucket, filename, resp.StatusCode)
  169. }
  170. defer resp.Body.Close()
  171. switch resp.StatusCode {
  172. case http.StatusOK:
  173. case http.StatusBadRequest:
  174. err = ecode.RequestErr
  175. return
  176. case http.StatusUnauthorized:
  177. // 验证不通过
  178. err = ecode.BfsUploadAuthErr
  179. return
  180. case http.StatusRequestEntityTooLarge:
  181. err = ecode.FileTooLarge
  182. return
  183. case http.StatusNotFound:
  184. err = ecode.NothingFound
  185. return
  186. case http.StatusMethodNotAllowed:
  187. err = ecode.MethodNotAllowed
  188. return
  189. case http.StatusServiceUnavailable:
  190. err = ecode.BfsUploadServiceUnavailable
  191. return
  192. case http.StatusInternalServerError:
  193. err = ecode.ServerErr
  194. return
  195. default:
  196. err = ecode.BfsUploadStatusErr
  197. return
  198. }
  199. code, err := strconv.Atoi(resp.Header.Get("Code"))
  200. if err != nil || code != 200 {
  201. log.Error("bucket:%s,dir:%s,filename:%s response.Header.Code(%s) error(%v)", bucket, dir, filename, resp.Header.Get("Code"), err)
  202. err = ecode.BfsUploadCodeErr
  203. return
  204. }
  205. location = resp.Header.Get("location")
  206. etag = resp.Header.Get("etag")
  207. return
  208. }
  209. // authorize generate authorization
  210. func (b *Bfs) authorize(key, secret, method, bucket, fileName string, expire int64) string {
  211. content := fmt.Sprintf("%s\n%s\n%s\n%d\n", method, bucket, fileName, expire)
  212. mac := hmac.New(sha1.New, []byte(secret))
  213. mac.Write([]byte(content))
  214. signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))
  215. return fmt.Sprintf("%s:%s:%d", key, signature, expire)
  216. }