adaptor.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. package sora
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "mime/multipart"
  7. "net/http"
  8. "net/textproto"
  9. "strconv"
  10. "strings"
  11. "github.com/QuantumNous/new-api/common"
  12. "github.com/QuantumNous/new-api/constant"
  13. "github.com/QuantumNous/new-api/dto"
  14. "github.com/QuantumNous/new-api/model"
  15. "github.com/QuantumNous/new-api/relay/channel"
  16. taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
  17. relaycommon "github.com/QuantumNous/new-api/relay/common"
  18. "github.com/QuantumNous/new-api/service"
  19. "github.com/gin-gonic/gin"
  20. "github.com/pkg/errors"
  21. "github.com/tidwall/sjson"
  22. )
  23. // ============================
  24. // Request / Response structures
  25. // ============================
  26. type ContentItem struct {
  27. Type string `json:"type"` // "text" or "image_url"
  28. Text string `json:"text,omitempty"` // for text type
  29. ImageURL *ImageURL `json:"image_url,omitempty"` // for image_url type
  30. }
  31. type ImageURL struct {
  32. URL string `json:"url"`
  33. }
  34. type responseTask struct {
  35. ID string `json:"id"`
  36. TaskID string `json:"task_id,omitempty"` //兼容旧接口
  37. Object string `json:"object"`
  38. Model string `json:"model"`
  39. Status string `json:"status"`
  40. Progress int `json:"progress"`
  41. CreatedAt int64 `json:"created_at"`
  42. CompletedAt int64 `json:"completed_at,omitempty"`
  43. ExpiresAt int64 `json:"expires_at,omitempty"`
  44. Seconds string `json:"seconds,omitempty"`
  45. Size string `json:"size,omitempty"`
  46. RemixedFromVideoID string `json:"remixed_from_video_id,omitempty"`
  47. Error *struct {
  48. Message string `json:"message"`
  49. Code string `json:"code"`
  50. } `json:"error,omitempty"`
  51. }
  52. // ============================
  53. // Adaptor implementation
  54. // ============================
  55. type TaskAdaptor struct {
  56. taskcommon.BaseBilling
  57. ChannelType int
  58. apiKey string
  59. baseURL string
  60. }
  61. func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
  62. a.ChannelType = info.ChannelType
  63. a.baseURL = info.ChannelBaseUrl
  64. a.apiKey = info.ApiKey
  65. }
  66. func validateRemixRequest(c *gin.Context) *dto.TaskError {
  67. var req relaycommon.TaskSubmitReq
  68. if err := common.UnmarshalBodyReusable(c, &req); err != nil {
  69. return service.TaskErrorWrapperLocal(err, "invalid_request", http.StatusBadRequest)
  70. }
  71. if strings.TrimSpace(req.Prompt) == "" {
  72. return service.TaskErrorWrapperLocal(fmt.Errorf("field prompt is required"), "invalid_request", http.StatusBadRequest)
  73. }
  74. // 存储原始请求到 context,与 ValidateMultipartDirect 路径保持一致
  75. c.Set("task_request", req)
  76. return nil
  77. }
  78. func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
  79. if info.Action == constant.TaskActionRemix {
  80. return validateRemixRequest(c)
  81. }
  82. return relaycommon.ValidateMultipartDirect(c, info)
  83. }
  84. // EstimateBilling 根据用户请求的 seconds 和 size 计算 OtherRatios。
  85. func (a *TaskAdaptor) EstimateBilling(c *gin.Context, info *relaycommon.RelayInfo) map[string]float64 {
  86. // remix 路径的 OtherRatios 已在 ResolveOriginTask 中设置
  87. if info.Action == constant.TaskActionRemix {
  88. return nil
  89. }
  90. req, err := relaycommon.GetTaskRequest(c)
  91. if err != nil {
  92. return nil
  93. }
  94. seconds, _ := strconv.Atoi(req.Seconds)
  95. if seconds == 0 {
  96. seconds = req.Duration
  97. }
  98. if seconds <= 0 {
  99. seconds = 4
  100. }
  101. size := req.Size
  102. if size == "" {
  103. size = "720x1280"
  104. }
  105. ratios := map[string]float64{
  106. "seconds": float64(seconds),
  107. "size": 1,
  108. }
  109. if size == "1792x1024" || size == "1024x1792" {
  110. ratios["size"] = 1.666667
  111. }
  112. return ratios
  113. }
  114. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
  115. if info.Action == constant.TaskActionRemix {
  116. return fmt.Sprintf("%s/v1/videos/%s/remix", a.baseURL, info.OriginTaskID), nil
  117. }
  118. return fmt.Sprintf("%s/v1/videos", a.baseURL), nil
  119. }
  120. // BuildRequestHeader sets required headers.
  121. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  122. req.Header.Set("Authorization", "Bearer "+a.apiKey)
  123. req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  124. return nil
  125. }
  126. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  127. storage, err := common.GetBodyStorage(c)
  128. if err != nil {
  129. return nil, errors.Wrap(err, "get_request_body_failed")
  130. }
  131. cachedBody, err := storage.Bytes()
  132. if err != nil {
  133. return nil, errors.Wrap(err, "read_body_bytes_failed")
  134. }
  135. contentType := c.GetHeader("Content-Type")
  136. if strings.HasPrefix(contentType, "application/json") {
  137. var bodyMap map[string]interface{}
  138. if err := common.Unmarshal(cachedBody, &bodyMap); err == nil {
  139. bodyMap["model"] = info.UpstreamModelName
  140. if newBody, err := common.Marshal(bodyMap); err == nil {
  141. return bytes.NewReader(newBody), nil
  142. }
  143. }
  144. return bytes.NewReader(cachedBody), nil
  145. }
  146. if strings.Contains(contentType, "multipart/form-data") {
  147. formData, err := common.ParseMultipartFormReusable(c)
  148. if err != nil {
  149. return bytes.NewReader(cachedBody), nil
  150. }
  151. var buf bytes.Buffer
  152. writer := multipart.NewWriter(&buf)
  153. writer.WriteField("model", info.UpstreamModelName)
  154. for key, values := range formData.Value {
  155. if key == "model" {
  156. continue
  157. }
  158. for _, v := range values {
  159. writer.WriteField(key, v)
  160. }
  161. }
  162. for fieldName, fileHeaders := range formData.File {
  163. for _, fh := range fileHeaders {
  164. f, err := fh.Open()
  165. if err != nil {
  166. continue
  167. }
  168. ct := fh.Header.Get("Content-Type")
  169. if ct == "" || ct == "application/octet-stream" {
  170. buf512 := make([]byte, 512)
  171. n, _ := io.ReadFull(f, buf512)
  172. ct = http.DetectContentType(buf512[:n])
  173. // Re-open after sniffing so the full content is copied below
  174. f.Close()
  175. f, err = fh.Open()
  176. if err != nil {
  177. continue
  178. }
  179. }
  180. h := make(textproto.MIMEHeader)
  181. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fieldName, fh.Filename))
  182. h.Set("Content-Type", ct)
  183. part, err := writer.CreatePart(h)
  184. if err != nil {
  185. f.Close()
  186. continue
  187. }
  188. io.Copy(part, f)
  189. f.Close()
  190. }
  191. }
  192. writer.Close()
  193. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  194. return &buf, nil
  195. }
  196. return common.ReaderOnly(storage), nil
  197. }
  198. // DoRequest delegates to common helper.
  199. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  200. return channel.DoTaskApiRequest(a, c, info, requestBody)
  201. }
  202. // DoResponse handles upstream response, returns taskID etc.
  203. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  204. responseBody, err := io.ReadAll(resp.Body)
  205. if err != nil {
  206. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  207. return
  208. }
  209. _ = resp.Body.Close()
  210. // Parse Sora response
  211. var dResp responseTask
  212. if err := common.Unmarshal(responseBody, &dResp); err != nil {
  213. taskErr = service.TaskErrorWrapper(errors.Wrapf(err, "body: %s", responseBody), "unmarshal_response_body_failed", http.StatusInternalServerError)
  214. return
  215. }
  216. upstreamID := dResp.ID
  217. if upstreamID == "" {
  218. upstreamID = dResp.TaskID
  219. }
  220. if upstreamID == "" {
  221. taskErr = service.TaskErrorWrapper(fmt.Errorf("task_id is empty"), "invalid_response", http.StatusInternalServerError)
  222. return
  223. }
  224. // 使用公开 task_xxxx ID 返回给客户端
  225. dResp.ID = info.PublicTaskID
  226. dResp.TaskID = info.PublicTaskID
  227. c.JSON(http.StatusOK, dResp)
  228. return upstreamID, responseBody, nil
  229. }
  230. // FetchTask fetch task status
  231. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  232. taskID, ok := body["task_id"].(string)
  233. if !ok {
  234. return nil, fmt.Errorf("invalid task_id")
  235. }
  236. uri := fmt.Sprintf("%s/v1/videos/%s", baseUrl, taskID)
  237. req, err := http.NewRequest(http.MethodGet, uri, nil)
  238. if err != nil {
  239. return nil, err
  240. }
  241. req.Header.Set("Authorization", "Bearer "+key)
  242. client, err := service.GetHttpClientWithProxy(proxy)
  243. if err != nil {
  244. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  245. }
  246. return client.Do(req)
  247. }
  248. func (a *TaskAdaptor) GetModelList() []string {
  249. return ModelList
  250. }
  251. func (a *TaskAdaptor) GetChannelName() string {
  252. return ChannelName
  253. }
  254. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  255. resTask := responseTask{}
  256. if err := common.Unmarshal(respBody, &resTask); err != nil {
  257. return nil, errors.Wrap(err, "unmarshal task result failed")
  258. }
  259. taskResult := relaycommon.TaskInfo{
  260. Code: 0,
  261. }
  262. switch resTask.Status {
  263. case "queued", "pending":
  264. taskResult.Status = model.TaskStatusQueued
  265. case "processing", "in_progress":
  266. taskResult.Status = model.TaskStatusInProgress
  267. case "completed":
  268. taskResult.Status = model.TaskStatusSuccess
  269. // Url intentionally left empty — the caller constructs the proxy URL using the public task ID
  270. case "failed", "cancelled":
  271. taskResult.Status = model.TaskStatusFailure
  272. if resTask.Error != nil {
  273. taskResult.Reason = resTask.Error.Message
  274. } else {
  275. taskResult.Reason = "task failed"
  276. }
  277. default:
  278. }
  279. if resTask.Progress > 0 && resTask.Progress < 100 {
  280. taskResult.Progress = fmt.Sprintf("%d%%", resTask.Progress)
  281. }
  282. return &taskResult, nil
  283. }
  284. func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
  285. data := task.Data
  286. var err error
  287. if data, err = sjson.SetBytes(data, "id", task.TaskID); err != nil {
  288. return nil, errors.Wrap(err, "set id failed")
  289. }
  290. return data, nil
  291. }