adaptor.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. package kling
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "one-api/model"
  9. "strings"
  10. "time"
  11. "github.com/samber/lo"
  12. "github.com/gin-gonic/gin"
  13. "github.com/golang-jwt/jwt"
  14. "github.com/pkg/errors"
  15. "one-api/constant"
  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 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. return fmt.Sprintf("%s%s", a.baseURL, path), nil
  104. }
  105. // BuildRequestHeader sets required headers.
  106. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  107. token, err := a.createJWTToken()
  108. if err != nil {
  109. return fmt.Errorf("failed to create JWT token: %w", err)
  110. }
  111. req.Header.Set("Content-Type", "application/json")
  112. req.Header.Set("Accept", "application/json")
  113. req.Header.Set("Authorization", "Bearer "+token)
  114. req.Header.Set("User-Agent", "kling-sdk/1.0")
  115. return nil
  116. }
  117. // BuildRequestBody converts request into Kling specific format.
  118. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  119. v, exists := c.Get("task_request")
  120. if !exists {
  121. return nil, fmt.Errorf("request not found in context")
  122. }
  123. req := v.(relaycommon.TaskSubmitReq)
  124. body, err := a.convertToRequestPayload(&req)
  125. if err != nil {
  126. return nil, err
  127. }
  128. if body.Image == "" && body.ImageTail == "" {
  129. c.Set("action", constant.TaskActionTextGenerate)
  130. }
  131. data, err := json.Marshal(body)
  132. if err != nil {
  133. return nil, err
  134. }
  135. return bytes.NewReader(data), nil
  136. }
  137. // DoRequest delegates to common helper.
  138. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  139. if action := c.GetString("action"); action != "" {
  140. info.Action = action
  141. }
  142. return channel.DoTaskApiRequest(a, c, info, requestBody)
  143. }
  144. // DoResponse handles upstream response, returns taskID etc.
  145. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  146. responseBody, err := io.ReadAll(resp.Body)
  147. if err != nil {
  148. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  149. return
  150. }
  151. var kResp responsePayload
  152. err = json.Unmarshal(responseBody, &kResp)
  153. if err != nil {
  154. taskErr = service.TaskErrorWrapper(err, "unmarshal_response_failed", http.StatusInternalServerError)
  155. return
  156. }
  157. if kResp.Code != 0 {
  158. taskErr = service.TaskErrorWrapperLocal(fmt.Errorf(kResp.Message), "task_failed", http.StatusBadRequest)
  159. return
  160. }
  161. kResp.TaskId = kResp.Data.TaskId
  162. c.JSON(http.StatusOK, kResp)
  163. return kResp.Data.TaskId, 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 == constant.TaskActionGenerate, "/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 *relaycommon.TaskSubmitReq) (*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. Model: req.Model, // Keep consistent with model_name, double writing improves compatibility
  208. CfgScale: 0.5,
  209. StaticMask: "",
  210. DynamicMasks: []DynamicMask{},
  211. CameraControl: nil,
  212. CallbackUrl: "",
  213. ExternalTaskId: "",
  214. }
  215. if r.ModelName == "" {
  216. r.ModelName = "kling-v1"
  217. }
  218. metadata := req.Metadata
  219. medaBytes, err := json.Marshal(metadata)
  220. if err != nil {
  221. return nil, errors.Wrap(err, "metadata marshal metadata failed")
  222. }
  223. err = json.Unmarshal(medaBytes, &r)
  224. if err != nil {
  225. return nil, errors.Wrap(err, "unmarshal metadata failed")
  226. }
  227. return &r, nil
  228. }
  229. func (a *TaskAdaptor) getAspectRatio(size string) string {
  230. switch size {
  231. case "1024x1024", "512x512":
  232. return "1:1"
  233. case "1280x720", "1920x1080":
  234. return "16:9"
  235. case "720x1280", "1080x1920":
  236. return "9:16"
  237. default:
  238. return "1:1"
  239. }
  240. }
  241. func defaultString(s, def string) string {
  242. if strings.TrimSpace(s) == "" {
  243. return def
  244. }
  245. return s
  246. }
  247. func defaultInt(v int, def int) int {
  248. if v == 0 {
  249. return def
  250. }
  251. return v
  252. }
  253. // ============================
  254. // JWT helpers
  255. // ============================
  256. func (a *TaskAdaptor) createJWTToken() (string, error) {
  257. return a.createJWTTokenWithKey(a.apiKey)
  258. }
  259. //func (a *TaskAdaptor) createJWTTokenWithKey(apiKey string) (string, error) {
  260. // parts := strings.Split(apiKey, "|")
  261. // if len(parts) != 2 {
  262. // return "", fmt.Errorf("invalid API key format, expected 'access_key,secret_key'")
  263. // }
  264. // return a.createJWTTokenWithKey(strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]))
  265. //}
  266. func (a *TaskAdaptor) createJWTTokenWithKey(apiKey string) (string, error) {
  267. keyParts := strings.Split(apiKey, "|")
  268. accessKey := strings.TrimSpace(keyParts[0])
  269. if len(keyParts) == 1 {
  270. return accessKey, nil
  271. }
  272. secretKey := strings.TrimSpace(keyParts[1])
  273. now := time.Now().Unix()
  274. claims := jwt.MapClaims{
  275. "iss": accessKey,
  276. "exp": now + 1800, // 30 minutes
  277. "nbf": now - 5,
  278. }
  279. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  280. token.Header["typ"] = "JWT"
  281. return token.SignedString([]byte(secretKey))
  282. }
  283. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  284. taskInfo := &relaycommon.TaskInfo{}
  285. resPayload := responsePayload{}
  286. err := json.Unmarshal(respBody, &resPayload)
  287. if err != nil {
  288. return nil, errors.Wrap(err, "failed to unmarshal response body")
  289. }
  290. taskInfo.Code = resPayload.Code
  291. taskInfo.TaskID = resPayload.Data.TaskId
  292. taskInfo.Reason = resPayload.Message
  293. //任务状态,枚举值:submitted(已提交)、processing(处理中)、succeed(成功)、failed(失败)
  294. status := resPayload.Data.TaskStatus
  295. switch status {
  296. case "submitted":
  297. taskInfo.Status = model.TaskStatusSubmitted
  298. case "processing":
  299. taskInfo.Status = model.TaskStatusInProgress
  300. case "succeed":
  301. taskInfo.Status = model.TaskStatusSuccess
  302. case "failed":
  303. taskInfo.Status = model.TaskStatusFailure
  304. default:
  305. return nil, fmt.Errorf("unknown task status: %s", status)
  306. }
  307. if videos := resPayload.Data.TaskResult.Videos; len(videos) > 0 {
  308. video := videos[0]
  309. taskInfo.Url = video.Url
  310. }
  311. return taskInfo, nil
  312. }