You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

476 lines
17 KiB

  1. package cos
  2. import (
  3. "context"
  4. "encoding/xml"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "strings"
  12. "time"
  13. )
  14. // ObjectService 相关 API
  15. type ObjectService service
  16. // ObjectGetOptions is the option of GetObject
  17. type ObjectGetOptions struct {
  18. ResponseContentType string `url:"response-content-type,omitempty" header:"-"`
  19. ResponseContentLanguage string `url:"response-content-language,omitempty" header:"-"`
  20. ResponseExpires string `url:"response-expires,omitempty" header:"-"`
  21. ResponseCacheControl string `url:"response-cache-control,omitempty" header:"-"`
  22. ResponseContentDisposition string `url:"response-content-disposition,omitempty" header:"-"`
  23. ResponseContentEncoding string `url:"response-content-encoding,omitempty" header:"-"`
  24. Range string `url:"-" header:"Range,omitempty"`
  25. IfModifiedSince string `url:"-" header:"If-Modified-Since,omitempty"`
  26. }
  27. // presignedURLTestingOptions is the opt of presigned url
  28. type presignedURLTestingOptions struct {
  29. authTime *AuthTime
  30. }
  31. // Get Object 请求可以将一个文件(Object)下载至本地。
  32. // 该操作需要对目标 Object 具有读权限或目标 Object 对所有人都开放了读权限(公有读)。
  33. //
  34. // https://www.qcloud.com/document/product/436/7753
  35. func (s *ObjectService) Get(ctx context.Context, name string, opt *ObjectGetOptions, id ...string) (*Response, error) {
  36. var u string
  37. if len(id) == 1 {
  38. u = fmt.Sprintf("/%s?versionId=%s", encodeURIComponent(name), id[0])
  39. } else if len(id) == 0 {
  40. u = "/" + encodeURIComponent(name)
  41. } else {
  42. return nil, errors.New("wrong params")
  43. }
  44. sendOpt := sendOptions{
  45. baseURL: s.client.BaseURL.BucketURL,
  46. uri: u,
  47. method: http.MethodGet,
  48. optQuery: opt,
  49. optHeader: opt,
  50. disableCloseBody: true,
  51. }
  52. resp, err := s.client.send(ctx, &sendOpt)
  53. return resp, err
  54. }
  55. // GetToFile download the object to local file
  56. func (s *ObjectService) GetToFile(ctx context.Context, name, localpath string, opt *ObjectGetOptions, id ...string) (*Response, error) {
  57. resp, err := s.Get(ctx, name, opt, id...)
  58. if err != nil {
  59. return resp, err
  60. }
  61. defer resp.Body.Close()
  62. // If file exist, overwrite it
  63. fd, err := os.OpenFile(localpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
  64. if err != nil {
  65. return resp, err
  66. }
  67. _, err = io.Copy(fd, resp.Body)
  68. fd.Close()
  69. if err != nil {
  70. return resp, err
  71. }
  72. return resp, nil
  73. }
  74. // GetPresignedURL get the object presigned to down or upload file by url
  75. func (s *ObjectService) GetPresignedURL(ctx context.Context, httpMethod, name, ak, sk string, expired time.Duration, opt interface{}) (*url.URL, error) {
  76. sendOpt := sendOptions{
  77. baseURL: s.client.BaseURL.BucketURL,
  78. uri: "/" + encodeURIComponent(name),
  79. method: httpMethod,
  80. optQuery: opt,
  81. optHeader: opt,
  82. }
  83. req, err := s.client.newRequest(ctx, sendOpt.baseURL, sendOpt.uri, sendOpt.method, sendOpt.body, sendOpt.optQuery, sendOpt.optHeader)
  84. if err != nil {
  85. return nil, err
  86. }
  87. var authTime *AuthTime
  88. if opt != nil {
  89. if opt, ok := opt.(*presignedURLTestingOptions); ok {
  90. authTime = opt.authTime
  91. }
  92. }
  93. if authTime == nil {
  94. authTime = NewAuthTime(expired)
  95. }
  96. authorization := newAuthorization(ak, sk, req, authTime)
  97. sign := encodeURIComponent(authorization)
  98. if req.URL.RawQuery == "" {
  99. req.URL.RawQuery = fmt.Sprintf("sign=%s", sign)
  100. } else {
  101. req.URL.RawQuery = fmt.Sprintf("%s&sign=%s", req.URL.RawQuery, sign)
  102. }
  103. return req.URL, nil
  104. }
  105. // ObjectPutHeaderOptions the options of header of the put object
  106. type ObjectPutHeaderOptions struct {
  107. CacheControl string `header:"Cache-Control,omitempty" url:"-"`
  108. ContentDisposition string `header:"Content-Disposition,omitempty" url:"-"`
  109. ContentEncoding string `header:"Content-Encoding,omitempty" url:"-"`
  110. ContentType string `header:"Content-Type,omitempty" url:"-"`
  111. ContentLength int `header:"Content-Length,omitempty" url:"-"`
  112. Expect string `header:"Expect,omitempty" url:"-"`
  113. Expires string `header:"Expires,omitempty" url:"-"`
  114. XCosContentSHA1 string `header:"x-cos-content-sha1,omitempty" url:"-"`
  115. // 自定义的 x-cos-meta-* header
  116. XCosMetaXXX *http.Header `header:"x-cos-meta-*,omitempty" url:"-"`
  117. XCosStorageClass string `header:"x-cos-storage-class,omitempty" url:"-"`
  118. // 可选值: Normal, Appendable
  119. //XCosObjectType string `header:"x-cos-object-type,omitempty" url:"-"`
  120. }
  121. // ObjectPutOptions the options of put object
  122. type ObjectPutOptions struct {
  123. *ACLHeaderOptions `header:",omitempty" url:"-" xml:"-"`
  124. *ObjectPutHeaderOptions `header:",omitempty" url:"-" xml:"-"`
  125. }
  126. // Put Object请求可以将一个文件(Oject)上传至指定Bucket。
  127. //
  128. // 当 r 不是 bytes.Buffer/bytes.Reader/strings.Reader 时,必须指定 opt.ObjectPutHeaderOptions.ContentLength
  129. //
  130. // https://www.qcloud.com/document/product/436/7749
  131. func (s *ObjectService) Put(ctx context.Context, name string, r io.Reader, opt *ObjectPutOptions) (*Response, error) {
  132. sendOpt := sendOptions{
  133. baseURL: s.client.BaseURL.BucketURL,
  134. uri: "/" + encodeURIComponent(name),
  135. method: http.MethodPut,
  136. body: r,
  137. optHeader: opt,
  138. }
  139. resp, err := s.client.send(ctx, &sendOpt)
  140. return resp, err
  141. }
  142. // PutFromFile put object from local file
  143. // Notice that when use this put large file need set non-body of debug req/resp, otherwise will out of memory
  144. func (s *ObjectService) PutFromFile(ctx context.Context, name string, filePath string, opt *ObjectPutOptions) (*Response, error) {
  145. fd, err := os.Open(filePath)
  146. if err != nil {
  147. return nil, err
  148. }
  149. defer fd.Close()
  150. return s.Put(ctx, name, fd, opt)
  151. }
  152. // ObjectCopyHeaderOptions is the head option of the Copy
  153. type ObjectCopyHeaderOptions struct {
  154. // When use replace directive to update meta infos
  155. CacheControl string `header:"Cache-Control,omitempty" url:"-"`
  156. ContentDisposition string `header:"Content-Disposition,omitempty" url:"-"`
  157. ContentEncoding string `header:"Content-Encoding,omitempty" url:"-"`
  158. ContentType string `header:"Content-Type,omitempty" url:"-"`
  159. Expires string `header:"Expires,omitempty" url:"-"`
  160. Expect string `header:"Expect,omitempty" url:"-"`
  161. XCosMetadataDirective string `header:"x-cos-metadata-directive,omitempty" url:"-" xml:"-"`
  162. XCosCopySourceIfModifiedSince string `header:"x-cos-copy-source-If-Modified-Since,omitempty" url:"-" xml:"-"`
  163. XCosCopySourceIfUnmodifiedSince string `header:"x-cos-copy-source-If-Unmodified-Since,omitempty" url:"-" xml:"-"`
  164. XCosCopySourceIfMatch string `header:"x-cos-copy-source-If-Match,omitempty" url:"-" xml:"-"`
  165. XCosCopySourceIfNoneMatch string `header:"x-cos-copy-source-If-None-Match,omitempty" url:"-" xml:"-"`
  166. XCosStorageClass string `header:"x-cos-storage-class,omitempty" url:"-" xml:"-"`
  167. // 自定义的 x-cos-meta-* header
  168. XCosMetaXXX *http.Header `header:"x-cos-meta-*,omitempty" url:"-"`
  169. XCosCopySource string `header:"x-cos-copy-source" url:"-" xml:"-"`
  170. XCosServerSideEncryption string `header:"x-cos-server-side-encryption,omitempty" url:"-" xml:"-"`
  171. }
  172. // ObjectCopyOptions is the option of Copy, choose header or body
  173. type ObjectCopyOptions struct {
  174. *ObjectCopyHeaderOptions `header:",omitempty" url:"-" xml:"-"`
  175. *ACLHeaderOptions `header:",omitempty" url:"-" xml:"-"`
  176. }
  177. // ObjectCopyResult is the result of Copy
  178. type ObjectCopyResult struct {
  179. XMLName xml.Name `xml:"CopyObjectResult"`
  180. ETag string `xml:"ETag,omitempty"`
  181. LastModified string `xml:"LastModified,omitempty"`
  182. }
  183. // Copy 调用 PutObjectCopy 请求实现将一个文件从源路径复制到目标路径。建议文件大小 1M 到 5G,
  184. // 超过 5G 的文件请使用分块上传 Upload - Copy。在拷贝的过程中,文件元属性和 ACL 可以被修改。
  185. //
  186. // 用户可以通过该接口实现文件移动,文件重命名,修改文件属性和创建副本。
  187. //
  188. // 注意:在跨帐号复制的时候,需要先设置被复制文件的权限为公有读,或者对目标帐号赋权,同帐号则不需要。
  189. //
  190. // https://cloud.tencent.com/document/product/436/10881
  191. func (s *ObjectService) Copy(ctx context.Context, name, sourceURL string, opt *ObjectCopyOptions) (*ObjectCopyResult, *Response, error) {
  192. var res ObjectCopyResult
  193. if opt == nil {
  194. opt = new(ObjectCopyOptions)
  195. }
  196. if opt.ObjectCopyHeaderOptions == nil {
  197. opt.ObjectCopyHeaderOptions = new(ObjectCopyHeaderOptions)
  198. }
  199. opt.XCosCopySource = encodeURIComponent(sourceURL)
  200. sendOpt := sendOptions{
  201. baseURL: s.client.BaseURL.BucketURL,
  202. uri: "/" + encodeURIComponent(name),
  203. method: http.MethodPut,
  204. body: nil,
  205. optHeader: opt,
  206. result: &res,
  207. }
  208. resp, err := s.client.send(ctx, &sendOpt)
  209. return &res, resp, err
  210. }
  211. // Delete Object请求可以将一个文件(Object)删除。
  212. //
  213. // https://www.qcloud.com/document/product/436/7743
  214. func (s *ObjectService) Delete(ctx context.Context, name string) (*Response, error) {
  215. // When use "" string might call the delete bucket interface
  216. if len(name) == 0 {
  217. return nil, errors.New("empty object name")
  218. }
  219. sendOpt := sendOptions{
  220. baseURL: s.client.BaseURL.BucketURL,
  221. uri: "/" + encodeURIComponent(name),
  222. method: http.MethodDelete,
  223. }
  224. resp, err := s.client.send(ctx, &sendOpt)
  225. return resp, err
  226. }
  227. // ObjectHeadOptions is the option of HeadObject
  228. type ObjectHeadOptions struct {
  229. IfModifiedSince string `url:"-" header:"If-Modified-Since,omitempty"`
  230. }
  231. // Head Object请求可以取回对应Object的元数据,Head的权限与Get的权限一致
  232. //
  233. // https://www.qcloud.com/document/product/436/7745
  234. func (s *ObjectService) Head(ctx context.Context, name string, opt *ObjectHeadOptions, id ...string) (*Response, error) {
  235. var u string
  236. if len(id) == 1 {
  237. u = fmt.Sprintf("/%s?versionId=%s", encodeURIComponent(name), id[0])
  238. } else if len(id) == 0 {
  239. u = "/" + encodeURIComponent(name)
  240. } else {
  241. return nil, errors.New("wrong params")
  242. }
  243. sendOpt := sendOptions{
  244. baseURL: s.client.BaseURL.BucketURL,
  245. uri: u,
  246. method: http.MethodHead,
  247. optHeader: opt,
  248. }
  249. resp, err := s.client.send(ctx, &sendOpt)
  250. if resp.Header["X-Cos-Object-Type"] != nil && resp.Header["X-Cos-Object-Type"][0] == "appendable" {
  251. resp.Header.Add("x-cos-next-append-position", resp.Header["Content-Length"][0])
  252. }
  253. return resp, err
  254. }
  255. // ObjectOptionsOptions is the option of object options
  256. type ObjectOptionsOptions struct {
  257. Origin string `url:"-" header:"Origin"`
  258. AccessControlRequestMethod string `url:"-" header:"Access-Control-Request-Method"`
  259. AccessControlRequestHeaders string `url:"-" header:"Access-Control-Request-Headers,omitempty"`
  260. }
  261. // Options Object请求实现跨域访问的预请求。即发出一个 OPTIONS 请求给服务器以确认是否可以进行跨域操作。
  262. //
  263. // 当CORS配置不存在时,请求返回403 Forbidden。
  264. //
  265. // https://www.qcloud.com/document/product/436/8288
  266. func (s *ObjectService) Options(ctx context.Context, name string, opt *ObjectOptionsOptions) (*Response, error) {
  267. sendOpt := sendOptions{
  268. baseURL: s.client.BaseURL.BucketURL,
  269. uri: "/" + encodeURIComponent(name),
  270. method: http.MethodOptions,
  271. optHeader: opt,
  272. }
  273. resp, err := s.client.send(ctx, &sendOpt)
  274. return resp, err
  275. }
  276. // CASJobParameters support three way: Standard(in 35 hours), Expedited(quick way, in 15 mins), Bulk(in 5-12 hours_
  277. type CASJobParameters struct {
  278. Tier string `xml:"Tier"`
  279. }
  280. // ObjectRestoreOptions is the option of object restore
  281. type ObjectRestoreOptions struct {
  282. XMLName xml.Name `xml:"RestoreRequest"`
  283. Days int `xml:"Days"`
  284. Tier *CASJobParameters `xml:"CASJobParameters"`
  285. }
  286. // PutRestore API can recover an object of type archived by COS archive.
  287. //
  288. // https://cloud.tencent.com/document/product/436/12633
  289. func (s *ObjectService) PostRestore(ctx context.Context, name string, opt *ObjectRestoreOptions) (*Response, error) {
  290. u := fmt.Sprintf("/%s?restore", encodeURIComponent(name))
  291. sendOpt := sendOptions{
  292. baseURL: s.client.BaseURL.BucketURL,
  293. uri: u,
  294. method: http.MethodPost,
  295. body: opt,
  296. }
  297. resp, err := s.client.send(ctx, &sendOpt)
  298. return resp, err
  299. }
  300. // TODO Append 接口在优化未开放使用
  301. //
  302. // Append请求可以将一个文件(Object)以分块追加的方式上传至 Bucket 中。使用Append Upload的文件必须事前被设定为Appendable。
  303. // 当Appendable的文件被执行Put Object的操作以后,文件被覆盖,属性改变为Normal。
  304. //
  305. // 文件属性可以在Head Object操作中被查询到,当您发起Head Object请求时,会返回自定义Header『x-cos-object-type』,该Header只有两个枚举值:Normal或者Appendable。
  306. //
  307. // 追加上传建议文件大小1M - 5G。如果position的值和当前Object的长度不致,COS会返回409错误。
  308. // 如果Append一个Normal的Object,COS会返回409 ObjectNotAppendable。
  309. //
  310. // Appendable的文件不可以被复制,不参与版本管理,不参与生命周期管理,不可跨区域复制。
  311. //
  312. // 当 r 不是 bytes.Buffer/bytes.Reader/strings.Reader 时,必须指定 opt.ObjectPutHeaderOptions.ContentLength
  313. //
  314. // https://www.qcloud.com/document/product/436/7741
  315. // func (s *ObjectService) Append(ctx context.Context, name string, position int, r io.Reader, opt *ObjectPutOptions) (*Response, error) {
  316. // u := fmt.Sprintf("/%s?append&position=%d", encodeURIComponent(name), position)
  317. // if position != 0{
  318. // opt = nil
  319. // }
  320. // sendOpt := sendOptions{
  321. // baseURL: s.client.BaseURL.BucketURL,
  322. // uri: u,
  323. // method: http.MethodPost,
  324. // optHeader: opt,
  325. // body: r,
  326. // }
  327. // resp, err := s.client.send(ctx, &sendOpt)
  328. // return resp, err
  329. // }
  330. // ObjectDeleteMultiOptions is the option of DeleteMulti
  331. type ObjectDeleteMultiOptions struct {
  332. XMLName xml.Name `xml:"Delete" header:"-"`
  333. Quiet bool `xml:"Quiet" header:"-"`
  334. Objects []Object `xml:"Object" header:"-"`
  335. //XCosSha1 string `xml:"-" header:"x-cos-sha1"`
  336. }
  337. // ObjectDeleteMultiResult is the result of DeleteMulti
  338. type ObjectDeleteMultiResult struct {
  339. XMLName xml.Name `xml:"DeleteResult"`
  340. DeletedObjects []Object `xml:"Deleted,omitempty"`
  341. Errors []struct {
  342. Key string
  343. Code string
  344. Message string
  345. } `xml:"Error,omitempty"`
  346. }
  347. // DeleteMulti 请求实现批量删除文件,最大支持单次删除1000个文件。
  348. // 对于返回结果,COS提供Verbose和Quiet两种结果模式。Verbose模式将返回每个Object的删除结果;
  349. // Quiet模式只返回报错的Object信息。
  350. // https://www.qcloud.com/document/product/436/8289
  351. func (s *ObjectService) DeleteMulti(ctx context.Context, opt *ObjectDeleteMultiOptions) (*ObjectDeleteMultiResult, *Response, error) {
  352. var res ObjectDeleteMultiResult
  353. sendOpt := sendOptions{
  354. baseURL: s.client.BaseURL.BucketURL,
  355. uri: "/?delete",
  356. method: http.MethodPost,
  357. body: opt,
  358. result: &res,
  359. }
  360. resp, err := s.client.send(ctx, &sendOpt)
  361. return &res, resp, err
  362. }
  363. // Object is the meta info of the object
  364. type Object struct {
  365. Key string `xml:",omitempty"`
  366. ETag string `xml:",omitempty"`
  367. Size int `xml:",omitempty"`
  368. PartNumber int `xml:",omitempty"`
  369. LastModified string `xml:",omitempty"`
  370. StorageClass string `xml:",omitempty"`
  371. Owner *Owner `xml:",omitempty"`
  372. }
  373. type MultiUploadOptions struct {
  374. OptIni *InitiateMultipartUploadOptions
  375. PartSize int
  376. }
  377. // MultiUpload 为高级upload接口,并发分块上传
  378. //
  379. // 需要指定分块大小 partSize >= 1 ,单位为MB
  380. // 同时请确认分块数量不超过10000
  381. //
  382. func (s *ObjectService) MultiUpload(ctx context.Context, name string, r io.Reader, opt *MultiUploadOptions) (*CompleteMultipartUploadResult, *Response, error) {
  383. optini := opt.OptIni
  384. res, _, err := s.InitiateMultipartUpload(ctx, name, optini)
  385. if err != nil {
  386. return nil, nil, err
  387. }
  388. uploadID := res.UploadID
  389. bufSize := opt.PartSize * 1024 * 1024
  390. buffer := make([]byte, bufSize)
  391. optcom := &CompleteMultipartUploadOptions{}
  392. PartUpload := func(ch chan *Response, ctx context.Context, name string, uploadId string, partNumber int, data io.Reader, opt *ObjectUploadPartOptions) {
  393. defer func() {
  394. if err := recover(); err != nil {
  395. fmt.Println(err)
  396. }
  397. }()
  398. resp, _ := s.UploadPart(context.Background(), name, uploadId, partNumber, data, nil)
  399. ch <- resp
  400. }
  401. chs := make([]chan *Response, 10000)
  402. PartNumber := 0
  403. for i := 1; true; i++ {
  404. bytesread, err := r.Read(buffer)
  405. if err != nil {
  406. if err != io.EOF {
  407. return nil, nil, err
  408. }
  409. PartNumber = i
  410. break
  411. }
  412. chs[i] = make(chan *Response)
  413. go PartUpload(chs[i], context.Background(), name, uploadID, i, strings.NewReader(string(buffer[:bytesread])), nil)
  414. }
  415. for i := 1; i < PartNumber; i++ {
  416. resp := <-chs[i]
  417. // Notice one part fail can not get the etag according.
  418. etag := resp.Header.Get("ETag")
  419. optcom.Parts = append(optcom.Parts, Object{
  420. PartNumber: i, ETag: etag},
  421. )
  422. }
  423. v, resp, err := s.CompleteMultipartUpload(context.Background(), name, uploadID, optcom)
  424. return v, resp, err
  425. }