spark_upload.go 1.6 KB
package ai

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/rest/httpc"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/tool"
	"net/http"
	"time"
)

func SparkUploadFile(appid string, appKey string, appSecret string, request SparkFileRequest) (id string, err error) {
	var response *http.Response
	request.FileType = "wiki"
	request.Timestamp = fmt.Sprintf("%v", time.Now().Unix())
	request.AppId = appid
	request.Signature = getSignature(appid, appSecret, request.Timestamp)
	if response, err = httpc.Do(context.Background(), http.MethodPost, hostFileUploadUrl, request); err != nil {
		return "", err
	}
	var parseResponse SparkFileResponse
	if err = httpc.Parse(response, &parseResponse); err != nil {
		return "", err
	}
	if parseResponse.Code != 0 {
		return "", fmt.Errorf("code:%v message:%v sid:%v", parseResponse.Code, parseResponse.Desc, parseResponse.Sid)
	}
	id = parseResponse.Data.FileID
	return
}

type (
	SparkFileRequest struct {
		AppId     string `header:"appId"`
		Timestamp string `header:"timestamp"`
		Signature string `header:"signature"`

		Url         string `form:"url"`
		FileName    string `form:"fileName"`
		FileType    string `form:"fileType"`
		CallbackUrl string `form:"callbackUrl,optional"`
	}
	SparkFileResponse struct {
		Flag bool   `json:"flag,optional"`
		Sid  string `json:"sid,optional"`
		Code int    `json:"code,optional"`
		Desc string `json:"desc,optional"`
		Data struct {
			FileID string `json:"fileId,optional"`
		} `json:"data,optional"`
	}
)

func getSignature(appId, secret string, ts string) string {
	auth := tool.Md5ByString(fmt.Sprintf("%v%v", appId, ts))
	return HmacWithSha1base64(auth, secret)
}