forked from MartialBE/one-hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmidjourney.go
317 lines (286 loc) · 8.14 KB
/
midjourney.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Author: Calcium-Ion
// GitHub: https://github.com/Calcium-Ion/new-api
// Path: controller/midjourney.go
package controller
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"one-api/common"
"one-api/common/logger"
"one-api/common/requester"
"one-api/model"
provider "one-api/providers/midjourney"
"sync"
"sync/atomic"
"time"
"github.com/gin-gonic/gin"
)
var (
taskActive int32 = 0
lock sync.Mutex
cond = sync.NewCond(&lock)
)
func InitMidjourneyTask() {
common.SafeGoroutine(func() {
midjourneyTask()
})
ActivateUpdateMidjourneyTaskBulk()
}
func midjourneyTask() {
for {
lock.Lock()
for atomic.LoadInt32(&taskActive) == 0 {
cond.Wait() // 等待激活信号
}
lock.Unlock()
UpdateMidjourneyTaskBulk()
}
}
func ActivateUpdateMidjourneyTaskBulk() {
if atomic.LoadInt32(&taskActive) == 1 {
return
}
lock.Lock()
atomic.StoreInt32(&taskActive, 1)
cond.Signal() // 通知等待的任务
lock.Unlock()
}
func DeactivateMidjourneyTaskBulk() {
if atomic.LoadInt32(&taskActive) == 0 {
return
}
lock.Lock()
atomic.StoreInt32(&taskActive, 0)
lock.Unlock()
}
func UpdateMidjourneyTaskBulk() {
ctx := context.WithValue(context.Background(), logger.RequestIdKey, "MidjourneyTask")
for {
logger.LogInfo(ctx, "running")
tasks := model.GetAllUnFinishTasks()
// 如果没有未完成的任务,则等待
if len(tasks) == 0 {
DeactivateMidjourneyTaskBulk()
logger.LogInfo(ctx, "no tasks, waiting...")
return
}
logger.LogWarn(ctx, fmt.Sprintf("检测到未完成的任务数有: %v", len(tasks)))
taskChannelM := make(map[int][]string)
taskM := make(map[string]*model.Midjourney)
nullTaskIds := make([]int, 0)
for _, task := range tasks {
if task.MjId == "" {
// 统计失败的未完成任务
nullTaskIds = append(nullTaskIds, task.Id)
continue
}
taskM[task.MjId] = task
taskChannelM[task.ChannelId] = append(taskChannelM[task.ChannelId], task.MjId)
}
if len(nullTaskIds) > 0 {
err := model.MjBulkUpdateByTaskIds(nullTaskIds, map[string]any{
"status": "FAILURE",
"progress": "100%",
})
if err != nil {
logger.LogError(ctx, fmt.Sprintf("Fix null mj_id task error: %v", err))
} else {
logger.LogInfo(ctx, fmt.Sprintf("Fix null mj_id task success: %v", nullTaskIds))
}
}
if len(taskChannelM) == 0 {
continue
}
for channelId, taskIds := range taskChannelM {
logger.LogWarn(ctx, fmt.Sprintf("渠道 #%d 未完成的任务有: %d", channelId, len(taskIds)))
if len(taskIds) == 0 {
continue
}
midjourneyChannel := model.ChannelGroup.GetChannel(channelId)
if midjourneyChannel == nil {
err := model.MjBulkUpdate(taskIds, map[string]any{
"fail_reason": fmt.Sprintf("获取渠道信息失败,请联系管理员,渠道ID:%d", channelId),
"status": "FAILURE",
"progress": "100%",
})
logger.LogError(ctx, fmt.Sprintf("UpdateMidjourneyTask error: %v", err))
continue
}
err := MjTaskHandler(midjourneyChannel, taskIds, taskM)
if err != nil {
logger.LogError(ctx, fmt.Sprintf("MjTaskHandler error: %v", err))
}
}
time.Sleep(time.Duration(15) * time.Second)
}
}
func MjTaskHandler(midjourneyChannel *model.Channel, taskIds []string, taskM map[string]*model.Midjourney) error {
requestUrl := fmt.Sprintf("%s/mj/task/list-by-condition", *midjourneyChannel.BaseURL)
body, _ := json.Marshal(map[string]any{
"ids": taskIds,
})
req, err := http.NewRequest("POST", requestUrl, bytes.NewBuffer(body))
if err != nil {
return fmt.Errorf("get task error: %v", err)
}
// 设置超时时间
timeout := time.Second * 5
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// 使用带有超时的 context 创建新的请求
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("mj-api-secret", midjourneyChannel.Key)
resp, err := requester.HTTPClient.Do(req)
if err != nil {
return fmt.Errorf("get task do req error: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("get task status code: %d", resp.StatusCode)
}
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("get task parse body error: %v", err)
}
var responseItems []provider.MidjourneyDto
err = json.Unmarshal(responseBody, &responseItems)
if err != nil {
return fmt.Errorf("get task parse body error2: %v, body: %s", err, string(responseBody))
}
for _, responseItem := range responseItems {
task := taskM[responseItem.MjId]
useTime := (time.Now().UnixNano() / int64(time.Millisecond)) - task.SubmitTime
// 如果时间超过一小时,且进度不是100%,则认为任务失败
if useTime > 3600000 && task.Progress != "100%" {
responseItem.FailReason = "上游任务超时(超过1小时)"
responseItem.Status = "FAILURE"
}
if !checkMjTaskNeedUpdate(task, responseItem) {
continue
}
task.Code = 1
task.Progress = responseItem.Progress
task.PromptEn = responseItem.PromptEn
task.State = responseItem.State
task.SubmitTime = responseItem.SubmitTime
task.StartTime = responseItem.StartTime
task.FinishTime = responseItem.FinishTime
task.ImageUrl = responseItem.ImageUrl
task.Status = responseItem.Status
task.FailReason = responseItem.FailReason
if responseItem.Properties != nil {
propertiesStr, _ := json.Marshal(responseItem.Properties)
task.Properties = string(propertiesStr)
}
if responseItem.Buttons != nil {
buttonStr, _ := json.Marshal(responseItem.Buttons)
task.Buttons = string(buttonStr)
}
if (task.Progress != "100%" && responseItem.FailReason != "") || (task.Progress == "100%" && task.Status == "FAILURE") {
logger.LogError(ctx, task.MjId+" 构建失败,"+task.FailReason)
task.Progress = "100%"
err = model.CacheUpdateUserQuota(task.UserId)
if err != nil {
logger.LogError(ctx, "error update user quota cache: "+err.Error())
} else {
quota := task.Quota
if quota != 0 {
err = model.IncreaseUserQuota(task.UserId, quota)
if err != nil {
logger.LogError(ctx, "fail to increase user quota: "+err.Error())
}
logContent := fmt.Sprintf("构图失败 %s,补偿 %s", task.MjId, common.LogQuota(quota))
model.RecordLog(task.UserId, model.LogTypeSystem, logContent)
}
}
}
err = task.Update()
if err != nil {
logger.LogError(ctx, "UpdateMidjourneyTask task error: "+err.Error())
}
}
return nil
}
func checkMjTaskNeedUpdate(oldTask *model.Midjourney, newTask provider.MidjourneyDto) bool {
if oldTask.Code != 1 {
return true
}
if oldTask.Progress != newTask.Progress {
return true
}
if oldTask.PromptEn != newTask.PromptEn {
return true
}
if oldTask.State != newTask.State {
return true
}
if oldTask.SubmitTime != newTask.SubmitTime {
return true
}
if oldTask.StartTime != newTask.StartTime {
return true
}
if oldTask.FinishTime != newTask.FinishTime {
return true
}
if oldTask.ImageUrl != newTask.ImageUrl {
return true
}
if oldTask.Status != newTask.Status {
return true
}
if oldTask.FailReason != newTask.FailReason {
return true
}
if oldTask.FinishTime != newTask.FinishTime {
return true
}
if oldTask.Progress != "100%" && newTask.FailReason != "" {
return true
}
return false
}
func GetAllMidjourney(c *gin.Context) {
var params model.MJTaskQueryParams
if err := c.ShouldBindQuery(¶ms); err != nil {
common.APIRespondWithError(c, http.StatusOK, err)
return
}
midjourneys, err := model.GetAllMJTasks(¶ms)
if err != nil {
common.APIRespondWithError(c, http.StatusOK, err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
"data": midjourneys,
})
}
func GetUserMidjourney(c *gin.Context) {
userId := c.GetInt("id")
tokenId := c.GetInt("token_id")
var params model.MJTaskQueryParams
if err := c.ShouldBindQuery(¶ms); err != nil {
common.APIRespondWithError(c, http.StatusOK, err)
return
}
if tokenId > 0 {
params.TokenID = tokenId
}
midjourneys, err := model.GetAllUserMJTask(userId, ¶ms)
if err != nil {
common.APIRespondWithError(c, http.StatusOK, err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
"data": midjourneys,
})
}