adaptor.go 12 KB

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