midjourney.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. package controller
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/gin-gonic/gin"
  8. "io"
  9. "log"
  10. "net/http"
  11. "one-api/common"
  12. "one-api/dto"
  13. "one-api/model"
  14. "one-api/service"
  15. "one-api/setting"
  16. "strconv"
  17. "time"
  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. common.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. common.LogError(ctx, fmt.Sprintf("Fix null mj_id task error: %v", err))
  48. } else {
  49. common.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. common.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. common.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. common.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. common.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. common.LogError(ctx, fmt.Sprintf("Get Task Do req error: %v", err))
  92. continue
  93. }
  94. if resp.StatusCode != http.StatusOK {
  95. common.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. common.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. common.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. shouldReturnQuota := false
  142. if (task.Progress != "100%" && responseItem.FailReason != "") || (task.Progress == "100%" && task.Status == "FAILURE") {
  143. common.LogInfo(ctx, task.MjId+" 构建失败,"+task.FailReason)
  144. task.Progress = "100%"
  145. if task.Quota != 0 {
  146. shouldReturnQuota = true
  147. }
  148. }
  149. err = task.Update()
  150. if err != nil {
  151. common.LogError(ctx, "UpdateMidjourneyTask task error: "+err.Error())
  152. } else {
  153. if shouldReturnQuota {
  154. err = model.IncreaseUserQuota(task.UserId, task.Quota)
  155. if err != nil {
  156. common.LogError(ctx, "fail to increase user quota: "+err.Error())
  157. }
  158. logContent := fmt.Sprintf("构图失败 %s,补偿 %s", task.MjId, common.LogQuota(task.Quota))
  159. model.RecordLog(task.UserId, model.LogTypeSystem, logContent)
  160. }
  161. }
  162. }
  163. }
  164. }
  165. }
  166. func checkMjTaskNeedUpdate(oldTask *model.Midjourney, newTask dto.MidjourneyDto) bool {
  167. if oldTask.Code != 1 {
  168. return true
  169. }
  170. if oldTask.Progress != newTask.Progress {
  171. return true
  172. }
  173. if oldTask.PromptEn != newTask.PromptEn {
  174. return true
  175. }
  176. if oldTask.State != newTask.State {
  177. return true
  178. }
  179. if oldTask.SubmitTime != newTask.SubmitTime {
  180. return true
  181. }
  182. if oldTask.StartTime != newTask.StartTime {
  183. return true
  184. }
  185. if oldTask.FinishTime != newTask.FinishTime {
  186. return true
  187. }
  188. if oldTask.ImageUrl != newTask.ImageUrl {
  189. return true
  190. }
  191. if oldTask.Status != newTask.Status {
  192. return true
  193. }
  194. if oldTask.FailReason != newTask.FailReason {
  195. return true
  196. }
  197. if oldTask.FinishTime != newTask.FinishTime {
  198. return true
  199. }
  200. if oldTask.Progress != "100%" && newTask.FailReason != "" {
  201. return true
  202. }
  203. return false
  204. }
  205. func GetAllMidjourney(c *gin.Context) {
  206. p, _ := strconv.Atoi(c.Query("p"))
  207. if p < 0 {
  208. p = 0
  209. }
  210. // 解析其他查询参数
  211. queryParams := model.TaskQueryParams{
  212. ChannelID: c.Query("channel_id"),
  213. MjID: c.Query("mj_id"),
  214. StartTimestamp: c.Query("start_timestamp"),
  215. EndTimestamp: c.Query("end_timestamp"),
  216. }
  217. logs := model.GetAllTasks(p*common.ItemsPerPage, common.ItemsPerPage, queryParams)
  218. if logs == nil {
  219. logs = make([]*model.Midjourney, 0)
  220. }
  221. if setting.MjForwardUrlEnabled {
  222. for i, midjourney := range logs {
  223. midjourney.ImageUrl = setting.ServerAddress + "/mj/image/" + midjourney.MjId
  224. logs[i] = midjourney
  225. }
  226. }
  227. c.JSON(200, gin.H{
  228. "success": true,
  229. "message": "",
  230. "data": logs,
  231. })
  232. }
  233. func GetUserMidjourney(c *gin.Context) {
  234. p, _ := strconv.Atoi(c.Query("p"))
  235. if p < 0 {
  236. p = 0
  237. }
  238. userId := c.GetInt("id")
  239. log.Printf("userId = %d \n", userId)
  240. queryParams := model.TaskQueryParams{
  241. MjID: c.Query("mj_id"),
  242. StartTimestamp: c.Query("start_timestamp"),
  243. EndTimestamp: c.Query("end_timestamp"),
  244. }
  245. logs := model.GetAllUserTask(userId, p*common.ItemsPerPage, common.ItemsPerPage, queryParams)
  246. if logs == nil {
  247. logs = make([]*model.Midjourney, 0)
  248. }
  249. if setting.MjForwardUrlEnabled {
  250. for i, midjourney := range logs {
  251. midjourney.ImageUrl = setting.ServerAddress + "/mj/image/" + midjourney.MjId
  252. logs[i] = midjourney
  253. }
  254. }
  255. c.JSON(200, gin.H{
  256. "success": true,
  257. "message": "",
  258. "data": logs,
  259. })
  260. }