adaptor.go 5.3 KB

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