adaptor.go 10.0 KB

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