adaptor.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. package suno
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "net/http"
  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/relay/channel"
  12. taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
  13. relaycommon "github.com/QuantumNous/new-api/relay/common"
  14. "github.com/QuantumNous/new-api/service"
  15. "github.com/gin-gonic/gin"
  16. )
  17. type TaskAdaptor struct {
  18. taskcommon.BaseBilling
  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. return nil, fmt.Errorf("task_request not found in context")
  70. }
  71. data, err := common.Marshal(sunoRequest)
  72. if err != nil {
  73. return nil, err
  74. }
  75. return bytes.NewReader(data), nil
  76. }
  77. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  78. return channel.DoTaskApiRequest(a, c, info, requestBody)
  79. }
  80. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  81. responseBody, err := io.ReadAll(resp.Body)
  82. if err != nil {
  83. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  84. return
  85. }
  86. var sunoResponse dto.TaskResponse[string]
  87. err = common.Unmarshal(responseBody, &sunoResponse)
  88. if err != nil {
  89. taskErr = service.TaskErrorWrapper(err, "unmarshal_response_body_failed", http.StatusInternalServerError)
  90. return
  91. }
  92. if !sunoResponse.IsSuccess() {
  93. taskErr = service.TaskErrorWrapper(fmt.Errorf("%s", sunoResponse.Message), sunoResponse.Code, http.StatusInternalServerError)
  94. return
  95. }
  96. // 使用公开 task_xxxx ID 替换上游 ID 返回给客户端
  97. publicResponse := dto.TaskResponse[string]{
  98. Code: sunoResponse.Code,
  99. Message: sunoResponse.Message,
  100. Data: info.PublicTaskID,
  101. }
  102. c.JSON(http.StatusOK, publicResponse)
  103. return sunoResponse.Data, nil, nil
  104. }
  105. func (a *TaskAdaptor) GetModelList() []string {
  106. return ModelList
  107. }
  108. func (a *TaskAdaptor) GetChannelName() string {
  109. return ChannelName
  110. }
  111. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  112. requestUrl := fmt.Sprintf("%s/suno/fetch", baseUrl)
  113. byteBody, err := common.Marshal(body)
  114. if err != nil {
  115. return nil, err
  116. }
  117. req, err := http.NewRequest("POST", requestUrl, bytes.NewBuffer(byteBody))
  118. if err != nil {
  119. common.SysLog(fmt.Sprintf("Get Task error: %v", err))
  120. return nil, err
  121. }
  122. req.Header.Set("Content-Type", "application/json")
  123. req.Header.Set("Authorization", "Bearer "+key)
  124. client, err := service.GetHttpClientWithProxy(proxy)
  125. if err != nil {
  126. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  127. }
  128. return client.Do(req)
  129. }
  130. func actionValidate(c *gin.Context, sunoRequest *dto.SunoSubmitReq, action string) (err error) {
  131. switch action {
  132. case constant.SunoActionMusic:
  133. if sunoRequest.Mv == "" {
  134. sunoRequest.Mv = "chirp-v3-0"
  135. }
  136. case constant.SunoActionLyrics:
  137. if sunoRequest.Prompt == "" {
  138. err = fmt.Errorf("prompt_empty")
  139. return
  140. }
  141. default:
  142. err = fmt.Errorf("invalid_action")
  143. }
  144. return
  145. }