adaptor.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. 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. kResp.TaskId = kResp.Data.TaskId
  165. c.JSON(http.StatusOK, kResp)
  166. return kResp.Data.TaskId, responseBody, nil
  167. }
  168. // FetchTask fetch task status
  169. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any) (*http.Response, error) {
  170. taskID, ok := body["task_id"].(string)
  171. if !ok {
  172. return nil, fmt.Errorf("invalid task_id")
  173. }
  174. action, ok := body["action"].(string)
  175. if !ok {
  176. return nil, fmt.Errorf("invalid action")
  177. }
  178. path := lo.Ternary(action == constant.TaskActionGenerate, "/v1/videos/image2video", "/v1/videos/text2video")
  179. url := fmt.Sprintf("%s%s/%s", baseUrl, path, taskID)
  180. if isNewAPIRelay(key) {
  181. url = fmt.Sprintf("%s/kling%s/%s", baseUrl, path, taskID)
  182. }
  183. req, err := http.NewRequest(http.MethodGet, url, nil)
  184. if err != nil {
  185. return nil, err
  186. }
  187. token, err := a.createJWTTokenWithKey(key)
  188. if err != nil {
  189. token = key
  190. }
  191. req.Header.Set("Accept", "application/json")
  192. req.Header.Set("Authorization", "Bearer "+token)
  193. req.Header.Set("User-Agent", "kling-sdk/1.0")
  194. return service.GetHttpClient().Do(req)
  195. }
  196. func (a *TaskAdaptor) GetModelList() []string {
  197. return []string{"kling-v1", "kling-v1-6", "kling-v2-master"}
  198. }
  199. func (a *TaskAdaptor) GetChannelName() string {
  200. return "kling"
  201. }
  202. // ============================
  203. // helpers
  204. // ============================
  205. func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*requestPayload, error) {
  206. r := requestPayload{
  207. Prompt: req.Prompt,
  208. Image: req.Image,
  209. Mode: defaultString(req.Mode, "std"),
  210. Duration: fmt.Sprintf("%d", defaultInt(req.Duration, 5)),
  211. AspectRatio: a.getAspectRatio(req.Size),
  212. ModelName: req.Model,
  213. Model: req.Model, // Keep consistent with model_name, double writing improves compatibility
  214. CfgScale: 0.5,
  215. StaticMask: "",
  216. DynamicMasks: []DynamicMask{},
  217. CameraControl: nil,
  218. CallbackUrl: "",
  219. ExternalTaskId: "",
  220. }
  221. if r.ModelName == "" {
  222. r.ModelName = "kling-v1"
  223. }
  224. metadata := req.Metadata
  225. medaBytes, err := json.Marshal(metadata)
  226. if err != nil {
  227. return nil, errors.Wrap(err, "metadata marshal metadata failed")
  228. }
  229. err = json.Unmarshal(medaBytes, &r)
  230. if err != nil {
  231. return nil, errors.Wrap(err, "unmarshal metadata failed")
  232. }
  233. return &r, nil
  234. }
  235. func (a *TaskAdaptor) getAspectRatio(size string) string {
  236. switch size {
  237. case "1024x1024", "512x512":
  238. return "1:1"
  239. case "1280x720", "1920x1080":
  240. return "16:9"
  241. case "720x1280", "1080x1920":
  242. return "9:16"
  243. default:
  244. return "1:1"
  245. }
  246. }
  247. func defaultString(s, def string) string {
  248. if strings.TrimSpace(s) == "" {
  249. return def
  250. }
  251. return s
  252. }
  253. func defaultInt(v int, def int) int {
  254. if v == 0 {
  255. return def
  256. }
  257. return v
  258. }
  259. // ============================
  260. // JWT helpers
  261. // ============================
  262. func (a *TaskAdaptor) createJWTToken() (string, error) {
  263. return a.createJWTTokenWithKey(a.apiKey)
  264. }
  265. //func (a *TaskAdaptor) createJWTTokenWithKey(apiKey string) (string, error) {
  266. // parts := strings.Split(apiKey, "|")
  267. // if len(parts) != 2 {
  268. // return "", fmt.Errorf("invalid API key format, expected 'access_key,secret_key'")
  269. // }
  270. // return a.createJWTTokenWithKey(strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]))
  271. //}
  272. func (a *TaskAdaptor) createJWTTokenWithKey(apiKey string) (string, error) {
  273. if isNewAPIRelay(apiKey) {
  274. return apiKey, nil // new api relay
  275. }
  276. keyParts := strings.Split(apiKey, "|")
  277. if len(keyParts) != 2 {
  278. return "", errors.New("invalid api_key, required format is accessKey|secretKey")
  279. }
  280. accessKey := strings.TrimSpace(keyParts[0])
  281. if len(keyParts) == 1 {
  282. return accessKey, nil
  283. }
  284. secretKey := strings.TrimSpace(keyParts[1])
  285. now := time.Now().Unix()
  286. claims := jwt.MapClaims{
  287. "iss": accessKey,
  288. "exp": now + 1800, // 30 minutes
  289. "nbf": now - 5,
  290. }
  291. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  292. token.Header["typ"] = "JWT"
  293. return token.SignedString([]byte(secretKey))
  294. }
  295. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  296. taskInfo := &relaycommon.TaskInfo{}
  297. resPayload := responsePayload{}
  298. err := json.Unmarshal(respBody, &resPayload)
  299. if err != nil {
  300. return nil, errors.Wrap(err, "failed to unmarshal response body")
  301. }
  302. taskInfo.Code = resPayload.Code
  303. taskInfo.TaskID = resPayload.Data.TaskId
  304. taskInfo.Reason = resPayload.Message
  305. //任务状态,枚举值:submitted(已提交)、processing(处理中)、succeed(成功)、failed(失败)
  306. status := resPayload.Data.TaskStatus
  307. switch status {
  308. case "submitted":
  309. taskInfo.Status = model.TaskStatusSubmitted
  310. case "processing":
  311. taskInfo.Status = model.TaskStatusInProgress
  312. case "succeed":
  313. taskInfo.Status = model.TaskStatusSuccess
  314. case "failed":
  315. taskInfo.Status = model.TaskStatusFailure
  316. default:
  317. return nil, fmt.Errorf("unknown task status: %s", status)
  318. }
  319. if videos := resPayload.Data.TaskResult.Videos; len(videos) > 0 {
  320. video := videos[0]
  321. taskInfo.Url = video.Url
  322. }
  323. return taskInfo, nil
  324. }
  325. func isNewAPIRelay(apiKey string) bool {
  326. return strings.HasPrefix(apiKey, "sk-")
  327. }