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.

931 lines
31 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package cos
  2. import (
  3. "context"
  4. "crypto/md5"
  5. "encoding/xml"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "time"
  17. )
  18. // ObjectService 相关 API
  19. type ObjectService service
  20. // ObjectGetOptions is the option of GetObject
  21. type ObjectGetOptions struct {
  22. ResponseContentType string `url:"response-content-type,omitempty" header:"-"`
  23. ResponseContentLanguage string `url:"response-content-language,omitempty" header:"-"`
  24. ResponseExpires string `url:"response-expires,omitempty" header:"-"`
  25. ResponseCacheControl string `url:"response-cache-control,omitempty" header:"-"`
  26. ResponseContentDisposition string `url:"response-content-disposition,omitempty" header:"-"`
  27. ResponseContentEncoding string `url:"response-content-encoding,omitempty" header:"-"`
  28. Range string `url:"-" header:"Range,omitempty"`
  29. IfModifiedSince string `url:"-" header:"If-Modified-Since,omitempty"`
  30. // SSE-C
  31. XCosSSECustomerAglo string `header:"x-cos-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
  32. XCosSSECustomerKey string `header:"x-cos-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
  33. XCosSSECustomerKeyMD5 string `header:"x-cos-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
  34. XCosTrafficLimit int `header:"x-cos-traffic-limit,omitempty" url:"-" xml:"-"`
  35. // 下载进度, ProgressCompleteEvent不能表示对应API调用成功,API是否调用成功的判断标准为返回err==nil
  36. Listener ProgressListener `header:"-" url:"-" xml:"-"`
  37. }
  38. // presignedURLTestingOptions is the opt of presigned url
  39. type presignedURLTestingOptions struct {
  40. authTime *AuthTime
  41. }
  42. // Get Object 请求可以将一个文件(Object)下载至本地。
  43. // 该操作需要对目标 Object 具有读权限或目标 Object 对所有人都开放了读权限(公有读)。
  44. //
  45. // https://www.qcloud.com/document/product/436/7753
  46. func (s *ObjectService) Get(ctx context.Context, name string, opt *ObjectGetOptions, id ...string) (*Response, error) {
  47. var u string
  48. if len(id) == 1 {
  49. u = fmt.Sprintf("/%s?versionId=%s", encodeURIComponent(name), id[0])
  50. } else if len(id) == 0 {
  51. u = "/" + encodeURIComponent(name)
  52. } else {
  53. return nil, errors.New("wrong params")
  54. }
  55. sendOpt := sendOptions{
  56. baseURL: s.client.BaseURL.BucketURL,
  57. uri: u,
  58. method: http.MethodGet,
  59. optQuery: opt,
  60. optHeader: opt,
  61. disableCloseBody: true,
  62. }
  63. resp, err := s.client.send(ctx, &sendOpt)
  64. if opt != nil && opt.Listener != nil {
  65. if err == nil && resp != nil {
  66. if totalBytes, e := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64); e == nil {
  67. resp.Body = TeeReader(resp.Body, nil, totalBytes, opt.Listener)
  68. }
  69. }
  70. }
  71. return resp, err
  72. }
  73. // GetToFile download the object to local file
  74. func (s *ObjectService) GetToFile(ctx context.Context, name, localpath string, opt *ObjectGetOptions, id ...string) (*Response, error) {
  75. resp, err := s.Get(ctx, name, opt, id...)
  76. if err != nil {
  77. return resp, err
  78. }
  79. defer resp.Body.Close()
  80. // If file exist, overwrite it
  81. fd, err := os.OpenFile(localpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
  82. if err != nil {
  83. return resp, err
  84. }
  85. _, err = io.Copy(fd, resp.Body)
  86. fd.Close()
  87. if err != nil {
  88. return resp, err
  89. }
  90. return resp, nil
  91. }
  92. // GetPresignedURL get the object presigned to down or upload file by url
  93. func (s *ObjectService) GetPresignedURL(ctx context.Context, httpMethod, name, ak, sk string, expired time.Duration, opt interface{}) (*url.URL, error) {
  94. sendOpt := sendOptions{
  95. baseURL: s.client.BaseURL.BucketURL,
  96. uri: "/" + encodeURIComponent(name),
  97. method: httpMethod,
  98. optQuery: opt,
  99. optHeader: opt,
  100. }
  101. req, err := s.client.newRequest(ctx, sendOpt.baseURL, sendOpt.uri, sendOpt.method, sendOpt.body, sendOpt.optQuery, sendOpt.optHeader)
  102. if err != nil {
  103. return nil, err
  104. }
  105. var authTime *AuthTime
  106. if opt != nil {
  107. if opt, ok := opt.(*presignedURLTestingOptions); ok {
  108. authTime = opt.authTime
  109. }
  110. }
  111. if authTime == nil {
  112. authTime = NewAuthTime(expired)
  113. }
  114. authorization := newAuthorization(ak, sk, req, authTime)
  115. sign := encodeURIComponent(authorization, []byte{'&','='})
  116. if req.URL.RawQuery == "" {
  117. req.URL.RawQuery = fmt.Sprintf("%s", sign)
  118. } else {
  119. req.URL.RawQuery = fmt.Sprintf("%s&%s", req.URL.RawQuery, sign)
  120. }
  121. return req.URL, nil
  122. }
  123. // ObjectPutHeaderOptions the options of header of the put object
  124. type ObjectPutHeaderOptions struct {
  125. CacheControl string `header:"Cache-Control,omitempty" url:"-"`
  126. ContentDisposition string `header:"Content-Disposition,omitempty" url:"-"`
  127. ContentEncoding string `header:"Content-Encoding,omitempty" url:"-"`
  128. ContentType string `header:"Content-Type,omitempty" url:"-"`
  129. ContentMD5 string `header:"Content-MD5,omitempty" url:"-"`
  130. ContentLength int `header:"Content-Length,omitempty" url:"-"`
  131. ContentLanguage string `header:"Content-Language,omitempty" url:"-"`
  132. Expect string `header:"Expect,omitempty" url:"-"`
  133. Expires string `header:"Expires,omitempty" url:"-"`
  134. XCosContentSHA1 string `header:"x-cos-content-sha1,omitempty" url:"-"`
  135. // 自定义的 x-cos-meta-* header
  136. XCosMetaXXX *http.Header `header:"x-cos-meta-*,omitempty" url:"-"`
  137. XCosStorageClass string `header:"x-cos-storage-class,omitempty" url:"-"`
  138. // 可选值: Normal, Appendable
  139. //XCosObjectType string `header:"x-cos-object-type,omitempty" url:"-"`
  140. // Enable Server Side Encryption, Only supported: AES256
  141. XCosServerSideEncryption string `header:"x-cos-server-side-encryption,omitempty" url:"-" xml:"-"`
  142. // SSE-C
  143. XCosSSECustomerAglo string `header:"x-cos-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
  144. XCosSSECustomerKey string `header:"x-cos-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
  145. XCosSSECustomerKeyMD5 string `header:"x-cos-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
  146. //兼容其他自定义头部
  147. XOptionHeader *http.Header `header:"-,omitempty" url:"-" xml:"-"`
  148. XCosTrafficLimit int `header:"x-cos-traffic-limit,omitempty" url:"-" xml:"-"`
  149. // 上传进度, ProgressCompleteEvent不能表示对应API调用成功,API是否调用成功的判断标准为返回err==nil
  150. Listener ProgressListener `header:"-" url:"-" xml:"-"`
  151. }
  152. // ObjectPutOptions the options of put object
  153. type ObjectPutOptions struct {
  154. *ACLHeaderOptions `header:",omitempty" url:"-" xml:"-"`
  155. *ObjectPutHeaderOptions `header:",omitempty" url:"-" xml:"-"`
  156. }
  157. // Put Object请求可以将一个文件(Oject)上传至指定Bucket。
  158. //
  159. // 当 r 不是 bytes.Buffer/bytes.Reader/strings.Reader 时,必须指定 opt.ObjectPutHeaderOptions.ContentLength
  160. //
  161. // https://www.qcloud.com/document/product/436/7749
  162. func (s *ObjectService) Put(ctx context.Context, name string, r io.Reader, opt *ObjectPutOptions) (*Response, error) {
  163. if opt != nil && opt.Listener != nil {
  164. totalBytes, err := GetReaderLen(r)
  165. if err != nil {
  166. return nil, err
  167. }
  168. r = TeeReader(r, nil, totalBytes, opt.Listener)
  169. }
  170. sendOpt := sendOptions{
  171. baseURL: s.client.BaseURL.BucketURL,
  172. uri: "/" + encodeURIComponent(name),
  173. method: http.MethodPut,
  174. body: r,
  175. optHeader: opt,
  176. }
  177. resp, err := s.client.send(ctx, &sendOpt)
  178. return resp, err
  179. }
  180. // PutFromFile put object from local file
  181. // Notice that when use this put large file need set non-body of debug req/resp, otherwise will out of memory
  182. func (s *ObjectService) PutFromFile(ctx context.Context, name string, filePath string, opt *ObjectPutOptions) (*Response, error) {
  183. fd, err := os.Open(filePath)
  184. if err != nil {
  185. return nil, err
  186. }
  187. defer fd.Close()
  188. return s.Put(ctx, name, fd, opt)
  189. }
  190. // ObjectCopyHeaderOptions is the head option of the Copy
  191. type ObjectCopyHeaderOptions struct {
  192. // When use replace directive to update meta infos
  193. CacheControl string `header:"Cache-Control,omitempty" url:"-"`
  194. ContentDisposition string `header:"Content-Disposition,omitempty" url:"-"`
  195. ContentEncoding string `header:"Content-Encoding,omitempty" url:"-"`
  196. ContentLanguage string `header:"Content-Language,omitempty" url:"-"`
  197. ContentType string `header:"Content-Type,omitempty" url:"-"`
  198. Expires string `header:"Expires,omitempty" url:"-"`
  199. Expect string `header:"Expect,omitempty" url:"-"`
  200. XCosMetadataDirective string `header:"x-cos-metadata-directive,omitempty" url:"-" xml:"-"`
  201. XCosCopySourceIfModifiedSince string `header:"x-cos-copy-source-If-Modified-Since,omitempty" url:"-" xml:"-"`
  202. XCosCopySourceIfUnmodifiedSince string `header:"x-cos-copy-source-If-Unmodified-Since,omitempty" url:"-" xml:"-"`
  203. XCosCopySourceIfMatch string `header:"x-cos-copy-source-If-Match,omitempty" url:"-" xml:"-"`
  204. XCosCopySourceIfNoneMatch string `header:"x-cos-copy-source-If-None-Match,omitempty" url:"-" xml:"-"`
  205. XCosStorageClass string `header:"x-cos-storage-class,omitempty" url:"-" xml:"-"`
  206. // 自定义的 x-cos-meta-* header
  207. XCosMetaXXX *http.Header `header:"x-cos-meta-*,omitempty" url:"-"`
  208. XCosCopySource string `header:"x-cos-copy-source" url:"-" xml:"-"`
  209. XCosServerSideEncryption string `header:"x-cos-server-side-encryption,omitempty" url:"-" xml:"-"`
  210. // SSE-C
  211. XCosSSECustomerAglo string `header:"x-cos-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
  212. XCosSSECustomerKey string `header:"x-cos-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
  213. XCosSSECustomerKeyMD5 string `header:"x-cos-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
  214. XCosCopySourceSSECustomerAglo string `header:"x-cos-copy-source-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
  215. XCosCopySourceSSECustomerKey string `header:"x-cos-copy-source-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
  216. XCosCopySourceSSECustomerKeyMD5 string `header:"x-cos-copy-source-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
  217. //兼容其他自定义头部
  218. XOptionHeader *http.Header `header:"-,omitempty" url:"-" xml:"-"`
  219. }
  220. // ObjectCopyOptions is the option of Copy, choose header or body
  221. type ObjectCopyOptions struct {
  222. *ObjectCopyHeaderOptions `header:",omitempty" url:"-" xml:"-"`
  223. *ACLHeaderOptions `header:",omitempty" url:"-" xml:"-"`
  224. }
  225. // ObjectCopyResult is the result of Copy
  226. type ObjectCopyResult struct {
  227. XMLName xml.Name `xml:"CopyObjectResult"`
  228. ETag string `xml:"ETag,omitempty"`
  229. LastModified string `xml:"LastModified,omitempty"`
  230. }
  231. // Copy 调用 PutObjectCopy 请求实现将一个文件从源路径复制到目标路径。建议文件大小 1M 到 5G,
  232. // 超过 5G 的文件请使用分块上传 Upload - Copy。在拷贝的过程中,文件元属性和 ACL 可以被修改。
  233. //
  234. // 用户可以通过该接口实现文件移动,文件重命名,修改文件属性和创建副本。
  235. //
  236. // 注意:在跨帐号复制的时候,需要先设置被复制文件的权限为公有读,或者对目标帐号赋权,同帐号则不需要。
  237. //
  238. // https://cloud.tencent.com/document/product/436/10881
  239. func (s *ObjectService) Copy(ctx context.Context, name, sourceURL string, opt *ObjectCopyOptions, id ...string) (*ObjectCopyResult, *Response, error) {
  240. surl := strings.SplitN(sourceURL, "/", 2)
  241. if len(surl) < 2 {
  242. return nil, nil, errors.New(fmt.Sprintf("x-cos-copy-source format error: %s", sourceURL))
  243. }
  244. var u string
  245. if len(id) == 1 {
  246. u = fmt.Sprintf("%s/%s?versionId=%s", surl[0], encodeURIComponent(surl[1]), id[0])
  247. } else if len(id) == 0 {
  248. u = fmt.Sprintf("%s/%s", surl[0], encodeURIComponent(surl[1]))
  249. } else {
  250. return nil, nil, errors.New("wrong params")
  251. }
  252. var res ObjectCopyResult
  253. copyOpt := &ObjectCopyOptions{
  254. &ObjectCopyHeaderOptions{},
  255. &ACLHeaderOptions{},
  256. }
  257. if opt != nil {
  258. if opt.ObjectCopyHeaderOptions != nil {
  259. *copyOpt.ObjectCopyHeaderOptions = *opt.ObjectCopyHeaderOptions
  260. }
  261. if opt.ACLHeaderOptions != nil {
  262. *copyOpt.ACLHeaderOptions = *opt.ACLHeaderOptions
  263. }
  264. }
  265. copyOpt.XCosCopySource = u
  266. sendOpt := sendOptions{
  267. baseURL: s.client.BaseURL.BucketURL,
  268. uri: "/" + encodeURIComponent(name),
  269. method: http.MethodPut,
  270. body: nil,
  271. optHeader: copyOpt,
  272. result: &res,
  273. }
  274. resp, err := s.client.send(ctx, &sendOpt)
  275. // If the error occurs during the copy operation, the error response is embedded in the 200 OK response. This means that a 200 OK response can contain either a success or an error.
  276. if err == nil && resp.StatusCode == 200 {
  277. if res.ETag == "" {
  278. return &res, resp, errors.New("response 200 OK, but body contains an error")
  279. }
  280. }
  281. return &res, resp, err
  282. }
  283. type ObjectDeleteOptions struct {
  284. // SSE-C
  285. XCosSSECustomerAglo string `header:"x-cos-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
  286. XCosSSECustomerKey string `header:"x-cos-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
  287. XCosSSECustomerKeyMD5 string `header:"x-cos-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
  288. //兼容其他自定义头部
  289. XOptionHeader *http.Header `header:"-,omitempty" url:"-" xml:"-"`
  290. VersionId string `header:"-" url:"VersionId,omitempty" xml:"-"`
  291. }
  292. // Delete Object请求可以将一个文件(Object)删除。
  293. //
  294. // https://www.qcloud.com/document/product/436/7743
  295. func (s *ObjectService) Delete(ctx context.Context, name string, opt ...*ObjectDeleteOptions) (*Response, error) {
  296. var optHeader *ObjectDeleteOptions
  297. // When use "" string might call the delete bucket interface
  298. if len(name) == 0 {
  299. return nil, errors.New("empty object name")
  300. }
  301. if len(opt) > 0 {
  302. optHeader = opt[0]
  303. }
  304. sendOpt := sendOptions{
  305. baseURL: s.client.BaseURL.BucketURL,
  306. uri: "/" + encodeURIComponent(name),
  307. method: http.MethodDelete,
  308. optHeader: optHeader,
  309. optQuery: optHeader,
  310. }
  311. resp, err := s.client.send(ctx, &sendOpt)
  312. return resp, err
  313. }
  314. // ObjectHeadOptions is the option of HeadObject
  315. type ObjectHeadOptions struct {
  316. IfModifiedSince string `url:"-" header:"If-Modified-Since,omitempty"`
  317. // SSE-C
  318. XCosSSECustomerAglo string `header:"x-cos-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
  319. XCosSSECustomerKey string `header:"x-cos-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
  320. XCosSSECustomerKeyMD5 string `header:"x-cos-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
  321. }
  322. // Head Object请求可以取回对应Object的元数据,Head的权限与Get的权限一致
  323. //
  324. // https://www.qcloud.com/document/product/436/7745
  325. func (s *ObjectService) Head(ctx context.Context, name string, opt *ObjectHeadOptions, id ...string) (*Response, error) {
  326. var u string
  327. if len(id) == 1 {
  328. u = fmt.Sprintf("/%s?versionId=%s", encodeURIComponent(name), id[0])
  329. } else if len(id) == 0 {
  330. u = "/" + encodeURIComponent(name)
  331. } else {
  332. return nil, errors.New("wrong params")
  333. }
  334. sendOpt := sendOptions{
  335. baseURL: s.client.BaseURL.BucketURL,
  336. uri: u,
  337. method: http.MethodHead,
  338. optHeader: opt,
  339. }
  340. resp, err := s.client.send(ctx, &sendOpt)
  341. if resp != nil && resp.Header["X-Cos-Object-Type"] != nil && resp.Header["X-Cos-Object-Type"][0] == "appendable" {
  342. resp.Header.Add("x-cos-next-append-position", resp.Header["Content-Length"][0])
  343. }
  344. return resp, err
  345. }
  346. // ObjectOptionsOptions is the option of object options
  347. type ObjectOptionsOptions struct {
  348. Origin string `url:"-" header:"Origin"`
  349. AccessControlRequestMethod string `url:"-" header:"Access-Control-Request-Method"`
  350. AccessControlRequestHeaders string `url:"-" header:"Access-Control-Request-Headers,omitempty"`
  351. }
  352. // Options Object请求实现跨域访问的预请求。即发出一个 OPTIONS 请求给服务器以确认是否可以进行跨域操作。
  353. //
  354. // 当CORS配置不存在时,请求返回403 Forbidden。
  355. //
  356. // https://www.qcloud.com/document/product/436/8288
  357. func (s *ObjectService) Options(ctx context.Context, name string, opt *ObjectOptionsOptions) (*Response, error) {
  358. sendOpt := sendOptions{
  359. baseURL: s.client.BaseURL.BucketURL,
  360. uri: "/" + encodeURIComponent(name),
  361. method: http.MethodOptions,
  362. optHeader: opt,
  363. }
  364. resp, err := s.client.send(ctx, &sendOpt)
  365. return resp, err
  366. }
  367. // CASJobParameters support three way: Standard(in 35 hours), Expedited(quick way, in 15 mins), Bulk(in 5-12 hours_
  368. type CASJobParameters struct {
  369. Tier string `xml:"Tier"`
  370. }
  371. // ObjectRestoreOptions is the option of object restore
  372. type ObjectRestoreOptions struct {
  373. XMLName xml.Name `xml:"RestoreRequest"`
  374. Days int `xml:"Days"`
  375. Tier *CASJobParameters `xml:"CASJobParameters"`
  376. }
  377. // PutRestore API can recover an object of type archived by COS archive.
  378. //
  379. // https://cloud.tencent.com/document/product/436/12633
  380. func (s *ObjectService) PostRestore(ctx context.Context, name string, opt *ObjectRestoreOptions) (*Response, error) {
  381. u := fmt.Sprintf("/%s?restore", encodeURIComponent(name))
  382. sendOpt := sendOptions{
  383. baseURL: s.client.BaseURL.BucketURL,
  384. uri: u,
  385. method: http.MethodPost,
  386. body: opt,
  387. }
  388. resp, err := s.client.send(ctx, &sendOpt)
  389. return resp, err
  390. }
  391. // TODO Append 接口在优化未开放使用
  392. //
  393. // Append请求可以将一个文件(Object)以分块追加的方式上传至 Bucket 中。使用Append Upload的文件必须事前被设定为Appendable。
  394. // 当Appendable的文件被执行Put Object的操作以后,文件被覆盖,属性改变为Normal。
  395. //
  396. // 文件属性可以在Head Object操作中被查询到,当您发起Head Object请求时,会返回自定义Header『x-cos-object-type』,该Header只有两个枚举值:Normal或者Appendable。
  397. //
  398. // 追加上传建议文件大小1M - 5G。如果position的值和当前Object的长度不致,COS会返回409错误。
  399. // 如果Append一个Normal的Object,COS会返回409 ObjectNotAppendable。
  400. //
  401. // Appendable的文件不可以被复制,不参与版本管理,不参与生命周期管理,不可跨区域复制。
  402. //
  403. // 当 r 不是 bytes.Buffer/bytes.Reader/strings.Reader 时,必须指定 opt.ObjectPutHeaderOptions.ContentLength
  404. //
  405. // https://www.qcloud.com/document/product/436/7741
  406. // func (s *ObjectService) Append(ctx context.Context, name string, position int, r io.Reader, opt *ObjectPutOptions) (*Response, error) {
  407. // u := fmt.Sprintf("/%s?append&position=%d", encodeURIComponent(name), position)
  408. // if position != 0{
  409. // opt = nil
  410. // }
  411. // sendOpt := sendOptions{
  412. // baseURL: s.client.BaseURL.BucketURL,
  413. // uri: u,
  414. // method: http.MethodPost,
  415. // optHeader: opt,
  416. // body: r,
  417. // }
  418. // resp, err := s.client.send(ctx, &sendOpt)
  419. // return resp, err
  420. // }
  421. // ObjectDeleteMultiOptions is the option of DeleteMulti
  422. type ObjectDeleteMultiOptions struct {
  423. XMLName xml.Name `xml:"Delete" header:"-"`
  424. Quiet bool `xml:"Quiet" header:"-"`
  425. Objects []Object `xml:"Object" header:"-"`
  426. //XCosSha1 string `xml:"-" header:"x-cos-sha1"`
  427. }
  428. // ObjectDeleteMultiResult is the result of DeleteMulti
  429. type ObjectDeleteMultiResult struct {
  430. XMLName xml.Name `xml:"DeleteResult"`
  431. DeletedObjects []Object `xml:"Deleted,omitempty"`
  432. Errors []struct {
  433. Key string `xml:",omitempty"`
  434. Code string `xml:",omitempty"`
  435. Message string `xml:",omitempty"`
  436. VersionId string `xml:",omitempty"`
  437. } `xml:"Error,omitempty"`
  438. }
  439. // DeleteMulti 请求实现批量删除文件,最大支持单次删除1000个文件。
  440. // 对于返回结果,COS提供Verbose和Quiet两种结果模式。Verbose模式将返回每个Object的删除结果;
  441. // Quiet模式只返回报错的Object信息。
  442. // https://www.qcloud.com/document/product/436/8289
  443. func (s *ObjectService) DeleteMulti(ctx context.Context, opt *ObjectDeleteMultiOptions) (*ObjectDeleteMultiResult, *Response, error) {
  444. var res ObjectDeleteMultiResult
  445. sendOpt := sendOptions{
  446. baseURL: s.client.BaseURL.BucketURL,
  447. uri: "/?delete",
  448. method: http.MethodPost,
  449. body: opt,
  450. result: &res,
  451. }
  452. resp, err := s.client.send(ctx, &sendOpt)
  453. return &res, resp, err
  454. }
  455. // Object is the meta info of the object
  456. type Object struct {
  457. Key string `xml:",omitempty"`
  458. ETag string `xml:",omitempty"`
  459. Size int `xml:",omitempty"`
  460. PartNumber int `xml:",omitempty"`
  461. LastModified string `xml:",omitempty"`
  462. StorageClass string `xml:",omitempty"`
  463. Owner *Owner `xml:",omitempty"`
  464. VersionId string `xml:",omitempty"`
  465. }
  466. // MultiUploadOptions is the option of the multiupload,
  467. // ThreadPoolSize default is one
  468. type MultiUploadOptions struct {
  469. OptIni *InitiateMultipartUploadOptions
  470. PartSize int64
  471. ThreadPoolSize int
  472. CheckPoint bool
  473. }
  474. type Chunk struct {
  475. Number int
  476. OffSet int64
  477. Size int64
  478. Done bool
  479. ETag string
  480. }
  481. // jobs
  482. type Jobs struct {
  483. Name string
  484. UploadId string
  485. FilePath string
  486. RetryTimes int
  487. Chunk Chunk
  488. Data io.Reader
  489. Opt *ObjectUploadPartOptions
  490. }
  491. type Results struct {
  492. PartNumber int
  493. Resp *Response
  494. err error
  495. }
  496. func worker(s *ObjectService, jobs <-chan *Jobs, results chan<- *Results) {
  497. for j := range jobs {
  498. fd, err := os.Open(j.FilePath)
  499. var res Results
  500. if err != nil {
  501. res.err = err
  502. res.PartNumber = j.Chunk.Number
  503. res.Resp = nil
  504. results <- &res
  505. }
  506. fd.Seek(j.Chunk.OffSet, os.SEEK_SET)
  507. // UploadPart do not support the chunk trsf, so need to add the content-length
  508. j.Opt.ContentLength = int(j.Chunk.Size)
  509. rt := j.RetryTimes
  510. for {
  511. resp, err := s.UploadPart(context.Background(), j.Name, j.UploadId, j.Chunk.Number,
  512. &io.LimitedReader{R: fd, N: j.Chunk.Size}, j.Opt)
  513. res.PartNumber = j.Chunk.Number
  514. res.Resp = resp
  515. res.err = err
  516. if err != nil {
  517. rt--
  518. if rt == 0 {
  519. fd.Close()
  520. results <- &res
  521. break
  522. }
  523. continue
  524. }
  525. fd.Close()
  526. results <- &res
  527. break
  528. }
  529. }
  530. }
  531. func DividePart(fileSize int64) (int64, int64) {
  532. partSize := int64(1 * 1024 * 1024)
  533. partNum := fileSize / partSize
  534. for partNum >= 10000 {
  535. partSize = partSize * 2
  536. partNum = fileSize / partSize
  537. }
  538. return partNum, partSize
  539. }
  540. func SplitFileIntoChunks(filePath string, partSize int64) (int64, []Chunk, int, error) {
  541. if filePath == "" {
  542. return 0, nil, 0, errors.New("filePath invalid")
  543. }
  544. file, err := os.Open(filePath)
  545. if err != nil {
  546. return 0, nil, 0, err
  547. }
  548. defer file.Close()
  549. stat, err := file.Stat()
  550. if err != nil {
  551. return 0, nil, 0, err
  552. }
  553. var partNum int64
  554. if partSize > 0 {
  555. partSize = partSize * 1024 * 1024
  556. partNum = stat.Size() / partSize
  557. if partNum >= 10000 {
  558. return 0, nil, 0, errors.New("Too many parts, out of 10000")
  559. }
  560. } else {
  561. partNum, partSize = DividePart(stat.Size())
  562. }
  563. var chunks []Chunk
  564. var chunk = Chunk{}
  565. for i := int64(0); i < partNum; i++ {
  566. chunk.Number = int(i + 1)
  567. chunk.OffSet = i * partSize
  568. chunk.Size = partSize
  569. chunks = append(chunks, chunk)
  570. }
  571. if stat.Size()%partSize > 0 {
  572. chunk.Number = len(chunks) + 1
  573. chunk.OffSet = int64(len(chunks)) * partSize
  574. chunk.Size = stat.Size() % partSize
  575. chunks = append(chunks, chunk)
  576. partNum++
  577. }
  578. return int64(stat.Size()), chunks, int(partNum), nil
  579. }
  580. func (s *ObjectService) getResumableUploadID(ctx context.Context, name string) (string, error) {
  581. opt := &ObjectListUploadsOptions{
  582. Prefix: name,
  583. EncodingType: "url",
  584. }
  585. res, _, err := s.ListUploads(ctx, opt)
  586. if err != nil {
  587. return "", err
  588. }
  589. if len(res.Upload) == 0 {
  590. return "", nil
  591. }
  592. last := len(res.Upload) - 1
  593. for last >= 0 {
  594. decodeKey, _ := decodeURIComponent(res.Upload[last].Key)
  595. if decodeKey == name {
  596. return decodeURIComponent(res.Upload[last].UploadID)
  597. }
  598. last = last - 1
  599. }
  600. return "", nil
  601. }
  602. func (s *ObjectService) checkUploadedParts(ctx context.Context, name, UploadID, filepath string, chunks []Chunk, partNum int) error {
  603. var uploadedParts []Object
  604. isTruncated := true
  605. opt := &ObjectListPartsOptions{
  606. EncodingType: "url",
  607. }
  608. for isTruncated {
  609. res, _, err := s.ListParts(ctx, name, UploadID, opt)
  610. if err != nil {
  611. return err
  612. }
  613. if len(res.Parts) > 0 {
  614. uploadedParts = append(uploadedParts, res.Parts...)
  615. }
  616. isTruncated = res.IsTruncated
  617. opt.PartNumberMarker = res.NextPartNumberMarker
  618. }
  619. fd, err := os.Open(filepath)
  620. if err != nil {
  621. return err
  622. }
  623. defer fd.Close()
  624. // 某个分块出错, 重置chunks
  625. ret := func(e error) error {
  626. for i, _ := range chunks {
  627. chunks[i].Done = false
  628. chunks[i].ETag = ""
  629. }
  630. return e
  631. }
  632. for _, part := range uploadedParts {
  633. partNumber := part.PartNumber
  634. if partNumber > partNum {
  635. return ret(errors.New("Part Number is not consistent"))
  636. }
  637. partNumber = partNumber - 1
  638. fd.Seek(chunks[partNumber].OffSet, os.SEEK_SET)
  639. bs, err := ioutil.ReadAll(io.LimitReader(fd, chunks[partNumber].Size))
  640. if err != nil {
  641. return ret(err)
  642. }
  643. localMD5 := fmt.Sprintf("\"%x\"", md5.Sum(bs))
  644. if localMD5 != part.ETag {
  645. return ret(errors.New(fmt.Sprintf("CheckSum Failed in Part[%d]", part.PartNumber)))
  646. }
  647. chunks[partNumber].Done = true
  648. chunks[partNumber].ETag = part.ETag
  649. }
  650. return nil
  651. }
  652. // MultiUpload/Upload 为高级upload接口,并发分块上传
  653. // 注意该接口目前只供参考
  654. //
  655. // 当 partSize > 0 时,由调用者指定分块大小,否则由 SDK 自动切分,单位为MB
  656. // 由调用者指定分块大小时,请确认分块数量不超过10000
  657. //
  658. func (s *ObjectService) MultiUpload(ctx context.Context, name string, filepath string, opt *MultiUploadOptions) (*CompleteMultipartUploadResult, *Response, error) {
  659. return s.Upload(ctx, name, filepath, opt)
  660. }
  661. func (s *ObjectService) Upload(ctx context.Context, name string, filepath string, opt *MultiUploadOptions) (*CompleteMultipartUploadResult, *Response, error) {
  662. if opt == nil {
  663. opt = &MultiUploadOptions{}
  664. }
  665. // 1.Get the file chunk
  666. totalBytes, chunks, partNum, err := SplitFileIntoChunks(filepath, opt.PartSize)
  667. if err != nil {
  668. return nil, nil, err
  669. }
  670. // filesize=0 , use simple upload
  671. if partNum == 0 {
  672. var opt0 *ObjectPutOptions
  673. if opt.OptIni != nil {
  674. opt0 = &ObjectPutOptions{
  675. opt.OptIni.ACLHeaderOptions,
  676. opt.OptIni.ObjectPutHeaderOptions,
  677. }
  678. }
  679. rsp, err := s.PutFromFile(ctx, name, filepath, opt0)
  680. if err != nil {
  681. return nil, rsp, err
  682. }
  683. result := &CompleteMultipartUploadResult{
  684. Key: name,
  685. ETag: rsp.Header.Get("ETag"),
  686. }
  687. return result, rsp, nil
  688. }
  689. var uploadID string
  690. resumableFlag := false
  691. if opt.CheckPoint {
  692. var err error
  693. uploadID, err = s.getResumableUploadID(ctx, name)
  694. if err == nil && uploadID != "" {
  695. err = s.checkUploadedParts(ctx, name, uploadID, filepath, chunks, partNum)
  696. resumableFlag = (err == nil)
  697. }
  698. }
  699. // 2.Init
  700. optini := opt.OptIni
  701. if !resumableFlag {
  702. res, _, err := s.InitiateMultipartUpload(ctx, name, optini)
  703. if err != nil {
  704. return nil, nil, err
  705. }
  706. uploadID = res.UploadID
  707. }
  708. var poolSize int
  709. if opt.ThreadPoolSize > 0 {
  710. poolSize = opt.ThreadPoolSize
  711. } else {
  712. // Default is one
  713. poolSize = 1
  714. }
  715. chjobs := make(chan *Jobs, 100)
  716. chresults := make(chan *Results, 10000)
  717. optcom := &CompleteMultipartUploadOptions{}
  718. // 3.Start worker
  719. for w := 1; w <= poolSize; w++ {
  720. go worker(s, chjobs, chresults)
  721. }
  722. // progress started event
  723. var listener ProgressListener
  724. var consumedBytes int64
  725. if opt.OptIni != nil {
  726. listener = opt.OptIni.Listener
  727. }
  728. event := newProgressEvent(ProgressStartedEvent, 0, 0, totalBytes)
  729. progressCallback(listener, event)
  730. // 4.Push jobs
  731. for _, chunk := range chunks {
  732. if chunk.Done {
  733. continue
  734. }
  735. partOpt := &ObjectUploadPartOptions{}
  736. if optini != nil && optini.ObjectPutHeaderOptions != nil {
  737. partOpt.XCosSSECustomerAglo = optini.XCosSSECustomerAglo
  738. partOpt.XCosSSECustomerKey = optini.XCosSSECustomerKey
  739. partOpt.XCosSSECustomerKeyMD5 = optini.XCosSSECustomerKeyMD5
  740. partOpt.XCosTrafficLimit = optini.XCosTrafficLimit
  741. }
  742. job := &Jobs{
  743. Name: name,
  744. RetryTimes: 3,
  745. FilePath: filepath,
  746. UploadId: uploadID,
  747. Chunk: chunk,
  748. Opt: partOpt,
  749. }
  750. chjobs <- job
  751. }
  752. close(chjobs)
  753. // 5.Recv the resp etag to complete
  754. for i := 0; i < partNum; i++ {
  755. if chunks[i].Done {
  756. optcom.Parts = append(optcom.Parts, Object{
  757. PartNumber: chunks[i].Number, ETag: chunks[i].ETag},
  758. )
  759. consumedBytes += chunks[i].Size
  760. event = newProgressEvent(ProgressDataEvent, chunks[i].Size, consumedBytes, totalBytes)
  761. progressCallback(listener, event)
  762. continue
  763. }
  764. res := <-chresults
  765. // Notice one part fail can not get the etag according.
  766. if res.Resp == nil || res.err != nil {
  767. // Some part already fail, can not to get the header inside.
  768. err := fmt.Errorf("UploadID %s, part %d failed to get resp content. error: %s", uploadID, res.PartNumber, res.err.Error())
  769. event = newProgressEvent(ProgressFailedEvent, 0, consumedBytes, totalBytes, err)
  770. progressCallback(listener, event)
  771. return nil, nil, err
  772. }
  773. // Notice one part fail can not get the etag according.
  774. etag := res.Resp.Header.Get("ETag")
  775. optcom.Parts = append(optcom.Parts, Object{
  776. PartNumber: res.PartNumber, ETag: etag},
  777. )
  778. consumedBytes += chunks[res.PartNumber-1].Size
  779. event = newProgressEvent(ProgressDataEvent, chunks[res.PartNumber-1].Size, consumedBytes, totalBytes)
  780. progressCallback(listener, event)
  781. }
  782. sort.Sort(ObjectList(optcom.Parts))
  783. event = newProgressEvent(ProgressCompletedEvent, 0, consumedBytes, totalBytes)
  784. progressCallback(listener, event)
  785. v, resp, err := s.CompleteMultipartUpload(context.Background(), name, uploadID, optcom)
  786. return v, resp, err
  787. }
  788. type ObjectPutTaggingOptions struct {
  789. XMLName xml.Name `xml:"Tagging"`
  790. TagSet []ObjectTaggingTag `xml:"TagSet>Tag,omitempty"`
  791. }
  792. type ObjectTaggingTag BucketTaggingTag
  793. type ObjectGetTaggingResult ObjectPutTaggingOptions
  794. func (s *ObjectService) PutTagging(ctx context.Context, name string, opt *ObjectPutTaggingOptions, id ...string) (*Response, error) {
  795. var u string
  796. if len(id) == 1 {
  797. u = fmt.Sprintf("/%s?tagging&versionId=%s", encodeURIComponent(name), id[0])
  798. } else if len(id) == 0 {
  799. u = fmt.Sprintf("/%s?tagging", encodeURIComponent(name))
  800. } else {
  801. return nil, errors.New("wrong params")
  802. }
  803. sendOpt := &sendOptions{
  804. baseURL: s.client.BaseURL.BucketURL,
  805. uri: u,
  806. method: http.MethodPut,
  807. body: opt,
  808. }
  809. resp, err := s.client.send(ctx, sendOpt)
  810. return resp, err
  811. }
  812. func (s *ObjectService) GetTagging(ctx context.Context, name string, id ...string) (*ObjectGetTaggingResult, *Response, error) {
  813. var u string
  814. if len(id) == 1 {
  815. u = fmt.Sprintf("/%s?tagging&versionId=%s", encodeURIComponent(name), id[0])
  816. } else if len(id) == 0 {
  817. u = fmt.Sprintf("/%s?tagging", encodeURIComponent(name))
  818. } else {
  819. return nil, nil, errors.New("wrong params")
  820. }
  821. var res ObjectGetTaggingResult
  822. sendOpt := &sendOptions{
  823. baseURL: s.client.BaseURL.BucketURL,
  824. uri: u,
  825. method: http.MethodGet,
  826. result: &res,
  827. }
  828. resp, err := s.client.send(ctx, sendOpt)
  829. return &res, resp, err
  830. }
  831. func (s *ObjectService) DeleteTagging(ctx context.Context, name string, id ...string) (*Response, error) {
  832. var u string
  833. if len(id) == 1 {
  834. u = fmt.Sprintf("/%s?tagging&versionId=%s", encodeURIComponent(name), id[0])
  835. } else if len(id) == 0 {
  836. u = fmt.Sprintf("/%s?tagging", encodeURIComponent(name))
  837. } else {
  838. return nil, errors.New("wrong params")
  839. }
  840. sendOpt := &sendOptions{
  841. baseURL: s.client.BaseURL.BucketURL,
  842. uri: u,
  843. method: http.MethodDelete,
  844. }
  845. resp, err := s.client.send(ctx, sendOpt)
  846. return resp, err
  847. }