adaptor.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. package suno
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strings"
  9. "time"
  10. "github.com/QuantumNous/new-api/common"
  11. "github.com/QuantumNous/new-api/constant"
  12. "github.com/QuantumNous/new-api/dto"
  13. "github.com/QuantumNous/new-api/relay/channel"
  14. taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
  15. relaycommon "github.com/QuantumNous/new-api/relay/common"
  16. "github.com/QuantumNous/new-api/service"
  17. "github.com/gin-gonic/gin"
  18. )
  19. type TaskAdaptor struct {
  20. taskcommon.BaseBilling
  21. ChannelType int
  22. }
  23. // ParseTaskResult is not used for Suno tasks.
  24. // Suno polling uses a dedicated batch-fetch path (service.UpdateSunoTasks) that
  25. // receives dto.TaskResponse[[]dto.SunoDataResponse] from the upstream /fetch API.
  26. // This differs from the per-task polling used by video adaptors.
  27. func (a *TaskAdaptor) ParseTaskResult([]byte) (*relaycommon.TaskInfo, error) {
  28. return nil, fmt.Errorf("suno uses batch polling via UpdateSunoTasks, ParseTaskResult is not applicable")
  29. }
  30. func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
  31. a.ChannelType = info.ChannelType
  32. }
  33. func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
  34. action := strings.ToUpper(c.Param("action"))
  35. var sunoRequest *dto.SunoSubmitReq
  36. err := common.UnmarshalBodyReusable(c, &sunoRequest)
  37. if err != nil {
  38. taskErr = service.TaskErrorWrapperLocal(err, "invalid_request", http.StatusBadRequest)
  39. return
  40. }
  41. err = actionValidate(c, sunoRequest, action)
  42. if err != nil {
  43. taskErr = service.TaskErrorWrapperLocal(err, "invalid_request", http.StatusBadRequest)
  44. return
  45. }
  46. if sunoRequest.ContinueClipId != "" {
  47. if sunoRequest.TaskID == "" {
  48. taskErr = service.TaskErrorWrapperLocal(fmt.Errorf("task id is empty"), "invalid_request", http.StatusBadRequest)
  49. return
  50. }
  51. info.OriginTaskID = sunoRequest.TaskID
  52. }
  53. info.Action = action
  54. c.Set("task_request", sunoRequest)
  55. return nil
  56. }
  57. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
  58. baseURL := info.ChannelBaseUrl
  59. fullRequestURL := fmt.Sprintf("%s%s", baseURL, "/suno/submit/"+info.Action)
  60. return fullRequestURL, nil
  61. }
  62. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  63. req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  64. req.Header.Set("Accept", c.Request.Header.Get("Accept"))
  65. req.Header.Set("Authorization", "Bearer "+info.ApiKey)
  66. return nil
  67. }
  68. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  69. sunoRequest, ok := c.Get("task_request")
  70. if !ok {
  71. return nil, fmt.Errorf("task_request not found in context")
  72. }
  73. data, err := common.Marshal(sunoRequest)
  74. if err != nil {
  75. return nil, err
  76. }
  77. return bytes.NewReader(data), nil
  78. }
  79. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  80. return channel.DoTaskApiRequest(a, c, info, requestBody)
  81. }
  82. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  83. responseBody, err := io.ReadAll(resp.Body)
  84. if err != nil {
  85. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  86. return
  87. }
  88. var sunoResponse dto.TaskResponse[string]
  89. err = common.Unmarshal(responseBody, &sunoResponse)
  90. if err != nil {
  91. taskErr = service.TaskErrorWrapper(err, "unmarshal_response_body_failed", http.StatusInternalServerError)
  92. return
  93. }
  94. if !sunoResponse.IsSuccess() {
  95. taskErr = service.TaskErrorWrapper(fmt.Errorf("%s", sunoResponse.Message), sunoResponse.Code, http.StatusInternalServerError)
  96. return
  97. }
  98. // 使用公开 task_xxxx ID 替换上游 ID 返回给客户端
  99. publicResponse := dto.TaskResponse[string]{
  100. Code: sunoResponse.Code,
  101. Message: sunoResponse.Message,
  102. Data: info.PublicTaskID,
  103. }
  104. c.JSON(http.StatusOK, publicResponse)
  105. return sunoResponse.Data, nil, nil
  106. }
  107. func (a *TaskAdaptor) GetModelList() []string {
  108. return ModelList
  109. }
  110. func (a *TaskAdaptor) GetChannelName() string {
  111. return ChannelName
  112. }
  113. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  114. requestUrl := fmt.Sprintf("%s/suno/fetch", baseUrl)
  115. byteBody, err := common.Marshal(body)
  116. if err != nil {
  117. return nil, err
  118. }
  119. req, err := http.NewRequest("POST", requestUrl, bytes.NewBuffer(byteBody))
  120. if err != nil {
  121. common.SysLog(fmt.Sprintf("Get Task error: %v", err))
  122. return nil, err
  123. }
  124. defer req.Body.Close()
  125. // 设置超时时间
  126. timeout := time.Second * 15
  127. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  128. defer cancel()
  129. // 使用带有超时的 context 创建新的请求
  130. req = req.WithContext(ctx)
  131. req.Header.Set("Content-Type", "application/json")
  132. req.Header.Set("Authorization", "Bearer "+key)
  133. client, err := service.GetHttpClientWithProxy(proxy)
  134. if err != nil {
  135. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  136. }
  137. return client.Do(req)
  138. }
  139. func actionValidate(c *gin.Context, sunoRequest *dto.SunoSubmitReq, action string) (err error) {
  140. switch action {
  141. case constant.SunoActionMusic:
  142. if sunoRequest.Mv == "" {
  143. sunoRequest.Mv = "chirp-v3-0"
  144. }
  145. case constant.SunoActionLyrics:
  146. if sunoRequest.Prompt == "" {
  147. err = fmt.Errorf("prompt_empty")
  148. return
  149. }
  150. default:
  151. err = fmt.Errorf("invalid_action")
  152. }
  153. return
  154. }