couldapi.go 2.06 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
package tencentyun

import (
	"encoding/json"
	"git.hilo.cn/hilo-common/domain"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/regions"
	v20201229 "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ims/v20201229"
	"golang.org/x/net/context"
	"time"
)

const (
	ImageModerationSecretId  = "IKIDqbCXaNt97oEOHtDG3ZomUu3vXsvhDTR8"
	ImageModerationSecretKey = "RdYCYeT0GFyPZS5QUHo43lCNHuFK8fut"
)

func ModerateImage(model *domain.Model, userId uint64, bizType, dataId, fileUrl string) (string, error) {
	beginTime := time.Now()
	credential := common.NewCredential(ImageModerationSecretId, ImageModerationSecretKey)

	client, _ := v20201229.NewClient(credential, regions.Frankfurt, profile.NewClientProfile())

	request := v20201229.NewImageModerationRequest()
	request.BizType = &bizType
	request.DataId = &dataId
	request.FileUrl = &fileUrl

	response, err := client.ImageModerationWithContext(context.Background(), request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		model.Log.Warnf("ModerateImage: An API error has returned: %s", err)
		return "", err
	}
	if err != nil {
		model.Log.Warnf("ModerateImage: An API error has returned: %s", err)
		return "", err
	}
	endTime := time.Now()
	model.Log.Infof("ModerateImage takes %d ms result: %s", endTime.Sub(beginTime).Milliseconds(), response.ToJsonString())

	if response.Response != nil && response.Response.Label != nil && response.Response.Suggestion != nil {
		rsp := *response.Response.Label
		buf, err := json.Marshal(*response.Response)
		if err == nil {
			rsp = string(buf)
		}
		mr := TxModerateRecord{
			UserId:     userId,
			DataId:     dataId,
			FileUrl:    fileUrl,
			Suggestion: *response.Response.Suggestion,
			Response:   rsp}
		if err = model.Db.Create(&mr).Error; err != nil {
			model.Log.Infof("Save TxModerateRecord err: %v", err)
		}
	}

	return *response.Response.Suggestion, nil
}