github.com/openimsdk/tools@v0.0.49/s3/cos/cos.go (about)

     1  // Copyright © 2023 OpenIM. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package cos
    16  
    17  import (
    18  	"context"
    19  	"crypto/hmac"
    20  	"crypto/sha1"
    21  	"encoding/base64"
    22  	"encoding/hex"
    23  	"encoding/json"
    24  	"errors"
    25  	"fmt"
    26  	"net/http"
    27  	"net/url"
    28  	"strconv"
    29  	"strings"
    30  	"time"
    31  
    32  	"github.com/openimsdk/tools/s3"
    33  	"github.com/tencentyun/cos-go-sdk-v5"
    34  
    35  	"github.com/openimsdk/tools/errs"
    36  )
    37  
    38  const (
    39  	minPartSize int64 = 1024 * 1024 * 1        // 1MB
    40  	maxPartSize int64 = 1024 * 1024 * 1024 * 5 // 5GB
    41  	maxNumSize  int64 = 1000
    42  )
    43  
    44  const (
    45  	imagePng  = "png"
    46  	imageJpg  = "jpg"
    47  	imageJpeg = "jpeg"
    48  	imageGif  = "gif"
    49  	imageWebp = "webp"
    50  )
    51  
    52  const successCode = http.StatusOK
    53  
    54  var _ s3.Interface = (*Cos)(nil)
    55  
    56  type Config struct {
    57  	BucketURL    string
    58  	SecretID     string
    59  	SecretKey    string
    60  	SessionToken string
    61  	PublicRead   bool
    62  }
    63  
    64  func NewCos(conf Config) (*Cos, error) {
    65  	u, err := url.Parse(conf.BucketURL)
    66  	if err != nil {
    67  		panic(err)
    68  	}
    69  	client := cos.NewClient(&cos.BaseURL{BucketURL: u}, &http.Client{
    70  		Transport: &cos.AuthorizationTransport{
    71  			SecretID:     conf.SecretID,
    72  			SecretKey:    conf.SecretKey,
    73  			SessionToken: conf.SessionToken,
    74  		},
    75  	})
    76  	return &Cos{
    77  		publicRead: conf.PublicRead,
    78  		copyURL:    u.Host + "/",
    79  		client:     client,
    80  		credential: client.GetCredential(),
    81  	}, nil
    82  }
    83  
    84  type Cos struct {
    85  	publicRead bool
    86  	copyURL    string
    87  	client     *cos.Client
    88  	credential *cos.Credential
    89  }
    90  
    91  func (c *Cos) Engine() string {
    92  	return "tencent-cos"
    93  }
    94  
    95  func (c *Cos) PartLimit() *s3.PartLimit {
    96  	return &s3.PartLimit{
    97  		MinPartSize: minPartSize,
    98  		MaxPartSize: maxPartSize,
    99  		MaxNumSize:  maxNumSize,
   100  	}
   101  }
   102  
   103  func (c *Cos) InitiateMultipartUpload(ctx context.Context, name string) (*s3.InitiateMultipartUploadResult, error) {
   104  	result, _, err := c.client.Object.InitiateMultipartUpload(ctx, name, nil)
   105  	if err != nil {
   106  		return nil, err
   107  	}
   108  	return &s3.InitiateMultipartUploadResult{
   109  		UploadID: result.UploadID,
   110  		Bucket:   result.Bucket,
   111  		Key:      result.Key,
   112  	}, nil
   113  }
   114  
   115  func (c *Cos) CompleteMultipartUpload(ctx context.Context, uploadID string, name string, parts []s3.Part) (*s3.CompleteMultipartUploadResult, error) {
   116  	opts := &cos.CompleteMultipartUploadOptions{
   117  		Parts: make([]cos.Object, len(parts)),
   118  	}
   119  	for i, part := range parts {
   120  		opts.Parts[i] = cos.Object{
   121  			PartNumber: part.PartNumber,
   122  			ETag:       strings.ReplaceAll(part.ETag, `"`, ``),
   123  		}
   124  	}
   125  	result, _, err := c.client.Object.CompleteMultipartUpload(ctx, name, uploadID, opts)
   126  	if err != nil {
   127  		return nil, err
   128  	}
   129  	return &s3.CompleteMultipartUploadResult{
   130  		Location: result.Location,
   131  		Bucket:   result.Bucket,
   132  		Key:      result.Key,
   133  		ETag:     result.ETag,
   134  	}, nil
   135  }
   136  
   137  func (c *Cos) PartSize(ctx context.Context, size int64) (int64, error) {
   138  	if size <= 0 {
   139  		return 0, errors.New("size must be greater than 0")
   140  	}
   141  	if size > maxPartSize*maxNumSize {
   142  		return 0, fmt.Errorf("COS size must be less than the maximum allowed limit")
   143  	}
   144  	if size <= minPartSize*maxNumSize {
   145  		return minPartSize, nil
   146  	}
   147  	partSize := size / maxNumSize
   148  	if size%maxNumSize != 0 {
   149  		partSize++
   150  	}
   151  	return partSize, nil
   152  }
   153  
   154  func (c *Cos) AuthSign(ctx context.Context, uploadID string, name string, expire time.Duration, partNumbers []int) (*s3.AuthSignResult, error) {
   155  	result := s3.AuthSignResult{
   156  		URL:    c.client.BaseURL.BucketURL.String() + "/" + cos.EncodeURIComponent(name),
   157  		Query:  url.Values{"uploadId": {uploadID}},
   158  		Header: make(http.Header),
   159  		Parts:  make([]s3.SignPart, len(partNumbers)),
   160  	}
   161  	req, err := http.NewRequestWithContext(ctx, http.MethodPut, result.URL, nil)
   162  	if err != nil {
   163  		return nil, err
   164  	}
   165  	cos.AddAuthorizationHeader(c.credential.SecretID, c.credential.SecretKey, c.credential.SessionToken, req, cos.NewAuthTime(expire))
   166  	result.Header = req.Header
   167  	for i, partNumber := range partNumbers {
   168  		result.Parts[i] = s3.SignPart{
   169  			PartNumber: partNumber,
   170  			Query:      url.Values{"partNumber": {strconv.Itoa(partNumber)}},
   171  		}
   172  	}
   173  	return &result, nil
   174  }
   175  
   176  func (c *Cos) PresignedPutObject(ctx context.Context, name string, expire time.Duration) (string, error) {
   177  	rawURL, err := c.client.Object.GetPresignedURL(ctx, http.MethodPut, name, c.credential.SecretID, c.credential.SecretKey, expire, nil)
   178  	if err != nil {
   179  		return "", err
   180  	}
   181  	return rawURL.String(), nil
   182  }
   183  
   184  func (c *Cos) DeleteObject(ctx context.Context, name string) error {
   185  	_, err := c.client.Object.Delete(ctx, name)
   186  	return err
   187  }
   188  
   189  func (c *Cos) StatObject(ctx context.Context, name string) (*s3.ObjectInfo, error) {
   190  	if name != "" && name[0] == '/' {
   191  		name = name[1:]
   192  	}
   193  	info, err := c.client.Object.Head(ctx, name, nil)
   194  	if err != nil {
   195  		return nil, err
   196  	}
   197  	res := &s3.ObjectInfo{Key: name}
   198  	if res.ETag = strings.ToLower(strings.ReplaceAll(info.Header.Get("ETag"), `"`, "")); res.ETag == "" {
   199  		return nil, errors.New("StatObject etag not found")
   200  	}
   201  	if contentLengthStr := info.Header.Get("Content-Length"); contentLengthStr == "" {
   202  		return nil, errors.New("StatObject content-length not found")
   203  	} else {
   204  		res.Size, err = strconv.ParseInt(contentLengthStr, 10, 64)
   205  		if err != nil {
   206  			return nil, fmt.Errorf("StatObject content-length parse error: %w", err)
   207  		}
   208  		if res.Size < 0 {
   209  			return nil, errors.New("StatObject content-length must be greater than 0")
   210  		}
   211  	}
   212  	if lastModified := info.Header.Get("Last-Modified"); lastModified == "" {
   213  		return nil, errors.New("StatObject last-modified not found")
   214  	} else {
   215  		res.LastModified, err = time.Parse(http.TimeFormat, lastModified)
   216  		if err != nil {
   217  			return nil, fmt.Errorf("StatObject last-modified parse error: %w", err)
   218  		}
   219  	}
   220  	return res, nil
   221  }
   222  
   223  func (c *Cos) CopyObject(ctx context.Context, src string, dst string) (*s3.CopyObjectInfo, error) {
   224  	sourceURL := c.copyURL + src
   225  	result, _, err := c.client.Object.Copy(ctx, dst, sourceURL, nil)
   226  	if err != nil {
   227  		return nil, err
   228  	}
   229  	return &s3.CopyObjectInfo{
   230  		Key:  dst,
   231  		ETag: strings.ReplaceAll(result.ETag, `"`, ``),
   232  	}, nil
   233  }
   234  
   235  func (c *Cos) IsNotFound(err error) bool {
   236  	switch e := errs.Unwrap(err).(type) {
   237  	case *cos.ErrorResponse:
   238  		return e.Response.StatusCode == http.StatusNotFound || e.Code == "NoSuchKey"
   239  	default:
   240  		return false
   241  	}
   242  }
   243  
   244  func (c *Cos) AbortMultipartUpload(ctx context.Context, uploadID string, name string) error {
   245  	_, err := c.client.Object.AbortMultipartUpload(ctx, name, uploadID)
   246  	return err
   247  }
   248  
   249  func (c *Cos) ListUploadedParts(ctx context.Context, uploadID string, name string, partNumberMarker int, maxParts int) (*s3.ListUploadedPartsResult, error) {
   250  	result, _, err := c.client.Object.ListParts(ctx, name, uploadID, &cos.ObjectListPartsOptions{
   251  		MaxParts:         strconv.Itoa(maxParts),
   252  		PartNumberMarker: strconv.Itoa(partNumberMarker),
   253  	})
   254  	if err != nil {
   255  		return nil, err
   256  	}
   257  	res := &s3.ListUploadedPartsResult{
   258  		Key:           result.Key,
   259  		UploadID:      result.UploadID,
   260  		UploadedParts: make([]s3.UploadedPart, len(result.Parts)),
   261  	}
   262  	res.MaxParts, _ = strconv.Atoi(result.MaxParts)
   263  	res.NextPartNumberMarker, _ = strconv.Atoi(result.NextPartNumberMarker)
   264  	for i, part := range result.Parts {
   265  		lastModified, _ := time.Parse(http.TimeFormat, part.LastModified)
   266  		res.UploadedParts[i] = s3.UploadedPart{
   267  			PartNumber:   part.PartNumber,
   268  			LastModified: lastModified,
   269  			ETag:         part.ETag,
   270  			Size:         part.Size,
   271  		}
   272  	}
   273  	return res, nil
   274  }
   275  
   276  func (c *Cos) AccessURL(ctx context.Context, name string, expire time.Duration, opt *s3.AccessURLOption) (string, error) {
   277  	var imageMogr string
   278  	var option cos.PresignedURLOptions
   279  	if opt != nil {
   280  		query := make(url.Values)
   281  		if opt.Image != nil {
   282  			// https://cloud.tencent.com/document/product/436/44880
   283  			style := make([]string, 0, 2)
   284  			wh := make([]string, 2)
   285  			if opt.Image.Width > 0 {
   286  				wh[0] = strconv.Itoa(opt.Image.Width)
   287  			}
   288  			if opt.Image.Height > 0 {
   289  				wh[1] = strconv.Itoa(opt.Image.Height)
   290  			}
   291  			if opt.Image.Width > 0 || opt.Image.Height > 0 {
   292  				style = append(style, strings.Join(wh, "x"))
   293  			}
   294  			switch opt.Image.Format {
   295  			case
   296  				imagePng,
   297  				imageJpg,
   298  				imageJpeg,
   299  				imageGif,
   300  				imageWebp:
   301  				style = append(style, "format/"+opt.Image.Format)
   302  			}
   303  			if len(style) > 0 {
   304  				imageMogr = "imageMogr2/thumbnail/" + strings.Join(style, "/") + "/ignore-error/1"
   305  			}
   306  		}
   307  		if opt.ContentType != "" {
   308  			query.Set("response-content-type", opt.ContentType)
   309  		}
   310  		if opt.Filename != "" {
   311  			query.Set("response-content-disposition", `attachment; filename=`+strconv.Quote(opt.Filename))
   312  		}
   313  		if len(query) > 0 {
   314  			option.Query = &query
   315  		}
   316  	}
   317  	if expire <= 0 {
   318  		expire = time.Hour * 24 * 365 * 99 // 99 years
   319  	} else if expire < time.Second {
   320  		expire = time.Second
   321  	}
   322  	rawURL, err := c.getPresignedURL(ctx, name, expire, &option)
   323  	if err != nil {
   324  		return "", err
   325  	}
   326  	if imageMogr != "" {
   327  		if rawURL.RawQuery == "" {
   328  			rawURL.RawQuery = imageMogr
   329  		} else {
   330  			rawURL.RawQuery = rawURL.RawQuery + "&" + imageMogr
   331  		}
   332  	}
   333  	return rawURL.String(), nil
   334  }
   335  
   336  func (c *Cos) getPresignedURL(ctx context.Context, name string, expire time.Duration, opt *cos.PresignedURLOptions) (*url.URL, error) {
   337  	if !c.publicRead {
   338  		return c.client.Object.GetPresignedURL(ctx, http.MethodGet, name, c.credential.SecretID, c.credential.SecretKey, expire, opt)
   339  	}
   340  	return c.client.Object.GetObjectURL(name), nil
   341  }
   342  
   343  func (c *Cos) FormData(ctx context.Context, name string, size int64, contentType string, duration time.Duration) (*s3.FormData, error) {
   344  	// https://cloud.tencent.com/document/product/436/14690
   345  	now := time.Now()
   346  	expiration := now.Add(duration)
   347  	keyTime := fmt.Sprintf("%d;%d", now.Unix(), expiration.Unix())
   348  	conditions := []any{
   349  		map[string]string{"q-sign-algorithm": "sha1"},
   350  		map[string]string{"q-ak": c.credential.SecretID},
   351  		map[string]string{"q-sign-time": keyTime},
   352  		map[string]string{"key": name},
   353  	}
   354  	if contentType != "" {
   355  		conditions = append(conditions, map[string]string{"Content-Type": contentType})
   356  	}
   357  	policy := map[string]any{
   358  		"expiration": expiration.Format("2006-01-02T15:04:05.000Z"),
   359  		"conditions": conditions,
   360  	}
   361  	policyJson, err := json.Marshal(policy)
   362  	if err != nil {
   363  		return nil, err
   364  	}
   365  	signKey := hmacSha1val(c.credential.SecretKey, keyTime)
   366  	strToSign := sha1val(string(policyJson))
   367  	signature := hmacSha1val(signKey, strToSign)
   368  
   369  	fd := &s3.FormData{
   370  		URL:     c.client.BaseURL.BucketURL.String(),
   371  		File:    "file",
   372  		Expires: expiration,
   373  		FormData: map[string]string{
   374  			"policy":                base64.StdEncoding.EncodeToString(policyJson),
   375  			"q-sign-algorithm":      "sha1",
   376  			"q-ak":                  c.credential.SecretID,
   377  			"q-key-time":            keyTime,
   378  			"q-signature":           signature,
   379  			"key":                   name,
   380  			"success_action_status": strconv.Itoa(successCode),
   381  		},
   382  		SuccessCodes: []int{successCode},
   383  	}
   384  	if contentType != "" {
   385  		fd.FormData["Content-Type"] = contentType
   386  	}
   387  	if c.credential.SessionToken != "" {
   388  		fd.FormData["x-cos-security-token"] = c.credential.SessionToken
   389  	}
   390  	return fd, nil
   391  }
   392  
   393  func hmacSha1val(key, msg string) string {
   394  	v := hmac.New(sha1.New, []byte(key))
   395  	v.Write([]byte(msg))
   396  	return hex.EncodeToString(v.Sum(nil))
   397  }
   398  
   399  func sha1val(msg string) string {
   400  	sha1Hash := sha1.New()
   401  	sha1Hash.Write([]byte(msg))
   402  	return hex.EncodeToString(sha1Hash.Sum(nil))
   403  }