midjourney.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package controller
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "time"
  10. "github.com/QuantumNous/new-api/common"
  11. "github.com/QuantumNous/new-api/dto"
  12. "github.com/QuantumNous/new-api/logger"
  13. "github.com/QuantumNous/new-api/model"
  14. "github.com/QuantumNous/new-api/service"
  15. "github.com/QuantumNous/new-api/setting"
  16. "github.com/QuantumNous/new-api/setting/system_setting"
  17. "github.com/gin-gonic/gin"
  18. )
  19. func UpdateMidjourneyTaskBulk() {
  20. //imageModel := "midjourney"
  21. ctx := context.TODO()
  22. for {
  23. time.Sleep(time.Duration(15) * time.Second)
  24. tasks := model.GetAllUnFinishTasks()
  25. if len(tasks) == 0 {
  26. continue
  27. }
  28. logger.LogInfo(ctx, fmt.Sprintf("检测到未完成的任务数有: %v", len(tasks)))
  29. taskChannelM := make(map[int][]string)
  30. taskM := make(map[string]*model.Midjourney)
  31. nullTaskIds := make([]int, 0)
  32. for _, task := range tasks {
  33. if task.MjId == "" {
  34. // 统计失败的未完成任务
  35. nullTaskIds = append(nullTaskIds, task.Id)
  36. continue
  37. }
  38. taskM[task.MjId] = task
  39. taskChannelM[task.ChannelId] = append(taskChannelM[task.ChannelId], task.MjId)
  40. }
  41. if len(nullTaskIds) > 0 {
  42. err := model.MjBulkUpdateByTaskIds(nullTaskIds, map[string]any{
  43. "status": "FAILURE",
  44. "progress": "100%",
  45. })
  46. if err != nil {
  47. logger.LogError(ctx, fmt.Sprintf("Fix null mj_id task error: %v", err))
  48. } else {
  49. logger.LogInfo(ctx, fmt.Sprintf("Fix null mj_id task success: %v", nullTaskIds))
  50. }
  51. }
  52. if len(taskChannelM) == 0 {
  53. continue
  54. }
  55. for channelId, taskIds := range taskChannelM {
  56. logger.LogInfo(ctx, fmt.Sprintf("渠道 #%d 未完成的任务有: %d", channelId, len(taskIds)))
  57. if len(taskIds) == 0 {
  58. continue
  59. }
  60. midjourneyChannel, err := model.CacheGetChannel(channelId)
  61. if err != nil {
  62. logger.LogError(ctx, fmt.Sprintf("CacheGetChannel: %v", err))
  63. err := model.MjBulkUpdate(taskIds, map[string]any{
  64. "fail_reason": fmt.Sprintf("获取渠道信息失败,请联系管理员,渠道ID:%d", channelId),
  65. "status": "FAILURE",
  66. "progress": "100%",
  67. })
  68. if err != nil {
  69. logger.LogInfo(ctx, fmt.Sprintf("UpdateMidjourneyTask error: %v", err))
  70. }
  71. continue
  72. }
  73. requestUrl := fmt.Sprintf("%s/mj/task/list-by-condition", *midjourneyChannel.BaseURL)
  74. body, _ := json.Marshal(map[string]any{
  75. "ids": taskIds,
  76. })
  77. req, err := http.NewRequest("POST", requestUrl, bytes.NewBuffer(body))
  78. if err != nil {
  79. logger.LogError(ctx, fmt.Sprintf("Get Task error: %v", err))
  80. continue
  81. }
  82. // 设置超时时间
  83. timeout := time.Second * 15
  84. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  85. // 使用带有超时的 context 创建新的请求
  86. req = req.WithContext(ctx)
  87. req.Header.Set("Content-Type", "application/json")
  88. req.Header.Set("mj-api-secret", midjourneyChannel.Key)
  89. resp, err := service.GetHttpClient().Do(req)
  90. if err != nil {
  91. logger.LogError(ctx, fmt.Sprintf("Get Task Do req error: %v", err))
  92. continue
  93. }
  94. if resp.StatusCode != http.StatusOK {
  95. logger.LogError(ctx, fmt.Sprintf("Get Task status code: %d", resp.StatusCode))
  96. continue
  97. }
  98. responseBody, err := io.ReadAll(resp.Body)
  99. if err != nil {
  100. logger.LogError(ctx, fmt.Sprintf("Get Task parse body error: %v", err))
  101. continue
  102. }
  103. var responseItems []dto.MidjourneyDto
  104. err = json.Unmarshal(responseBody, &responseItems)
  105. if err != nil {
  106. logger.LogError(ctx, fmt.Sprintf("Get Task parse body error2: %v, body: %s", err, string(responseBody)))
  107. continue
  108. }
  109. resp.Body.Close()
  110. req.Body.Close()
  111. cancel()
  112. for _, responseItem := range responseItems {
  113. task := taskM[responseItem.MjId]
  114. useTime := (time.Now().UnixNano() / int64(time.Millisecond)) - task.SubmitTime
  115. // 如果时间超过一小时,且进度不是100%,则认为任务失败
  116. if useTime > 3600000 && task.Progress != "100%" {
  117. responseItem.FailReason = "上游任务超时(超过1小时)"
  118. responseItem.Status = "FAILURE"
  119. }
  120. if !checkMjTaskNeedUpdate(task, responseItem) {
  121. continue
  122. }
  123. task.Code = 1
  124. task.Progress = responseItem.Progress
  125. task.PromptEn = responseItem.PromptEn
  126. task.State = responseItem.State
  127. task.SubmitTime = responseItem.SubmitTime
  128. task.StartTime = responseItem.StartTime
  129. task.FinishTime = responseItem.FinishTime
  130. task.ImageUrl = responseItem.ImageUrl
  131. task.Status = responseItem.Status
  132. task.FailReason = responseItem.FailReason
  133. if responseItem.Properties != nil {
  134. propertiesStr, _ := json.Marshal(responseItem.Properties)
  135. task.Properties = string(propertiesStr)
  136. }
  137. if responseItem.Buttons != nil {
  138. buttonStr, _ := json.Marshal(responseItem.Buttons)
  139. task.Buttons = string(buttonStr)
  140. }
  141. // 映射 VideoUrl
  142. task.VideoUrl = responseItem.VideoUrl
  143. // 映射 VideoUrls - 将数组序列化为 JSON 字符串
  144. if responseItem.VideoUrls != nil && len(responseItem.VideoUrls) > 0 {
  145. videoUrlsStr, err := json.Marshal(responseItem.VideoUrls)
  146. if err != nil {
  147. logger.LogError(ctx, fmt.Sprintf("序列化 VideoUrls 失败: %v", err))
  148. task.VideoUrls = "[]" // 失败时设置为空数组
  149. } else {
  150. task.VideoUrls = string(videoUrlsStr)
  151. }
  152. } else {
  153. task.VideoUrls = "" // 空值时清空字段
  154. }
  155. shouldReturnQuota := false
  156. if (task.Progress != "100%" && responseItem.FailReason != "") || (task.Progress == "100%" && task.Status == "FAILURE") {
  157. logger.LogInfo(ctx, task.MjId+" 构建失败,"+task.FailReason)
  158. task.Progress = "100%"
  159. if task.Quota != 0 {
  160. shouldReturnQuota = true
  161. }
  162. }
  163. err = task.Update()
  164. if err != nil {
  165. logger.LogError(ctx, "UpdateMidjourneyTask task error: "+err.Error())
  166. } else {
  167. if shouldReturnQuota {
  168. err = model.IncreaseUserQuota(task.UserId, task.Quota, false)
  169. if err != nil {
  170. logger.LogError(ctx, "fail to increase user quota: "+err.Error())
  171. }
  172. logContent := fmt.Sprintf("构图失败 %s,补偿 %s", task.MjId, logger.LogQuota(task.Quota))
  173. model.RecordLog(task.UserId, model.LogTypeSystem, logContent)
  174. }
  175. }
  176. }
  177. }
  178. }
  179. }
  180. func checkMjTaskNeedUpdate(oldTask *model.Midjourney, newTask dto.MidjourneyDto) bool {
  181. if oldTask.Code != 1 {
  182. return true
  183. }
  184. if oldTask.Progress != newTask.Progress {
  185. return true
  186. }
  187. if oldTask.PromptEn != newTask.PromptEn {
  188. return true
  189. }
  190. if oldTask.State != newTask.State {
  191. return true
  192. }
  193. if oldTask.SubmitTime != newTask.SubmitTime {
  194. return true
  195. }
  196. if oldTask.StartTime != newTask.StartTime {
  197. return true
  198. }
  199. if oldTask.FinishTime != newTask.FinishTime {
  200. return true
  201. }
  202. if oldTask.ImageUrl != newTask.ImageUrl {
  203. return true
  204. }
  205. if oldTask.Status != newTask.Status {
  206. return true
  207. }
  208. if oldTask.FailReason != newTask.FailReason {
  209. return true
  210. }
  211. if oldTask.FinishTime != newTask.FinishTime {
  212. return true
  213. }
  214. if oldTask.Progress != "100%" && newTask.FailReason != "" {
  215. return true
  216. }
  217. // 检查 VideoUrl 是否需要更新
  218. if oldTask.VideoUrl != newTask.VideoUrl {
  219. return true
  220. }
  221. // 检查 VideoUrls 是否需要更新
  222. if newTask.VideoUrls != nil && len(newTask.VideoUrls) > 0 {
  223. newVideoUrlsStr, _ := json.Marshal(newTask.VideoUrls)
  224. if oldTask.VideoUrls != string(newVideoUrlsStr) {
  225. return true
  226. }
  227. } else if oldTask.VideoUrls != "" {
  228. // 如果新数据没有 VideoUrls 但旧数据有,需要更新(清空)
  229. return true
  230. }
  231. return false
  232. }
  233. func GetAllMidjourney(c *gin.Context) {
  234. pageInfo := common.GetPageQuery(c)
  235. // 解析其他查询参数
  236. queryParams := model.TaskQueryParams{
  237. ChannelID: c.Query("channel_id"),
  238. MjID: c.Query("mj_id"),
  239. StartTimestamp: c.Query("start_timestamp"),
  240. EndTimestamp: c.Query("end_timestamp"),
  241. }
  242. items := model.GetAllTasks(pageInfo.GetStartIdx(), pageInfo.GetPageSize(), queryParams)
  243. total := model.CountAllTasks(queryParams)
  244. if setting.MjForwardUrlEnabled {
  245. for i, midjourney := range items {
  246. midjourney.ImageUrl = system_setting.ServerAddress + "/mj/image/" + midjourney.MjId
  247. items[i] = midjourney
  248. }
  249. }
  250. pageInfo.SetTotal(int(total))
  251. pageInfo.SetItems(items)
  252. common.ApiSuccess(c, pageInfo)
  253. }
  254. func GetUserMidjourney(c *gin.Context) {
  255. pageInfo := common.GetPageQuery(c)
  256. userId := c.GetInt("id")
  257. queryParams := model.TaskQueryParams{
  258. MjID: c.Query("mj_id"),
  259. StartTimestamp: c.Query("start_timestamp"),
  260. EndTimestamp: c.Query("end_timestamp"),
  261. }
  262. items := model.GetAllUserTask(userId, pageInfo.GetStartIdx(), pageInfo.GetPageSize(), queryParams)
  263. total := model.CountAllUserTask(userId, queryParams)
  264. if setting.MjForwardUrlEnabled {
  265. for i, midjourney := range items {
  266. midjourney.ImageUrl = system_setting.ServerAddress + "/mj/image/" + midjourney.MjId
  267. items[i] = midjourney
  268. }
  269. }
  270. pageInfo.SetTotal(int(total))
  271. pageInfo.SetItems(items)
  272. common.ApiSuccess(c, pageInfo)
  273. }