oss.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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/hrms_api/global"
  9. "hongze/hrms_api/services/alarm_msg"
  10. "hongze/hrms_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. // todo 修改bucket空间
  135. HzBucketName string = "hzchart"
  136. )
  137. //上传文件到阿里云
  138. func UploadFileToAliyun(filename, filepath, savePath string) error {
  139. defer func() {
  140. os.Remove(filepath)
  141. }()
  142. client, err := oss.New(HzEndpoint, AccessKeyId, AccessKeySecret)
  143. if err != nil {
  144. return err
  145. }
  146. bucket, err := client.Bucket(HzBucketName)
  147. if err != nil {
  148. return err
  149. }
  150. //path := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
  151. //path += filename
  152. err = bucket.PutObjectFromFile(savePath, filepath)
  153. if err != nil {
  154. return err
  155. }
  156. return err
  157. }
  158. type STSToken struct {
  159. AccessKeyId string `json:"access_key_id"`
  160. AccessKeySecret string `json:"access_key_secret"`
  161. SecurityToken string `json:"security_token"`
  162. ExpiredTime string `json:"expired_time"`
  163. }
  164. // GetOssSTSToken 获取STSToken
  165. func GetOssSTSToken() (item *STSToken, err error) {
  166. defer func() {
  167. if err != nil {
  168. global.LOG.Info("GetOssSTSToken Err:"+err.Error())
  169. go alarm_msg.SendAlarmMsg("获取STSToken失败, ErrMsg: "+err.Error(), 3)
  170. }
  171. }()
  172. item = new(STSToken)
  173. // 获取缓存中的Token
  174. recent, _ := global.Redis.Get(context.TODO(), STSTokenCacheKey).Result()
  175. if recent != "" {
  176. lastToken := new(STSToken)
  177. if e := json.Unmarshal([]byte(recent), &lastToken); e != nil {
  178. err = errors.New("GetOssSTSToken lastToken Unmarshal Err: " + e.Error())
  179. return
  180. }
  181. // 未防止正在上传大文件时Token过期, 将判定的过期时间提前10分钟
  182. afterTime := time.Now().Local().Add(10 * time.Minute)
  183. expired, e := time.ParseInLocation(utils.FormatDateTime, lastToken.ExpiredTime, time.Local)
  184. if e != nil {
  185. err = errors.New("GetOssSTSToken expiredTime Parse Err: " + e.Error())
  186. return
  187. }
  188. if expired.After(afterTime) {
  189. item.AccessKeyId = lastToken.AccessKeyId
  190. item.AccessKeySecret = lastToken.AccessKeySecret
  191. item.SecurityToken = lastToken.SecurityToken
  192. item.ExpiredTime = lastToken.ExpiredTime
  193. return
  194. }
  195. }
  196. // 已过期则获取新的token
  197. newToken, e := NewSTSToken()
  198. if e != nil {
  199. err = errors.New("GetOssSTSToken NewSTSToken Err: " + e.Error())
  200. return
  201. }
  202. newTokenJson, e := json.Marshal(newToken)
  203. if e != nil {
  204. err = errors.New("GetOssSTSToken NewToken JSON Err: " + e.Error())
  205. return
  206. }
  207. // 覆盖缓存
  208. if statusCmd := global.Redis.SetEX(context.TODO(), STSTokenCacheKey, newTokenJson, time.Hour); statusCmd.Err() != nil {
  209. err = errors.New("GetOssSTSToken SetRedis Err: " + statusCmd.Err().Error())
  210. return
  211. }
  212. item = newToken
  213. return
  214. }
  215. // NewSTSToken 获取一个新的STSToken
  216. func NewSTSToken() (item *STSToken, err error) {
  217. defer func() {
  218. if err != nil {
  219. global.LOG.Info("NewSTSToken Err:"+err.Error())
  220. }
  221. }()
  222. item = new(STSToken)
  223. client, e := sts.NewClientWithAccessKey("cn-shanghai", RAMAccessKeyId, RAMAccessKeySecret)
  224. if e != nil {
  225. err = errors.New("NewSTSToken NewClient Err: " + e.Error())
  226. return
  227. }
  228. request := sts.CreateAssumeRoleRequest()
  229. request.Scheme = "https"
  230. request.RegionId = "cn-shanghai"
  231. request.RoleArn = RoleArn
  232. now := time.Now().Format(utils.FormatDateTimeUnSpace)
  233. request.RoleSessionName = RoleSessionName + now
  234. request.DurationSeconds = "3600"
  235. response, e := client.AssumeRole(request)
  236. if e != nil {
  237. err = errors.New("NewSTSToken AssumeRole Err: " + e.Error())
  238. return
  239. }
  240. if response != nil {
  241. item.AccessKeyId = response.Credentials.AccessKeyId
  242. item.AccessKeySecret = response.Credentials.AccessKeySecret
  243. item.SecurityToken = response.Credentials.SecurityToken
  244. t, _ := time.Parse(time.RFC3339, response.Credentials.Expiration)
  245. expiration := t.In(time.Local)
  246. item.ExpiredTime = expiration.Format(utils.FormatDateTime)
  247. }
  248. return
  249. }