record.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. package service
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha1"
  6. "encoding/hex"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "go-common/app/interface/main/upload/model"
  14. "go-common/library/ecode"
  15. "go-common/library/log"
  16. "go-common/library/queue/databus/report"
  17. )
  18. const (
  19. _genImageContentType = "image/png"
  20. )
  21. // GenImageUpload generate watermark image by text and upload it.
  22. func (s *Service) GenImageUpload(ctx context.Context, uploadKey string, wmKey, wmText string, distance int, vertical bool) (res *model.ResultWm, err error) {
  23. var image []byte
  24. res = new(model.ResultWm)
  25. key, secret, bucket := s.authorizeInfo(uploadKey)
  26. if image, res.Height, res.Width, res.Md5, err = s.bfs.GenImage(ctx, wmKey, wmText, distance, vertical); err != nil {
  27. return
  28. }
  29. res.Location, _, err = s.bfs.Upload(ctx, key, secret, _genImageContentType, bucket, "", "", image)
  30. return
  31. }
  32. // Upload upload by key and secret.
  33. func (s *Service) Upload(ctx context.Context, uploadKey, uploadToken, contentType string, data []byte) (result *model.Result, err error) {
  34. if !s.verify(uploadKey, uploadToken) {
  35. err = ecode.AccessDenied
  36. return
  37. }
  38. key, secret, bucket := s.authorizeInfo(uploadKey)
  39. if contentType == "" {
  40. contentType = http.DetectContentType(data)
  41. }
  42. location, etag, err := s.bfs.Upload(ctx, key, secret, contentType, bucket, "", "", data)
  43. if err != nil {
  44. return
  45. }
  46. result = &model.Result{
  47. Location: location,
  48. Etag: etag,
  49. }
  50. return
  51. }
  52. // authorizeInfo get authorize info by upload key.
  53. func (s *Service) authorizeInfo(uploadKey string) (key, secret, bucket string) {
  54. key = s.c.BfsBucket.Key
  55. secret = s.c.BfsBucket.Sercet
  56. bucket = s.c.BfsBucket.Bucket
  57. for _, a := range s.c.Auths {
  58. if a.AppKey == uploadKey && a.BfsBucket != nil {
  59. key = a.BfsBucket.Key
  60. secret = a.BfsBucket.Sercet
  61. bucket = a.BfsBucket.Bucket
  62. break
  63. }
  64. }
  65. return
  66. }
  67. func (s *Service) verify(key, token string) bool {
  68. var (
  69. expire, now, delta int64
  70. err error
  71. )
  72. for _, auth := range s.c.Auths {
  73. if key == auth.AppKey {
  74. srcs := strings.Split(token, ":")
  75. if len(srcs) != 2 {
  76. log.Error("verify error: len(srcs) != 2")
  77. return false
  78. }
  79. if expire, err = strconv.ParseInt(srcs[1], 10, 64); err != nil {
  80. log.Error("verify error: expire not int (%v)", err)
  81. return false
  82. }
  83. if s.gen(auth.AppKey, auth.AppSercet, expire) != srcs[0] {
  84. log.Error("verify error: s.gen(%s,%s,%d) != srcs[0]:%s", auth.AppKey, auth.AppSercet, expire, srcs[0])
  85. return false
  86. }
  87. now = time.Now().Unix()
  88. // > ±15 min is forbidden
  89. if expire > now {
  90. delta = expire - now
  91. } else {
  92. delta = now - expire
  93. }
  94. if delta > 900 {
  95. log.Error("verify error: delta > 900")
  96. return false
  97. }
  98. return true
  99. }
  100. }
  101. return false
  102. }
  103. func (s *Service) gen(key, sercet string, now int64) string {
  104. sha1 := sha1.New()
  105. sha1.Write([]byte(fmt.Sprintf("i love bilibili %s:%d", sercet, now)))
  106. return hex.EncodeToString(sha1.Sum([]byte("")))
  107. }
  108. // UploadRecord .
  109. func (s *Service) UploadRecord(ctx context.Context, action model.UploadActionType, mid int64, up *model.UploadParam, data []byte) (result *model.Result, err error) {
  110. var (
  111. location string
  112. etag string
  113. b *model.Bucket
  114. ok bool
  115. )
  116. if b, ok = s.bucketCache[up.Bucket]; !ok {
  117. err = ecode.BfsUplaodBucketNotExist
  118. log.Error("read bucket items failed: (%s)", up.Bucket)
  119. return
  120. }
  121. // content-type
  122. if up.ContentType == "" {
  123. up.ContentType = http.DetectContentType(data)
  124. }
  125. // check limit if dir not null
  126. if up.Dir != "" {
  127. up.Dir = strings.Trim(up.Dir, "/")
  128. //todo: dir limit if conf exist
  129. if err = s.dirlimit(up.Bucket, up.Dir, up.ContentType, data); err != nil {
  130. return
  131. }
  132. }
  133. log.Info("upload record params:%+v", up)
  134. if up.WmKey != "" || up.WmText != "" {
  135. var image []byte
  136. if image, err = s.bfs.Watermark(ctx, data, up.ContentType, up.WmKey, up.WmText, up.WmPaddingX, up.WmPaddingY, up.WmScale); err != nil {
  137. log.Error("Upload.Watermark data length(%d) params(%+v) error(%v)", len(data), up, err)
  138. } else {
  139. data = image
  140. }
  141. }
  142. if location, etag, err = s.bfs.Upload(ctx, b.KeyID, b.KeySecret, up.ContentType, up.Bucket, up.Dir, up.FileName, data); err != nil {
  143. return
  144. }
  145. uri, err := url.Parse(location)
  146. if err != nil {
  147. return
  148. }
  149. //todo: add user report
  150. // http://info.bilibili.co/pages/viewpage.action?pageId=8474335
  151. uInfo := &report.UserInfo{
  152. Mid: mid,
  153. Platform: "bfs-upload-interface",
  154. Build: 1,
  155. Business: 61, //bfs-upload
  156. Action: action.String(),
  157. Ctime: time.Now(),
  158. Index: []interface{}{location, up.Bucket, up.Dir, uri.Path}, // path is filename
  159. Content: map[string]interface{}{
  160. "upload_param": up,
  161. },
  162. }
  163. report.User(uInfo)
  164. result = &model.Result{
  165. Location: location,
  166. Etag: etag,
  167. }
  168. return
  169. }
  170. // UploadAdminRecord no dir limit upload method.
  171. func (s *Service) UploadAdminRecord(ctx context.Context, action model.UploadActionType, up *model.UploadParam, data []byte) (result *model.Result, err error) {
  172. var (
  173. location, etag string
  174. b *model.Bucket
  175. ok bool
  176. )
  177. if b, ok = s.bucketCache[up.Bucket]; !ok {
  178. err = ecode.BfsUplaodBucketNotExist
  179. log.Error("read bucket items failed: (%s)", up.Bucket)
  180. return
  181. }
  182. if up.ContentType == "" {
  183. up.ContentType = http.DetectContentType(data)
  184. }
  185. if location, etag, err = s.bfs.Upload(ctx, b.KeyID, b.KeySecret, up.ContentType, up.Bucket, up.Dir, up.FileName, data); err != nil {
  186. return
  187. }
  188. uri, err := url.Parse(location)
  189. if err != nil {
  190. return
  191. }
  192. //todo: add user report
  193. // http://info.bilibili.co/pages/viewpage.action?pageId=8474335
  194. uInfo := &report.UserInfo{
  195. Mid: 0,
  196. Platform: "bfs-upload-interface",
  197. Build: 1,
  198. Business: 61, //bfs-upload
  199. Action: action.String(), //操作类型
  200. Ctime: time.Now(),
  201. Index: []interface{}{location, up.Bucket, up.Dir, uri.Path}, // path is filename in bfs
  202. Content: map[string]interface{}{
  203. "upload_param": up,
  204. },
  205. }
  206. report.User(uInfo)
  207. result = &model.Result{
  208. Location: location,
  209. Etag: etag,
  210. }
  211. return
  212. }
  213. func (s *Service) dirlimit(bucket, dir, contentType string, data []byte) (err error) {
  214. var (
  215. width int
  216. height int
  217. dirlimit *model.DirConfig
  218. ok bool
  219. )
  220. dir = strings.Trim(dir, "/")
  221. if dirlimit, ok = s.bucketCache[bucket].DirLimit[dir]; !ok {
  222. return
  223. }
  224. if len(dirlimit.Pic.AllowTypeSlice) != 0 {
  225. var isAllow bool
  226. for _, ctype := range dirlimit.Pic.AllowTypeSlice {
  227. if ctype == contentType {
  228. isAllow = true
  229. }
  230. }
  231. if !isAllow {
  232. log.Error("image content type illegal,bucket(%s),dir(%s),content type(%s)", bucket, dir, contentType)
  233. err = ecode.BfsUploadFileContentTypeIllegal
  234. return
  235. }
  236. }
  237. if dirlimit.Pic.FileSize > 0 && len(data) > dirlimit.Pic.FileSize {
  238. log.Error("data is too large, bucket(%s), dir(%s)", bucket, dir)
  239. err = ecode.FileTooLarge
  240. return
  241. }
  242. dataReader := bytes.NewReader(data)
  243. if width, height, err = Pixel(dataReader); err != nil {
  244. log.Error("get pixal error(%v), content-type maybe not support, bucket(%s), dir(%s)", err, bucket, dir)
  245. err = nil
  246. return
  247. }
  248. if (dirlimit.Pic.MinPixelWidthSize != 0 && width < dirlimit.Pic.MinPixelWidthSize) || (dirlimit.Pic.MaxPixelWidthSize != 0 && width > dirlimit.Pic.MaxPixelWidthSize) {
  249. log.Error("image width illegal, bucket(%s), dir(%s)", bucket, dir)
  250. err = ecode.BfsUploadFilePixelWidthIllegal
  251. return
  252. }
  253. if (dirlimit.Pic.MinPixelWidthSize != 0 && height < dirlimit.Pic.MinPixelHeightSize) || (dirlimit.Pic.MaxPixelWidthSize != 0 && height > dirlimit.Pic.MaxPixelHeightSize) {
  254. log.Error("image height illegal, bucket(%s), dir(%s)", bucket, dir)
  255. err = ecode.BfsUploadFilePixelHeightIllegal
  256. return
  257. }
  258. if dirlimit.Pic.MinAspectRatio != 0 && float64(width/height) < dirlimit.Pic.MinAspectRatio {
  259. log.Error("image MinAspectRatio illegal, bucket(%s), dir(%s)", bucket, dir)
  260. err = ecode.BfsUploadFilePixelAspectRatioIllegal
  261. return
  262. }
  263. if dirlimit.Pic.MaxAspectRatio != 0 && float64(width/height) > dirlimit.Pic.MaxAspectRatio {
  264. log.Error("image MaxAspectRatio illegal, bucket(%s), dir(%s)", bucket, dir)
  265. err = ecode.BfsUploadFilePixelAspectRatioIllegal
  266. return
  267. }
  268. return
  269. }