adaptor.go 9.8 KB

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