adaptor.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package sora
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "github.com/QuantumNous/new-api/common"
  9. "github.com/QuantumNous/new-api/constant"
  10. "github.com/QuantumNous/new-api/dto"
  11. "github.com/QuantumNous/new-api/model"
  12. "github.com/QuantumNous/new-api/relay/channel"
  13. taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
  14. relaycommon "github.com/QuantumNous/new-api/relay/common"
  15. "github.com/QuantumNous/new-api/service"
  16. "github.com/gin-gonic/gin"
  17. "github.com/pkg/errors"
  18. )
  19. // ============================
  20. // Request / Response structures
  21. // ============================
  22. type ContentItem struct {
  23. Type string `json:"type"` // "text" or "image_url"
  24. Text string `json:"text,omitempty"` // for text type
  25. ImageURL *ImageURL `json:"image_url,omitempty"` // for image_url type
  26. }
  27. type ImageURL struct {
  28. URL string `json:"url"`
  29. }
  30. type responseTask struct {
  31. ID string `json:"id"`
  32. TaskID string `json:"task_id,omitempty"` //兼容旧接口
  33. Object string `json:"object"`
  34. Model string `json:"model"`
  35. Status string `json:"status"`
  36. Progress int `json:"progress"`
  37. CreatedAt int64 `json:"created_at"`
  38. CompletedAt int64 `json:"completed_at,omitempty"`
  39. ExpiresAt int64 `json:"expires_at,omitempty"`
  40. Seconds string `json:"seconds,omitempty"`
  41. Size string `json:"size,omitempty"`
  42. RemixedFromVideoID string `json:"remixed_from_video_id,omitempty"`
  43. Error *struct {
  44. Message string `json:"message"`
  45. Code string `json:"code"`
  46. } `json:"error,omitempty"`
  47. }
  48. // ============================
  49. // Adaptor implementation
  50. // ============================
  51. type TaskAdaptor struct {
  52. taskcommon.BaseBilling
  53. ChannelType int
  54. apiKey string
  55. baseURL string
  56. }
  57. func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
  58. a.ChannelType = info.ChannelType
  59. a.baseURL = info.ChannelBaseUrl
  60. a.apiKey = info.ApiKey
  61. }
  62. func validateRemixRequest(c *gin.Context) *dto.TaskError {
  63. var req relaycommon.TaskSubmitReq
  64. if err := common.UnmarshalBodyReusable(c, &req); err != nil {
  65. return service.TaskErrorWrapperLocal(err, "invalid_request", http.StatusBadRequest)
  66. }
  67. if strings.TrimSpace(req.Prompt) == "" {
  68. return service.TaskErrorWrapperLocal(fmt.Errorf("field prompt is required"), "invalid_request", http.StatusBadRequest)
  69. }
  70. // 存储原始请求到 context,与 ValidateMultipartDirect 路径保持一致
  71. c.Set("task_request", req)
  72. return nil
  73. }
  74. func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
  75. if info.Action == constant.TaskActionRemix {
  76. return validateRemixRequest(c)
  77. }
  78. return relaycommon.ValidateMultipartDirect(c, info)
  79. }
  80. // EstimateBilling 根据用户请求的 seconds 和 size 计算 OtherRatios。
  81. func (a *TaskAdaptor) EstimateBilling(c *gin.Context, info *relaycommon.RelayInfo) map[string]float64 {
  82. // remix 路径的 OtherRatios 已在 ResolveOriginTask 中设置
  83. if info.Action == constant.TaskActionRemix {
  84. return nil
  85. }
  86. req, err := relaycommon.GetTaskRequest(c)
  87. if err != nil {
  88. return nil
  89. }
  90. seconds, _ := strconv.Atoi(req.Seconds)
  91. if seconds == 0 {
  92. seconds = req.Duration
  93. }
  94. if seconds <= 0 {
  95. seconds = 4
  96. }
  97. size := req.Size
  98. if size == "" {
  99. size = "720x1280"
  100. }
  101. ratios := map[string]float64{
  102. "seconds": float64(seconds),
  103. "size": 1,
  104. }
  105. if size == "1792x1024" || size == "1024x1792" {
  106. ratios["size"] = 1.666667
  107. }
  108. return ratios
  109. }
  110. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
  111. if info.Action == constant.TaskActionRemix {
  112. return fmt.Sprintf("%s/v1/videos/%s/remix", a.baseURL, info.OriginTaskID), nil
  113. }
  114. return fmt.Sprintf("%s/v1/videos", a.baseURL), nil
  115. }
  116. // BuildRequestHeader sets required headers.
  117. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  118. req.Header.Set("Authorization", "Bearer "+a.apiKey)
  119. req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  120. return nil
  121. }
  122. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  123. storage, err := common.GetBodyStorage(c)
  124. if err != nil {
  125. return nil, errors.Wrap(err, "get_request_body_failed")
  126. }
  127. return common.ReaderOnly(storage), nil
  128. }
  129. // DoRequest delegates to common helper.
  130. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  131. return channel.DoTaskApiRequest(a, c, info, requestBody)
  132. }
  133. // DoResponse handles upstream response, returns taskID etc.
  134. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  135. responseBody, err := io.ReadAll(resp.Body)
  136. if err != nil {
  137. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  138. return
  139. }
  140. _ = resp.Body.Close()
  141. // Parse Sora response
  142. var dResp responseTask
  143. if err := common.Unmarshal(responseBody, &dResp); err != nil {
  144. taskErr = service.TaskErrorWrapper(errors.Wrapf(err, "body: %s", responseBody), "unmarshal_response_body_failed", http.StatusInternalServerError)
  145. return
  146. }
  147. upstreamID := dResp.ID
  148. if upstreamID == "" {
  149. upstreamID = dResp.TaskID
  150. }
  151. if upstreamID == "" {
  152. taskErr = service.TaskErrorWrapper(fmt.Errorf("task_id is empty"), "invalid_response", http.StatusInternalServerError)
  153. return
  154. }
  155. // 使用公开 task_xxxx ID 返回给客户端
  156. dResp.ID = info.PublicTaskID
  157. dResp.TaskID = info.PublicTaskID
  158. c.JSON(http.StatusOK, dResp)
  159. return upstreamID, responseBody, nil
  160. }
  161. // FetchTask fetch task status
  162. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  163. taskID, ok := body["task_id"].(string)
  164. if !ok {
  165. return nil, fmt.Errorf("invalid task_id")
  166. }
  167. uri := fmt.Sprintf("%s/v1/videos/%s", baseUrl, taskID)
  168. req, err := http.NewRequest(http.MethodGet, uri, nil)
  169. if err != nil {
  170. return nil, err
  171. }
  172. req.Header.Set("Authorization", "Bearer "+key)
  173. client, err := service.GetHttpClientWithProxy(proxy)
  174. if err != nil {
  175. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  176. }
  177. return client.Do(req)
  178. }
  179. func (a *TaskAdaptor) GetModelList() []string {
  180. return ModelList
  181. }
  182. func (a *TaskAdaptor) GetChannelName() string {
  183. return ChannelName
  184. }
  185. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  186. resTask := responseTask{}
  187. if err := common.Unmarshal(respBody, &resTask); err != nil {
  188. return nil, errors.Wrap(err, "unmarshal task result failed")
  189. }
  190. taskResult := relaycommon.TaskInfo{
  191. Code: 0,
  192. }
  193. switch resTask.Status {
  194. case "queued", "pending":
  195. taskResult.Status = model.TaskStatusQueued
  196. case "processing", "in_progress":
  197. taskResult.Status = model.TaskStatusInProgress
  198. case "completed":
  199. taskResult.Status = model.TaskStatusSuccess
  200. // Url intentionally left empty — the caller constructs the proxy URL using the public task ID
  201. case "failed", "cancelled":
  202. taskResult.Status = model.TaskStatusFailure
  203. if resTask.Error != nil {
  204. taskResult.Reason = resTask.Error.Message
  205. } else {
  206. taskResult.Reason = "task failed"
  207. }
  208. default:
  209. }
  210. if resTask.Progress > 0 && resTask.Progress < 100 {
  211. taskResult.Progress = fmt.Sprintf("%d%%", resTask.Progress)
  212. }
  213. return &taskResult, nil
  214. }
  215. func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
  216. return task.Data, nil
  217. }