midjourney.go 8.5 KB

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