adaptor.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. package kling
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/samber/lo"
  7. "io"
  8. "net/http"
  9. "one-api/model"
  10. "strings"
  11. "time"
  12. "github.com/gin-gonic/gin"
  13. "github.com/golang-jwt/jwt"
  14. "github.com/pkg/errors"
  15. "one-api/common"
  16. "one-api/dto"
  17. "one-api/relay/channel"
  18. relaycommon "one-api/relay/common"
  19. "one-api/service"
  20. )
  21. // ============================
  22. // Request / Response structures
  23. // ============================
  24. type SubmitReq struct {
  25. Prompt string `json:"prompt"`
  26. Model string `json:"model,omitempty"`
  27. Mode string `json:"mode,omitempty"`
  28. Image string `json:"image,omitempty"`
  29. Size string `json:"size,omitempty"`
  30. Duration int `json:"duration,omitempty"`
  31. Metadata map[string]interface{} `json:"metadata,omitempty"`
  32. }
  33. type requestPayload struct {
  34. Prompt string `json:"prompt,omitempty"`
  35. Image string `json:"image,omitempty"`
  36. Mode string `json:"mode,omitempty"`
  37. Duration string `json:"duration,omitempty"`
  38. AspectRatio string `json:"aspect_ratio,omitempty"`
  39. ModelName string `json:"model_name,omitempty"`
  40. CfgScale float64 `json:"cfg_scale,omitempty"`
  41. }
  42. type responsePayload struct {
  43. Code int `json:"code"`
  44. Message string `json:"message"`
  45. RequestId string `json:"request_id"`
  46. Data struct {
  47. TaskId string `json:"task_id"`
  48. TaskStatus string `json:"task_status"`
  49. TaskStatusMsg string `json:"task_status_msg"`
  50. TaskResult struct {
  51. Videos []struct {
  52. Id string `json:"id"`
  53. Url string `json:"url"`
  54. Duration string `json:"duration"`
  55. } `json:"videos"`
  56. } `json:"task_result"`
  57. CreatedAt int64 `json:"created_at"`
  58. UpdatedAt int64 `json:"updated_at"`
  59. } `json:"data"`
  60. }
  61. // ============================
  62. // Adaptor implementation
  63. // ============================
  64. type TaskAdaptor struct {
  65. ChannelType int
  66. accessKey string
  67. secretKey string
  68. baseURL string
  69. }
  70. func (a *TaskAdaptor) Init(info *relaycommon.TaskRelayInfo) {
  71. a.ChannelType = info.ChannelType
  72. a.baseURL = info.BaseUrl
  73. // apiKey format: "access_key|secret_key"
  74. keyParts := strings.Split(info.ApiKey, "|")
  75. if len(keyParts) == 2 {
  76. a.accessKey = strings.TrimSpace(keyParts[0])
  77. a.secretKey = strings.TrimSpace(keyParts[1])
  78. }
  79. }
  80. // ValidateRequestAndSetAction parses body, validates fields and sets default action.
  81. func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.TaskRelayInfo) (taskErr *dto.TaskError) {
  82. // Accept only POST /v1/video/generations as "generate" action.
  83. action := "generate"
  84. info.Action = action
  85. var req SubmitReq
  86. if err := common.UnmarshalBodyReusable(c, &req); err != nil {
  87. taskErr = service.TaskErrorWrapperLocal(err, "invalid_request", http.StatusBadRequest)
  88. return
  89. }
  90. if strings.TrimSpace(req.Prompt) == "" {
  91. taskErr = service.TaskErrorWrapperLocal(fmt.Errorf("prompt is required"), "invalid_request", http.StatusBadRequest)
  92. return
  93. }
  94. // Store into context for later usage
  95. c.Set("task_request", req)
  96. return nil
  97. }
  98. // BuildRequestURL constructs the upstream URL.
  99. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.TaskRelayInfo) (string, error) {
  100. path := lo.Ternary(info.Action == "generate", "/v1/videos/image2video", "/v1/videos/text2video")
  101. return fmt.Sprintf("%s%s", a.baseURL, path), nil
  102. }
  103. // BuildRequestHeader sets required headers.
  104. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.TaskRelayInfo) error {
  105. token, err := a.createJWTToken()
  106. if err != nil {
  107. return fmt.Errorf("failed to create JWT token: %w", err)
  108. }
  109. req.Header.Set("Content-Type", "application/json")
  110. req.Header.Set("Accept", "application/json")
  111. req.Header.Set("Authorization", "Bearer "+token)
  112. req.Header.Set("User-Agent", "kling-sdk/1.0")
  113. return nil
  114. }
  115. // BuildRequestBody converts request into Kling specific format.
  116. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.TaskRelayInfo) (io.Reader, error) {
  117. v, exists := c.Get("task_request")
  118. if !exists {
  119. return nil, fmt.Errorf("request not found in context")
  120. }
  121. req := v.(SubmitReq)
  122. body, err := a.convertToRequestPayload(&req)
  123. if err != nil {
  124. return nil, err
  125. }
  126. data, err := json.Marshal(body)
  127. if err != nil {
  128. return nil, err
  129. }
  130. return bytes.NewReader(data), nil
  131. }
  132. // DoRequest delegates to common helper.
  133. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.TaskRelayInfo, requestBody io.Reader) (*http.Response, error) {
  134. if action := c.GetString("action"); action != "" {
  135. info.Action = action
  136. }
  137. return channel.DoTaskApiRequest(a, c, info, requestBody)
  138. }
  139. // DoResponse handles upstream response, returns taskID etc.
  140. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.TaskRelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  141. responseBody, err := io.ReadAll(resp.Body)
  142. if err != nil {
  143. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  144. return
  145. }
  146. // Attempt Kling response parse first.
  147. var kResp responsePayload
  148. if err := json.Unmarshal(responseBody, &kResp); err == nil && kResp.Code == 0 {
  149. c.JSON(http.StatusOK, gin.H{"task_id": kResp.Data.TaskId})
  150. return kResp.Data.TaskId, responseBody, nil
  151. }
  152. // Fallback generic task response.
  153. var generic dto.TaskResponse[string]
  154. if err := json.Unmarshal(responseBody, &generic); err != nil {
  155. taskErr = service.TaskErrorWrapper(errors.Wrapf(err, "body: %s", responseBody), "unmarshal_response_body_failed", http.StatusInternalServerError)
  156. return
  157. }
  158. if !generic.IsSuccess() {
  159. taskErr = service.TaskErrorWrapper(fmt.Errorf(generic.Message), generic.Code, http.StatusInternalServerError)
  160. return
  161. }
  162. c.JSON(http.StatusOK, gin.H{"task_id": generic.Data})
  163. return generic.Data, responseBody, nil
  164. }
  165. // FetchTask fetch task status
  166. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any) (*http.Response, error) {
  167. taskID, ok := body["task_id"].(string)
  168. if !ok {
  169. return nil, fmt.Errorf("invalid task_id")
  170. }
  171. action, ok := body["action"].(string)
  172. if !ok {
  173. return nil, fmt.Errorf("invalid action")
  174. }
  175. path := lo.Ternary(action == "generate", "/v1/videos/image2video", "/v1/videos/text2video")
  176. url := fmt.Sprintf("%s%s/%s", baseUrl, path, taskID)
  177. req, err := http.NewRequest(http.MethodGet, url, nil)
  178. if err != nil {
  179. return nil, err
  180. }
  181. token, err := a.createJWTTokenWithKey(key)
  182. if err != nil {
  183. token = key
  184. }
  185. req.Header.Set("Accept", "application/json")
  186. req.Header.Set("Authorization", "Bearer "+token)
  187. req.Header.Set("User-Agent", "kling-sdk/1.0")
  188. return service.GetHttpClient().Do(req)
  189. }
  190. func (a *TaskAdaptor) GetModelList() []string {
  191. return []string{"kling-v1", "kling-v1-6", "kling-v2-master"}
  192. }
  193. func (a *TaskAdaptor) GetChannelName() string {
  194. return "kling"
  195. }
  196. // ============================
  197. // helpers
  198. // ============================
  199. func (a *TaskAdaptor) convertToRequestPayload(req *SubmitReq) (*requestPayload, error) {
  200. r := requestPayload{
  201. Prompt: req.Prompt,
  202. Image: req.Image,
  203. Mode: defaultString(req.Mode, "std"),
  204. Duration: fmt.Sprintf("%d", defaultInt(req.Duration, 5)),
  205. AspectRatio: a.getAspectRatio(req.Size),
  206. ModelName: req.Model,
  207. CfgScale: 0.5,
  208. }
  209. if r.ModelName == "" {
  210. r.ModelName = "kling-v1"
  211. }
  212. metadata := req.Metadata
  213. medaBytes, err := json.Marshal(metadata)
  214. if err != nil {
  215. return nil, errors.Wrap(err, "metadata marshal metadata failed")
  216. }
  217. err = json.Unmarshal(medaBytes, &r)
  218. if err != nil {
  219. return nil, errors.Wrap(err, "unmarshal metadata failed")
  220. }
  221. return &r, nil
  222. }
  223. func (a *TaskAdaptor) getAspectRatio(size string) string {
  224. switch size {
  225. case "1024x1024", "512x512":
  226. return "1:1"
  227. case "1280x720", "1920x1080":
  228. return "16:9"
  229. case "720x1280", "1080x1920":
  230. return "9:16"
  231. default:
  232. return "1:1"
  233. }
  234. }
  235. func defaultString(s, def string) string {
  236. if strings.TrimSpace(s) == "" {
  237. return def
  238. }
  239. return s
  240. }
  241. func defaultInt(v int, def int) int {
  242. if v == 0 {
  243. return def
  244. }
  245. return v
  246. }
  247. // ============================
  248. // JWT helpers
  249. // ============================
  250. func (a *TaskAdaptor) createJWTToken() (string, error) {
  251. return a.createJWTTokenWithKeys(a.accessKey, a.secretKey)
  252. }
  253. func (a *TaskAdaptor) createJWTTokenWithKey(apiKey string) (string, error) {
  254. parts := strings.Split(apiKey, "|")
  255. if len(parts) != 2 {
  256. return "", fmt.Errorf("invalid API key format, expected 'access_key,secret_key'")
  257. }
  258. return a.createJWTTokenWithKeys(strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]))
  259. }
  260. func (a *TaskAdaptor) createJWTTokenWithKeys(accessKey, secretKey string) (string, error) {
  261. if accessKey == "" || secretKey == "" {
  262. return "", fmt.Errorf("access key and secret key are required")
  263. }
  264. now := time.Now().Unix()
  265. claims := jwt.MapClaims{
  266. "iss": accessKey,
  267. "exp": now + 1800, // 30 minutes
  268. "nbf": now - 5,
  269. }
  270. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  271. token.Header["typ"] = "JWT"
  272. return token.SignedString([]byte(secretKey))
  273. }
  274. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  275. resPayload := responsePayload{}
  276. err := json.Unmarshal(respBody, &resPayload)
  277. if err != nil {
  278. return nil, errors.Wrap(err, "failed to unmarshal response body")
  279. }
  280. taskInfo := &relaycommon.TaskInfo{}
  281. taskInfo.Code = resPayload.Code
  282. taskInfo.TaskID = resPayload.Data.TaskId
  283. taskInfo.Reason = resPayload.Message
  284. //任务状态,枚举值:submitted(已提交)、processing(处理中)、succeed(成功)、failed(失败)
  285. status := resPayload.Data.TaskStatus
  286. switch status {
  287. case "submitted":
  288. taskInfo.Status = model.TaskStatusSubmitted
  289. case "processing":
  290. taskInfo.Status = model.TaskStatusInProgress
  291. case "succeed":
  292. taskInfo.Status = model.TaskStatusSuccess
  293. case "failed":
  294. taskInfo.Status = model.TaskStatusFailure
  295. default:
  296. return nil, fmt.Errorf("unknown task status: %s", status)
  297. }
  298. if videos := resPayload.Data.TaskResult.Videos; len(videos) > 0 {
  299. video := videos[0]
  300. taskInfo.Url = video.Url
  301. }
  302. return taskInfo, nil
  303. }