oss.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package resource
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "github.com/aliyun/alibaba-cloud-sdk-go/services/sts"
  7. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  8. "hongze/fms_api/global"
  9. "hongze/fms_api/services/alarm_msg"
  10. "hongze/fms_api/utils"
  11. "os"
  12. "time"
  13. )
  14. var (
  15. RoleArn = "acs:ram::1884217364581072:role/hzossrole"
  16. RoleSessionName = "hzossRole"
  17. RAMAccessKeyId = "LTAI5t9S36LXduhTnECVY6Hn"
  18. RAMAccessKeySecret = "V6FG5bdzjKKqMpqEqxeWijJCdzDCuL"
  19. STSTokenCacheKey = "hrms_api:oss:sts_token"
  20. )
  21. // UploadAliyun 图片上传到阿里云
  22. func UploadAliyun(filename, filepath string) (string, error) {
  23. client, err := oss.New(global.CONFIG.AliOss.EndPoint, global.CONFIG.AliOss.AccessKeyId, global.CONFIG.AliOss.AccessKeySecret)
  24. if err != nil {
  25. return "1", err
  26. }
  27. bucket, err := client.Bucket(global.CONFIG.AliOss.BucketName)
  28. if err != nil {
  29. return "2", err
  30. }
  31. path := global.CONFIG.AliOss.UploadDir + time.Now().Format("200601/20060102/")
  32. path += filename
  33. err = bucket.PutObjectFromFile(path, filepath)
  34. if err != nil {
  35. return "3", err
  36. }
  37. path = global.CONFIG.AliOss.ImgHost + path
  38. return path, err
  39. }
  40. // UploadAudioAliyun 音频上传到阿里云
  41. func UploadAudioAliyun(filename, filepath string) (string, error) {
  42. client, err := oss.New(global.CONFIG.AliOss.EndPoint, global.CONFIG.AliOss.AccessKeyId, global.CONFIG.AliOss.AccessKeySecret)
  43. if err != nil {
  44. return "1", err
  45. }
  46. bucket, err := client.Bucket(global.CONFIG.AliOss.BucketName)
  47. if err != nil {
  48. return "2", err
  49. }
  50. path := global.CONFIG.AliOss.UploadAudioDir + time.Now().Format("200601/20060102/")
  51. path += filename
  52. err = bucket.PutObjectFromFile(path, filepath)
  53. if err != nil {
  54. return "3", err
  55. }
  56. path = global.CONFIG.AliOss.ImgHost + path
  57. return path, err
  58. }
  59. // UploadVideoAliyun 视频上传到阿里云
  60. func UploadVideoAliyun(filename, filepath, savePath string) error {
  61. defer func() {
  62. _ = os.Remove(filepath)
  63. }()
  64. client, err := oss.New(global.CONFIG.AliOss.EndPoint, global.CONFIG.AliOss.AccessKeyId, global.CONFIG.AliOss.AccessKeySecret)
  65. if err != nil {
  66. return err
  67. }
  68. bucket, err := client.Bucket(global.CONFIG.AliOss.BucketName)
  69. if err != nil {
  70. return err
  71. }
  72. //path := global.CONFIG.AliOss.UploadAudioDir + time.Now().Format("200601/20060102/")
  73. //path += filename
  74. err = bucket.PutObjectFromFile(savePath, filepath)
  75. if err != nil {
  76. return err
  77. }
  78. //path = global.CONFIG.AliOss.ImgHost + path
  79. //return path,err
  80. return err
  81. }
  82. var (
  83. Bucketname = "hzchart"
  84. Endpoint = "oss-cn-shanghai.aliyuncs.com"
  85. ResourceHost = "https://hzstatic.hzinsights.com/"
  86. StaticDir = "static/"
  87. AccessKeyId = "LTAIFMZYQhS2BTvW"
  88. AccessKeySecret = "12kk1ptCHoGWedhBnKRVW5hRJzq9Fq"
  89. UploadDir = "static/images/"
  90. )
  91. // UploadAliyunToDir
  92. func UploadAliyunToDir(filename, filepath, fileDir string) (string, error) {
  93. client, err := oss.New(Endpoint, AccessKeyId, AccessKeySecret)
  94. if err != nil {
  95. return "1", err
  96. }
  97. bucket, err := client.Bucket(Bucketname)
  98. if err != nil {
  99. return "2", err
  100. }
  101. if fileDir == "" {
  102. fileDir = time.Now().Format("200601/20060102/")
  103. }
  104. path := StaticDir + fileDir
  105. path += filename
  106. err = bucket.PutObjectFromFile(path, filepath)
  107. if err != nil {
  108. return "3", err
  109. }
  110. path = ResourceHost + path
  111. return path, err
  112. }
  113. // UploadAliyunV2 图片上传到阿里云
  114. func UploadAliyunV2(filename, filepath string) (string, error) {
  115. client, err := oss.New(Endpoint, AccessKeyId, AccessKeySecret)
  116. if err != nil {
  117. return "1", err
  118. }
  119. bucket, err := client.Bucket(Bucketname)
  120. if err != nil {
  121. return "2", err
  122. }
  123. path := UploadDir + time.Now().Format("200601/20060102/")
  124. path += filename
  125. err = bucket.PutObjectFromFile(path, filepath)
  126. if err != nil {
  127. return "3", err
  128. }
  129. path = ResourceHost + path
  130. return path, err
  131. }
  132. const (
  133. HzEndpoint = "oss-cn-shanghai.aliyuncs.com"
  134. HzBucketName string = "hzchart"
  135. )
  136. //上传文件到阿里云
  137. func UploadFileToAliyun(filename, filepath, savePath string) error {
  138. defer func() {
  139. os.Remove(filepath)
  140. }()
  141. client, err := oss.New(HzEndpoint, AccessKeyId, AccessKeySecret)
  142. if err != nil {
  143. return err
  144. }
  145. bucket, err := client.Bucket(HzBucketName)
  146. if err != nil {
  147. return err
  148. }
  149. //path := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
  150. //path += filename
  151. err = bucket.PutObjectFromFile(savePath, filepath)
  152. if err != nil {
  153. return err
  154. }
  155. return err
  156. }
  157. type STSToken struct {
  158. AccessKeyId string `json:"access_key_id"`
  159. AccessKeySecret string `json:"access_key_secret"`
  160. SecurityToken string `json:"security_token"`
  161. ExpiredTime string `json:"expired_time"`
  162. }
  163. // GetOssSTSToken 获取STSToken
  164. func GetOssSTSToken() (item *STSToken, err error) {
  165. defer func() {
  166. if err != nil {
  167. global.LOG.Info("GetOssSTSToken Err:" + err.Error())
  168. go alarm_msg.SendAlarmMsg("获取STSToken失败, ErrMsg: "+err.Error(), 3)
  169. }
  170. }()
  171. item = new(STSToken)
  172. // 获取缓存中的Token
  173. recent, _ := global.Redis.Get(context.TODO(), STSTokenCacheKey).Result()
  174. if recent != "" {
  175. lastToken := new(STSToken)
  176. if e := json.Unmarshal([]byte(recent), &lastToken); e != nil {
  177. err = errors.New("GetOssSTSToken lastToken Unmarshal Err: " + e.Error())
  178. return
  179. }
  180. // 未防止正在上传大文件时Token过期, 将判定的过期时间提前10分钟
  181. afterTime := time.Now().Local().Add(10 * time.Minute)
  182. expired, e := time.ParseInLocation(utils.FormatDateTime, lastToken.ExpiredTime, time.Local)
  183. if e != nil {
  184. err = errors.New("GetOssSTSToken expiredTime Parse Err: " + e.Error())
  185. return
  186. }
  187. if expired.After(afterTime) {
  188. item.AccessKeyId = lastToken.AccessKeyId
  189. item.AccessKeySecret = lastToken.AccessKeySecret
  190. item.SecurityToken = lastToken.SecurityToken
  191. item.ExpiredTime = lastToken.ExpiredTime
  192. return
  193. }
  194. }
  195. // 已过期则获取新的token
  196. newToken, e := NewSTSToken()
  197. if e != nil {
  198. err = errors.New("GetOssSTSToken NewSTSToken Err: " + e.Error())
  199. return
  200. }
  201. newTokenJson, e := json.Marshal(newToken)
  202. if e != nil {
  203. err = errors.New("GetOssSTSToken NewToken JSON Err: " + e.Error())
  204. return
  205. }
  206. // 覆盖缓存
  207. if statusCmd := global.Redis.SetEX(context.TODO(), STSTokenCacheKey, newTokenJson, time.Hour); statusCmd.Err() != nil {
  208. err = errors.New("GetOssSTSToken SetRedis Err: " + statusCmd.Err().Error())
  209. return
  210. }
  211. item = newToken
  212. return
  213. }
  214. // NewSTSToken 获取一个新的STSToken
  215. func NewSTSToken() (item *STSToken, err error) {
  216. defer func() {
  217. if err != nil {
  218. global.LOG.Info("NewSTSToken Err:" + err.Error())
  219. }
  220. }()
  221. item = new(STSToken)
  222. client, e := sts.NewClientWithAccessKey("cn-shanghai", RAMAccessKeyId, RAMAccessKeySecret)
  223. if e != nil {
  224. err = errors.New("NewSTSToken NewClient Err: " + e.Error())
  225. return
  226. }
  227. request := sts.CreateAssumeRoleRequest()
  228. request.Scheme = "https"
  229. request.RegionId = "cn-shanghai"
  230. request.RoleArn = RoleArn
  231. now := time.Now().Format(utils.FormatDateTimeUnSpace)
  232. request.RoleSessionName = RoleSessionName + now
  233. request.DurationSeconds = "3600"
  234. response, e := client.AssumeRole(request)
  235. if e != nil {
  236. err = errors.New("NewSTSToken AssumeRole Err: " + e.Error())
  237. return
  238. }
  239. if response != nil {
  240. item.AccessKeyId = response.Credentials.AccessKeyId
  241. item.AccessKeySecret = response.Credentials.AccessKeySecret
  242. item.SecurityToken = response.Credentials.SecurityToken
  243. t, _ := time.Parse(time.RFC3339, response.Credentials.Expiration)
  244. expiration := t.In(time.Local)
  245. item.ExpiredTime = expiration.Format(utils.FormatDateTime)
  246. }
  247. return
  248. }