2023-04-23 10:24:11 +00:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"net/http"
|
|
|
|
"one-api/common"
|
|
|
|
"one-api/model"
|
|
|
|
"strconv"
|
2023-06-11 01:37:36 +00:00
|
|
|
"strings"
|
2023-04-23 10:24:11 +00:00
|
|
|
)
|
|
|
|
|
2023-06-07 15:26:00 +00:00
|
|
|
type ModelRequest struct {
|
|
|
|
Model string `json:"model"`
|
|
|
|
}
|
|
|
|
|
2023-04-23 10:24:11 +00:00
|
|
|
func Distribute() func(c *gin.Context) {
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
var channel *model.Channel
|
|
|
|
channelId, ok := c.Get("channelId")
|
|
|
|
if ok {
|
|
|
|
id, err := strconv.Atoi(channelId.(string))
|
|
|
|
if err != nil {
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
|
|
"error": gin.H{
|
|
|
|
"message": "无效的渠道 ID",
|
|
|
|
"type": "one_api_error",
|
|
|
|
},
|
|
|
|
})
|
|
|
|
c.Abort()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
channel, err = model.GetChannelById(id, true)
|
|
|
|
if err != nil {
|
|
|
|
c.JSON(200, gin.H{
|
|
|
|
"error": gin.H{
|
|
|
|
"message": "无效的渠道 ID",
|
|
|
|
"type": "one_api_error",
|
|
|
|
},
|
|
|
|
})
|
|
|
|
c.Abort()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if channel.Status != common.ChannelStatusEnabled {
|
|
|
|
c.JSON(200, gin.H{
|
|
|
|
"error": gin.H{
|
|
|
|
"message": "该渠道已被禁用",
|
|
|
|
"type": "one_api_error",
|
|
|
|
},
|
|
|
|
})
|
|
|
|
c.Abort()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// Select a channel for the user
|
2023-06-07 15:26:00 +00:00
|
|
|
var modelRequest ModelRequest
|
|
|
|
err := common.UnmarshalBodyReusable(c, &modelRequest)
|
|
|
|
if err != nil {
|
|
|
|
c.JSON(200, gin.H{
|
|
|
|
"error": gin.H{
|
|
|
|
"message": "无效的请求",
|
|
|
|
"type": "one_api_error",
|
|
|
|
},
|
|
|
|
})
|
|
|
|
c.Abort()
|
|
|
|
return
|
|
|
|
}
|
2023-06-11 01:37:36 +00:00
|
|
|
if strings.HasPrefix(c.Request.URL.Path, "/v1/moderations") {
|
|
|
|
if modelRequest.Model == "" {
|
|
|
|
modelRequest.Model = "text-moderation-stable"
|
|
|
|
}
|
|
|
|
}
|
2023-06-07 15:26:00 +00:00
|
|
|
userId := c.GetInt("id")
|
|
|
|
userGroup, _ := model.GetUserGroup(userId)
|
|
|
|
channel, err = model.GetRandomSatisfiedChannel(userGroup, modelRequest.Model)
|
2023-04-23 10:24:11 +00:00
|
|
|
if err != nil {
|
|
|
|
c.JSON(200, gin.H{
|
|
|
|
"error": gin.H{
|
|
|
|
"message": "无可用渠道",
|
|
|
|
"type": "one_api_error",
|
|
|
|
},
|
|
|
|
})
|
|
|
|
c.Abort()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
c.Set("channel", channel.Type)
|
2023-05-15 09:34:09 +00:00
|
|
|
c.Set("channel_id", channel.Id)
|
|
|
|
c.Set("channel_name", channel.Name)
|
2023-04-23 10:24:11 +00:00
|
|
|
c.Request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", channel.Key))
|
2023-06-09 10:30:01 +00:00
|
|
|
c.Set("base_url", channel.BaseURL)
|
|
|
|
if channel.Type == common.ChannelTypeAzure {
|
|
|
|
c.Set("api_version", channel.Other)
|
2023-04-23 12:35:49 +00:00
|
|
|
}
|
2023-04-23 10:24:11 +00:00
|
|
|
c.Next()
|
|
|
|
}
|
|
|
|
}
|