adaptor.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. package kling
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strings"
  9. "time"
  10. "github.com/QuantumNous/new-api/common"
  11. "github.com/QuantumNous/new-api/model"
  12. "github.com/samber/lo"
  13. "github.com/gin-gonic/gin"
  14. "github.com/golang-jwt/jwt/v5"
  15. "github.com/pkg/errors"
  16. "github.com/QuantumNous/new-api/constant"
  17. "github.com/QuantumNous/new-api/dto"
  18. "github.com/QuantumNous/new-api/relay/channel"
  19. relaycommon "github.com/QuantumNous/new-api/relay/common"
  20. "github.com/QuantumNous/new-api/service"
  21. )
  22. // ============================
  23. // Request / Response structures
  24. // ============================
  25. type TrajectoryPoint struct {
  26. X int `json:"x"`
  27. Y int `json:"y"`
  28. }
  29. type DynamicMask struct {
  30. Mask string `json:"mask,omitempty"`
  31. Trajectories []TrajectoryPoint `json:"trajectories,omitempty"`
  32. }
  33. type CameraConfig struct {
  34. Horizontal float64 `json:"horizontal,omitempty"`
  35. Vertical float64 `json:"vertical,omitempty"`
  36. Pan float64 `json:"pan,omitempty"`
  37. Tilt float64 `json:"tilt,omitempty"`
  38. Roll float64 `json:"roll,omitempty"`
  39. Zoom float64 `json:"zoom,omitempty"`
  40. }
  41. type CameraControl struct {
  42. Type string `json:"type,omitempty"`
  43. Config *CameraConfig `json:"config,omitempty"`
  44. }
  45. type requestPayload struct {
  46. Prompt string `json:"prompt,omitempty"`
  47. Image string `json:"image,omitempty"`
  48. ImageTail string `json:"image_tail,omitempty"`
  49. NegativePrompt string `json:"negative_prompt,omitempty"`
  50. Mode string `json:"mode,omitempty"`
  51. Duration string `json:"duration,omitempty"`
  52. AspectRatio string `json:"aspect_ratio,omitempty"`
  53. ModelName string `json:"model_name,omitempty"`
  54. Model string `json:"model,omitempty"` // Compatible with upstreams that only recognize "model"
  55. CfgScale float64 `json:"cfg_scale,omitempty"`
  56. StaticMask string `json:"static_mask,omitempty"`
  57. DynamicMasks []DynamicMask `json:"dynamic_masks,omitempty"`
  58. CameraControl *CameraControl `json:"camera_control,omitempty"`
  59. CallbackUrl string `json:"callback_url,omitempty"`
  60. ExternalTaskId string `json:"external_task_id,omitempty"`
  61. }
  62. type responsePayload struct {
  63. Code int `json:"code"`
  64. Message string `json:"message"`
  65. TaskId string `json:"task_id"`
  66. RequestId string `json:"request_id"`
  67. Data struct {
  68. TaskId string `json:"task_id"`
  69. TaskStatus string `json:"task_status"`
  70. TaskStatusMsg string `json:"task_status_msg"`
  71. TaskResult struct {
  72. Videos []struct {
  73. Id string `json:"id"`
  74. Url string `json:"url"`
  75. Duration string `json:"duration"`
  76. } `json:"videos"`
  77. } `json:"task_result"`
  78. CreatedAt int64 `json:"created_at"`
  79. UpdatedAt int64 `json:"updated_at"`
  80. } `json:"data"`
  81. }
  82. // ============================
  83. // Adaptor implementation
  84. // ============================
  85. type TaskAdaptor struct {
  86. ChannelType int
  87. apiKey string
  88. baseURL string
  89. }
  90. func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
  91. a.ChannelType = info.ChannelType
  92. a.baseURL = info.ChannelBaseUrl
  93. a.apiKey = info.ApiKey
  94. // apiKey format: "access_key|secret_key"
  95. }
  96. // ValidateRequestAndSetAction parses body, validates fields and sets default action.
  97. func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
  98. // Use the standard validation method for TaskSubmitReq
  99. return relaycommon.ValidateBasicTaskRequest(c, info, constant.TaskActionGenerate)
  100. }
  101. // BuildRequestURL constructs the upstream URL.
  102. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
  103. path := lo.Ternary(info.Action == constant.TaskActionGenerate, "/v1/videos/image2video", "/v1/videos/text2video")
  104. if isNewAPIRelay(info.ApiKey) {
  105. return fmt.Sprintf("%s/kling%s", a.baseURL, path), nil
  106. }
  107. return fmt.Sprintf("%s%s", a.baseURL, path), nil
  108. }
  109. // BuildRequestHeader sets required headers.
  110. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  111. token, err := a.createJWTToken()
  112. if err != nil {
  113. return fmt.Errorf("failed to create JWT token: %w", err)
  114. }
  115. req.Header.Set("Content-Type", "application/json")
  116. req.Header.Set("Accept", "application/json")
  117. req.Header.Set("Authorization", "Bearer "+token)
  118. req.Header.Set("User-Agent", "kling-sdk/1.0")
  119. return nil
  120. }
  121. // BuildRequestBody converts request into Kling specific format.
  122. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  123. v, exists := c.Get("task_request")
  124. if !exists {
  125. return nil, fmt.Errorf("request not found in context")
  126. }
  127. req := v.(relaycommon.TaskSubmitReq)
  128. body, err := a.convertToRequestPayload(&req)
  129. if err != nil {
  130. return nil, err
  131. }
  132. if body.Image == "" && body.ImageTail == "" {
  133. c.Set("action", constant.TaskActionTextGenerate)
  134. }
  135. data, err := json.Marshal(body)
  136. if err != nil {
  137. return nil, err
  138. }
  139. return bytes.NewReader(data), nil
  140. }
  141. // DoRequest delegates to common helper.
  142. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  143. if action := c.GetString("action"); action != "" {
  144. info.Action = action
  145. }
  146. return channel.DoTaskApiRequest(a, c, info, requestBody)
  147. }
  148. // DoResponse handles upstream response, returns taskID etc.
  149. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  150. responseBody, err := io.ReadAll(resp.Body)
  151. if err != nil {
  152. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  153. return
  154. }
  155. var kResp responsePayload
  156. err = json.Unmarshal(responseBody, &kResp)
  157. if err != nil {
  158. taskErr = service.TaskErrorWrapper(err, "unmarshal_response_failed", http.StatusInternalServerError)
  159. return
  160. }
  161. if kResp.Code != 0 {
  162. taskErr = service.TaskErrorWrapperLocal(fmt.Errorf(kResp.Message), "task_failed", http.StatusBadRequest)
  163. return
  164. }
  165. ov := dto.NewOpenAIVideo()
  166. ov.ID = kResp.Data.TaskId
  167. ov.TaskID = kResp.Data.TaskId
  168. ov.CreatedAt = time.Now().Unix()
  169. ov.Model = info.OriginModelName
  170. c.JSON(http.StatusOK, ov)
  171. return kResp.Data.TaskId, responseBody, nil
  172. }
  173. // FetchTask fetch task status
  174. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any) (*http.Response, error) {
  175. taskID, ok := body["task_id"].(string)
  176. if !ok {
  177. return nil, fmt.Errorf("invalid task_id")
  178. }
  179. action, ok := body["action"].(string)
  180. if !ok {
  181. return nil, fmt.Errorf("invalid action")
  182. }
  183. path := lo.Ternary(action == constant.TaskActionGenerate, "/v1/videos/image2video", "/v1/videos/text2video")
  184. url := fmt.Sprintf("%s%s/%s", baseUrl, path, taskID)
  185. if isNewAPIRelay(key) {
  186. url = fmt.Sprintf("%s/kling%s/%s", baseUrl, path, taskID)
  187. }
  188. req, err := http.NewRequest(http.MethodGet, url, nil)
  189. if err != nil {
  190. return nil, err
  191. }
  192. token, err := a.createJWTTokenWithKey(key)
  193. if err != nil {
  194. token = key
  195. }
  196. req.Header.Set("Accept", "application/json")
  197. req.Header.Set("Authorization", "Bearer "+token)
  198. req.Header.Set("User-Agent", "kling-sdk/1.0")
  199. return service.GetHttpClient().Do(req)
  200. }
  201. func (a *TaskAdaptor) GetModelList() []string {
  202. return []string{"kling-v1", "kling-v1-6", "kling-v2-master"}
  203. }
  204. func (a *TaskAdaptor) GetChannelName() string {
  205. return "kling"
  206. }
  207. // ============================
  208. // helpers
  209. // ============================
  210. func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*requestPayload, error) {
  211. r := requestPayload{
  212. Prompt: req.Prompt,
  213. Image: req.Image,
  214. Mode: defaultString(req.Mode, "std"),
  215. Duration: fmt.Sprintf("%d", defaultInt(req.Duration, 5)),
  216. AspectRatio: a.getAspectRatio(req.Size),
  217. ModelName: req.Model,
  218. Model: req.Model, // Keep consistent with model_name, double writing improves compatibility
  219. CfgScale: 0.5,
  220. StaticMask: "",
  221. DynamicMasks: []DynamicMask{},
  222. CameraControl: nil,
  223. CallbackUrl: "",
  224. ExternalTaskId: "",
  225. }
  226. if r.ModelName == "" {
  227. r.ModelName = "kling-v1"
  228. }
  229. metadata := req.Metadata
  230. medaBytes, err := json.Marshal(metadata)
  231. if err != nil {
  232. return nil, errors.Wrap(err, "metadata marshal metadata failed")
  233. }
  234. err = json.Unmarshal(medaBytes, &r)
  235. if err != nil {
  236. return nil, errors.Wrap(err, "unmarshal metadata failed")
  237. }
  238. return &r, nil
  239. }
  240. func (a *TaskAdaptor) getAspectRatio(size string) string {
  241. switch size {
  242. case "1024x1024", "512x512":
  243. return "1:1"
  244. case "1280x720", "1920x1080":
  245. return "16:9"
  246. case "720x1280", "1080x1920":
  247. return "9:16"
  248. default:
  249. return "1:1"
  250. }
  251. }
  252. func defaultString(s, def string) string {
  253. if strings.TrimSpace(s) == "" {
  254. return def
  255. }
  256. return s
  257. }
  258. func defaultInt(v int, def int) int {
  259. if v == 0 {
  260. return def
  261. }
  262. return v
  263. }
  264. // ============================
  265. // JWT helpers
  266. // ============================
  267. func (a *TaskAdaptor) createJWTToken() (string, error) {
  268. return a.createJWTTokenWithKey(a.apiKey)
  269. }
  270. func (a *TaskAdaptor) createJWTTokenWithKey(apiKey string) (string, error) {
  271. if isNewAPIRelay(apiKey) {
  272. return apiKey, nil // new api relay
  273. }
  274. keyParts := strings.Split(apiKey, "|")
  275. if len(keyParts) != 2 {
  276. return "", errors.New("invalid api_key, required format is accessKey|secretKey")
  277. }
  278. accessKey := strings.TrimSpace(keyParts[0])
  279. if len(keyParts) == 1 {
  280. return accessKey, nil
  281. }
  282. secretKey := strings.TrimSpace(keyParts[1])
  283. now := time.Now().Unix()
  284. claims := jwt.MapClaims{
  285. "iss": accessKey,
  286. "exp": now + 1800, // 30 minutes
  287. "nbf": now - 5,
  288. }
  289. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  290. token.Header["typ"] = "JWT"
  291. return token.SignedString([]byte(secretKey))
  292. }
  293. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  294. taskInfo := &relaycommon.TaskInfo{}
  295. resPayload := responsePayload{}
  296. err := json.Unmarshal(respBody, &resPayload)
  297. if err != nil {
  298. return nil, errors.Wrap(err, "failed to unmarshal response body")
  299. }
  300. taskInfo.Code = resPayload.Code
  301. taskInfo.TaskID = resPayload.Data.TaskId
  302. taskInfo.Reason = resPayload.Message
  303. //任务状态,枚举值:submitted(已提交)、processing(处理中)、succeed(成功)、failed(失败)
  304. status := resPayload.Data.TaskStatus
  305. switch status {
  306. case "submitted":
  307. taskInfo.Status = model.TaskStatusSubmitted
  308. case "processing":
  309. taskInfo.Status = model.TaskStatusInProgress
  310. case "succeed":
  311. taskInfo.Status = model.TaskStatusSuccess
  312. case "failed":
  313. taskInfo.Status = model.TaskStatusFailure
  314. default:
  315. return nil, fmt.Errorf("unknown task status: %s", status)
  316. }
  317. if videos := resPayload.Data.TaskResult.Videos; len(videos) > 0 {
  318. video := videos[0]
  319. taskInfo.Url = video.Url
  320. }
  321. return taskInfo, nil
  322. }
  323. func isNewAPIRelay(apiKey string) bool {
  324. return strings.HasPrefix(apiKey, "sk-")
  325. }
  326. func (a *TaskAdaptor) ConvertToOpenAIVideo(originTask *model.Task) ([]byte, error) {
  327. var klingResp responsePayload
  328. if err := json.Unmarshal(originTask.Data, &klingResp); err != nil {
  329. return nil, errors.Wrap(err, "unmarshal kling task data failed")
  330. }
  331. openAIVideo := dto.NewOpenAIVideo()
  332. openAIVideo.ID = originTask.TaskID
  333. openAIVideo.Status = originTask.Status.ToVideoStatus()
  334. openAIVideo.SetProgressStr(originTask.Progress)
  335. openAIVideo.CreatedAt = klingResp.Data.CreatedAt
  336. openAIVideo.CompletedAt = klingResp.Data.UpdatedAt
  337. if len(klingResp.Data.TaskResult.Videos) > 0 {
  338. video := klingResp.Data.TaskResult.Videos[0]
  339. if video.Url != "" {
  340. openAIVideo.SetMetadata("url", video.Url)
  341. }
  342. if video.Duration != "" {
  343. openAIVideo.Seconds = video.Duration
  344. }
  345. }
  346. if klingResp.Code != 0 && klingResp.Message != "" {
  347. openAIVideo.Error = &dto.OpenAIVideoError{
  348. Message: klingResp.Message,
  349. Code: fmt.Sprintf("%d", klingResp.Code),
  350. }
  351. }
  352. jsonData, _ := common.Marshal(openAIVideo)
  353. return jsonData, nil
  354. }