Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

437 linhas
12 KiB

  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "sync"
  7. "github.com/QuantumNous/new-api/common"
  8. "github.com/samber/lo"
  9. "gorm.io/gorm"
  10. "gorm.io/gorm/clause"
  11. )
  12. type Ability struct {
  13. Group string `json:"group" gorm:"type:varchar(64);primaryKey;autoIncrement:false"`
  14. Model string `json:"model" gorm:"type:varchar(255);primaryKey;autoIncrement:false"`
  15. ChannelId int `json:"channel_id" gorm:"primaryKey;autoIncrement:false;index"`
  16. Enabled bool `json:"enabled"`
  17. Priority *int64 `json:"priority" gorm:"bigint;default:0;index"`
  18. Weight uint `json:"weight" gorm:"default:0;index"`
  19. Tag *string `json:"tag" gorm:"index"`
  20. }
  21. type AbilityWithChannel struct {
  22. Ability
  23. ChannelType int `json:"channel_type"`
  24. }
  25. type ChannelFilter func(*Channel) (bool, error)
  26. func GetAllEnableAbilityWithChannels() ([]AbilityWithChannel, error) {
  27. var abilities []AbilityWithChannel
  28. err := DB.Table("abilities").
  29. Select("abilities.*, channels.type as channel_type").
  30. Joins("left join channels on abilities.channel_id = channels.id").
  31. Joins("left join models on abilities.model = models.model_name").
  32. Where("abilities.enabled = ? and models.model_name is NOT null", true).
  33. Scan(&abilities).Error
  34. return abilities, err
  35. }
  36. func GetGroupEnabledModels(group string) []string {
  37. var models []string
  38. // Find distinct models
  39. DB.Table("abilities").Where(commonGroupCol+" = ? and enabled = ?", group, true).Distinct("model").Pluck("model", &models)
  40. return models
  41. }
  42. func GetEnabledModels() []string {
  43. var models []string
  44. // Find distinct models
  45. DB.Table("abilities").Where("enabled = ?", true).Distinct("model").Pluck("model", &models)
  46. return models
  47. }
  48. func GetAllEnableAbilities() []Ability {
  49. var abilities []Ability
  50. DB.Find(&abilities, "enabled = ?", true)
  51. return abilities
  52. }
  53. // GetAbilitiesByChannelId 获取指定渠道的所有能力
  54. func GetAbilitiesByChannelId(channelId int) ([]*Ability, error) {
  55. var abilities []*Ability
  56. err := DB.Where("channel_id = ?", channelId).Find(&abilities).Error
  57. return abilities, err
  58. }
  59. func getPriority(group string, model string, retry int) (int, error) {
  60. var priorities []int
  61. err := DB.Model(&Ability{}).
  62. Select("DISTINCT(priority)").
  63. Where(commonGroupCol+" = ? and model = ? and enabled = ?", group, model, true).
  64. Order("priority DESC"). // 按优先级降序排序
  65. Pluck("priority", &priorities).Error // Pluck用于将查询的结果直接扫描到一个切片中
  66. if err != nil {
  67. // 处理错误
  68. return 0, err
  69. }
  70. if len(priorities) == 0 {
  71. // 如果没有查询到优先级,则返回错误
  72. return 0, errors.New("数据库一致性被破坏")
  73. }
  74. // 确定要使用的优先级
  75. var priorityToUse int
  76. if retry >= len(priorities) {
  77. // 如果重试次数大于优先级数,则使用最小的优先级
  78. priorityToUse = priorities[len(priorities)-1]
  79. } else {
  80. priorityToUse = priorities[retry]
  81. }
  82. return priorityToUse, nil
  83. }
  84. func getChannelQuery(group string, model string, retry int) (*gorm.DB, error) {
  85. maxPrioritySubQuery := DB.Model(&Ability{}).Select("MAX(priority)").Where(commonGroupCol+" = ? and model = ? and enabled = ?", group, model, true)
  86. channelQuery := DB.Where(commonGroupCol+" = ? and model = ? and enabled = ? and priority = (?)", group, model, true, maxPrioritySubQuery)
  87. if retry != 0 {
  88. priority, err := getPriority(group, model, retry)
  89. if err != nil {
  90. return nil, err
  91. } else {
  92. channelQuery = DB.Where(commonGroupCol+" = ? and model = ? and enabled = ? and priority = ?", group, model, true, priority)
  93. }
  94. }
  95. return channelQuery, nil
  96. }
  97. func GetChannel(group string, model string, retry int) (*Channel, error) {
  98. return GetChannelWithFilter(group, model, retry, nil)
  99. }
  100. func GetChannelWithFilter(group string, model string, retry int, filter ChannelFilter) (*Channel, error) {
  101. var abilities []Ability
  102. var err error = nil
  103. channelQuery, err := getChannelQuery(group, model, retry)
  104. if err != nil {
  105. return nil, err
  106. }
  107. if common.UsingSQLite || common.UsingPostgreSQL {
  108. err = channelQuery.Order("weight DESC").Find(&abilities).Error
  109. } else {
  110. err = channelQuery.Order("weight DESC").Find(&abilities).Error
  111. }
  112. if err != nil {
  113. return nil, err
  114. }
  115. if filter != nil && len(abilities) > 0 {
  116. channelIds := make([]int, 0, len(abilities))
  117. seenChannelIds := make(map[int]struct{}, len(abilities))
  118. for _, ability := range abilities {
  119. if _, ok := seenChannelIds[ability.ChannelId]; ok {
  120. continue
  121. }
  122. seenChannelIds[ability.ChannelId] = struct{}{}
  123. channelIds = append(channelIds, ability.ChannelId)
  124. }
  125. var channels []Channel
  126. if err = DB.Where("id IN ?", channelIds).Find(&channels).Error; err != nil {
  127. return nil, err
  128. }
  129. channelByID := make(map[int]*Channel, len(channels))
  130. for i := range channels {
  131. channelByID[channels[i].Id] = &channels[i]
  132. }
  133. filtered := make([]Ability, 0, len(abilities))
  134. for _, ability := range abilities {
  135. candidate, ok := channelByID[ability.ChannelId]
  136. if !ok {
  137. return nil, fmt.Errorf("channel #%d does not exist", ability.ChannelId)
  138. }
  139. accepted, filterErr := filter(candidate)
  140. if filterErr != nil {
  141. return nil, filterErr
  142. }
  143. if accepted {
  144. filtered = append(filtered, ability)
  145. }
  146. }
  147. abilities = filtered
  148. }
  149. channel := Channel{}
  150. if len(abilities) > 0 {
  151. // Randomly choose one
  152. weightSum := uint(0)
  153. for _, ability_ := range abilities {
  154. weightSum += ability_.Weight + 10
  155. }
  156. // Randomly choose one
  157. weight := common.GetRandomInt(int(weightSum))
  158. for _, ability_ := range abilities {
  159. weight -= int(ability_.Weight) + 10
  160. //log.Printf("weight: %d, ability weight: %d", weight, *ability_.Weight)
  161. if weight <= 0 {
  162. channel.Id = ability_.ChannelId
  163. break
  164. }
  165. }
  166. } else {
  167. return nil, nil
  168. }
  169. err = DB.First(&channel, "id = ?", channel.Id).Error
  170. return &channel, err
  171. }
  172. func (channel *Channel) AddAbilities(tx *gorm.DB) error {
  173. models_ := strings.Split(channel.Models, ",")
  174. // 统一使用 useDB,避免重复的数据库连接选择
  175. useDB := DB
  176. if tx != nil {
  177. useDB = tx
  178. }
  179. // === 自动同步模型到 models 表(批量处理)===
  180. // 收集需要同步的模型名称
  181. modelNames := make([]string, 0, len(models_))
  182. for _, modelName := range models_ {
  183. modelName = strings.TrimSpace(modelName)
  184. if modelName != "" {
  185. modelNames = append(modelNames, modelName)
  186. }
  187. }
  188. // 批量查询已存在的模型
  189. existingModels := make(map[string]bool)
  190. if len(modelNames) > 0 {
  191. var existingModelList []Model
  192. useDB.Where("model_name IN ?", modelNames).Select("model_name").Find(&existingModelList)
  193. for _, m := range existingModelList {
  194. existingModels[m.ModelName] = true
  195. }
  196. }
  197. // 收集需要创建的模型
  198. now := common.GetTimestamp()
  199. newModels := make([]Model, 0, len(modelNames))
  200. for _, modelName := range modelNames {
  201. if !existingModels[modelName] {
  202. newModels = append(newModels, Model{
  203. ModelName: modelName,
  204. Status: 1, // 启用状态
  205. SyncOfficial: 0, // 标记为用户模型,不被官方同步覆盖
  206. CreatedTime: now,
  207. UpdatedTime: now,
  208. })
  209. }
  210. }
  211. // 批量插入新模型(使用 OnConflict 忽略重复)
  212. if len(newModels) > 0 {
  213. for _, chunk := range lo.Chunk(newModels, 50) {
  214. if err := useDB.Clauses(clause.OnConflict{DoNothing: true}).Create(&chunk).Error; err != nil {
  215. return err
  216. }
  217. }
  218. }
  219. // === 自动同步结束 ===
  220. groups_ := strings.Split(channel.Group, ",")
  221. abilitySet := make(map[string]struct{})
  222. abilities := make([]Ability, 0, len(models_))
  223. for _, model := range models_ {
  224. for _, group := range groups_ {
  225. key := group + "|" + model
  226. if _, exists := abilitySet[key]; exists {
  227. continue
  228. }
  229. abilitySet[key] = struct{}{}
  230. ability := Ability{
  231. Group: group,
  232. Model: model,
  233. ChannelId: channel.Id,
  234. Enabled: channel.Status == common.ChannelStatusEnabled,
  235. Priority: channel.Priority,
  236. Weight: uint(channel.GetWeight()),
  237. Tag: channel.Tag,
  238. }
  239. abilities = append(abilities, ability)
  240. }
  241. }
  242. if len(abilities) == 0 {
  243. return nil
  244. }
  245. for _, chunk := range lo.Chunk(abilities, 50) {
  246. err := useDB.Clauses(clause.OnConflict{DoNothing: true}).Create(&chunk).Error
  247. if err != nil {
  248. return err
  249. }
  250. }
  251. return nil
  252. }
  253. func (channel *Channel) DeleteAbilities() error {
  254. return DB.Where("channel_id = ?", channel.Id).Delete(&Ability{}).Error
  255. }
  256. // UpdateAbilities updates abilities of this channel.
  257. // Make sure the channel is completed before calling this function.
  258. func (channel *Channel) UpdateAbilities(tx *gorm.DB) error {
  259. isNewTx := false
  260. // 如果没有传入事务,创建新的事务
  261. if tx == nil {
  262. tx = DB.Begin()
  263. if tx.Error != nil {
  264. return tx.Error
  265. }
  266. isNewTx = true
  267. defer func() {
  268. if r := recover(); r != nil {
  269. tx.Rollback()
  270. }
  271. }()
  272. }
  273. // First delete all abilities of this channel
  274. err := tx.Where("channel_id = ?", channel.Id).Delete(&Ability{}).Error
  275. if err != nil {
  276. if isNewTx {
  277. tx.Rollback()
  278. }
  279. return err
  280. }
  281. // Then add new abilities
  282. models_ := strings.Split(channel.Models, ",")
  283. groups_ := strings.Split(channel.Group, ",")
  284. abilitySet := make(map[string]struct{})
  285. abilities := make([]Ability, 0, len(models_))
  286. for _, model := range models_ {
  287. for _, group := range groups_ {
  288. key := group + "|" + model
  289. if _, exists := abilitySet[key]; exists {
  290. continue
  291. }
  292. abilitySet[key] = struct{}{}
  293. ability := Ability{
  294. Group: group,
  295. Model: model,
  296. ChannelId: channel.Id,
  297. Enabled: channel.Status == common.ChannelStatusEnabled,
  298. Priority: channel.Priority,
  299. Weight: uint(channel.GetWeight()),
  300. Tag: channel.Tag,
  301. }
  302. abilities = append(abilities, ability)
  303. }
  304. }
  305. if len(abilities) > 0 {
  306. for _, chunk := range lo.Chunk(abilities, 50) {
  307. err = tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&chunk).Error
  308. if err != nil {
  309. if isNewTx {
  310. tx.Rollback()
  311. }
  312. return err
  313. }
  314. }
  315. }
  316. // 如果是新创建的事务,需要提交
  317. if isNewTx {
  318. return tx.Commit().Error
  319. }
  320. return nil
  321. }
  322. func UpdateAbilityStatus(channelId int, status bool) error {
  323. return DB.Model(&Ability{}).Where("channel_id = ?", channelId).Select("enabled").Update("enabled", status).Error
  324. }
  325. func UpdateAbilityStatusByTag(tag string, status bool) error {
  326. return DB.Model(&Ability{}).Where("tag = ?", tag).Select("enabled").Update("enabled", status).Error
  327. }
  328. func UpdateAbilityByTag(tag string, newTag *string, priority *int64, weight *uint) error {
  329. ability := Ability{}
  330. if newTag != nil {
  331. ability.Tag = newTag
  332. }
  333. if priority != nil {
  334. ability.Priority = priority
  335. }
  336. if weight != nil {
  337. ability.Weight = *weight
  338. }
  339. return DB.Model(&Ability{}).Where("tag = ?", tag).Updates(ability).Error
  340. }
  341. var fixLock = sync.Mutex{}
  342. func FixAbility() (int, int, error) {
  343. lock := fixLock.TryLock()
  344. if !lock {
  345. return 0, 0, errors.New("已经有一个修复任务在运行中,请稍后再试")
  346. }
  347. defer fixLock.Unlock()
  348. // truncate abilities table
  349. if common.UsingSQLite {
  350. err := DB.Exec("DELETE FROM abilities").Error
  351. if err != nil {
  352. common.SysLog(fmt.Sprintf("Delete abilities failed: %s", err.Error()))
  353. return 0, 0, err
  354. }
  355. } else {
  356. err := DB.Exec("TRUNCATE TABLE abilities").Error
  357. if err != nil {
  358. common.SysLog(fmt.Sprintf("Truncate abilities failed: %s", err.Error()))
  359. return 0, 0, err
  360. }
  361. }
  362. var channels []*Channel
  363. // Find all channels
  364. err := DB.Model(&Channel{}).Find(&channels).Error
  365. if err != nil {
  366. return 0, 0, err
  367. }
  368. if len(channels) == 0 {
  369. return 0, 0, nil
  370. }
  371. successCount := 0
  372. failCount := 0
  373. for _, chunk := range lo.Chunk(channels, 50) {
  374. ids := lo.Map(chunk, func(c *Channel, _ int) int { return c.Id })
  375. // Delete all abilities of this channel
  376. err = DB.Where("channel_id IN ?", ids).Delete(&Ability{}).Error
  377. if err != nil {
  378. common.SysLog(fmt.Sprintf("Delete abilities failed: %s", err.Error()))
  379. failCount += len(chunk)
  380. continue
  381. }
  382. // Then add new abilities
  383. for _, channel := range chunk {
  384. err = channel.AddAbilities(nil)
  385. if err != nil {
  386. common.SysLog(fmt.Sprintf("Add abilities for channel %d failed: %s", channel.Id, err.Error()))
  387. failCount++
  388. } else {
  389. successCount++
  390. }
  391. }
  392. }
  393. InitChannelCache()
  394. return successCount, failCount, nil
  395. }