channel.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. package model
  2. import (
  3. "database/sql/driver"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "math/rand"
  8. "one-api/common"
  9. "one-api/constant"
  10. "one-api/dto"
  11. "one-api/types"
  12. "strings"
  13. "sync"
  14. "gorm.io/gorm"
  15. )
  16. type Channel struct {
  17. Id int `json:"id"`
  18. Type int `json:"type" gorm:"default:0"`
  19. Key string `json:"key" gorm:"not null"`
  20. OpenAIOrganization *string `json:"openai_organization"`
  21. TestModel *string `json:"test_model"`
  22. Status int `json:"status" gorm:"default:1"`
  23. Name string `json:"name" gorm:"index"`
  24. Weight *uint `json:"weight" gorm:"default:0"`
  25. CreatedTime int64 `json:"created_time" gorm:"bigint"`
  26. TestTime int64 `json:"test_time" gorm:"bigint"`
  27. ResponseTime int `json:"response_time"` // in milliseconds
  28. BaseURL *string `json:"base_url" gorm:"column:base_url;default:''"`
  29. Other string `json:"other"`
  30. Balance float64 `json:"balance"` // in USD
  31. BalanceUpdatedTime int64 `json:"balance_updated_time" gorm:"bigint"`
  32. Models string `json:"models"`
  33. Group string `json:"group" gorm:"type:varchar(64);default:'default'"`
  34. UsedQuota int64 `json:"used_quota" gorm:"bigint;default:0"`
  35. ModelMapping *string `json:"model_mapping" gorm:"type:text"`
  36. //MaxInputTokens *int `json:"max_input_tokens" gorm:"default:0"`
  37. StatusCodeMapping *string `json:"status_code_mapping" gorm:"type:varchar(1024);default:''"`
  38. Priority *int64 `json:"priority" gorm:"bigint;default:0"`
  39. AutoBan *int `json:"auto_ban" gorm:"default:1"`
  40. OtherInfo string `json:"other_info"`
  41. Tag *string `json:"tag" gorm:"index"`
  42. Setting *string `json:"setting" gorm:"type:text"` // 渠道额外设置
  43. ParamOverride *string `json:"param_override" gorm:"type:text"`
  44. // add after v0.8.5
  45. ChannelInfo ChannelInfo `json:"channel_info" gorm:"type:json"`
  46. }
  47. type ChannelInfo struct {
  48. IsMultiKey bool `json:"is_multi_key"` // 是否多Key模式
  49. MultiKeySize int `json:"multi_key_size"` // 多Key模式下的Key数量
  50. MultiKeyStatusList map[int]int `json:"multi_key_status_list"` // key状态列表,key index -> status
  51. MultiKeyPollingIndex int `json:"multi_key_polling_index"` // 多Key模式下轮询的key索引
  52. MultiKeyMode constant.MultiKeyMode `json:"multi_key_mode"`
  53. }
  54. // Value implements driver.Valuer interface
  55. func (c ChannelInfo) Value() (driver.Value, error) {
  56. return common.Marshal(&c)
  57. }
  58. // Scan implements sql.Scanner interface
  59. func (c *ChannelInfo) Scan(value interface{}) error {
  60. bytesValue, _ := value.([]byte)
  61. return common.Unmarshal(bytesValue, c)
  62. }
  63. func (channel *Channel) getKeys() []string {
  64. if channel.Key == "" {
  65. return []string{}
  66. }
  67. // use \n to split keys
  68. keys := strings.Split(strings.Trim(channel.Key, "\n"), "\n")
  69. return keys
  70. }
  71. func (channel *Channel) GetNextEnabledKey() (string, int, *types.NewAPIError) {
  72. // If not in multi-key mode, return the original key string directly.
  73. if !channel.ChannelInfo.IsMultiKey {
  74. return channel.Key, 0, nil
  75. }
  76. // Obtain all keys (split by \n)
  77. keys := channel.getKeys()
  78. if len(keys) == 0 {
  79. // No keys available, return error, should disable the channel
  80. return "", 0, types.NewError(errors.New("no keys available"), types.ErrorCodeChannelNoAvailableKey)
  81. }
  82. statusList := channel.ChannelInfo.MultiKeyStatusList
  83. // helper to get key status, default to enabled when missing
  84. getStatus := func(idx int) int {
  85. if statusList == nil {
  86. return common.ChannelStatusEnabled
  87. }
  88. if status, ok := statusList[idx]; ok {
  89. return status
  90. }
  91. return common.ChannelStatusEnabled
  92. }
  93. // Collect indexes of enabled keys
  94. enabledIdx := make([]int, 0, len(keys))
  95. for i := range keys {
  96. if getStatus(i) == common.ChannelStatusEnabled {
  97. enabledIdx = append(enabledIdx, i)
  98. }
  99. }
  100. // If no specific status list or none enabled, fall back to first key
  101. if len(enabledIdx) == 0 {
  102. return keys[0], 0, nil
  103. }
  104. switch channel.ChannelInfo.MultiKeyMode {
  105. case constant.MultiKeyModeRandom:
  106. // Randomly pick one enabled key
  107. selectedIdx := enabledIdx[rand.Intn(len(enabledIdx))]
  108. return keys[selectedIdx], selectedIdx, nil
  109. case constant.MultiKeyModePolling:
  110. // Use channel-specific lock to ensure thread-safe polling
  111. lock := getChannelPollingLock(channel.Id)
  112. lock.Lock()
  113. defer lock.Unlock()
  114. channelInfo, err := CacheGetChannelInfo(channel.Id)
  115. if err != nil {
  116. return "", 0, types.NewError(err, types.ErrorCodeGetChannelFailed)
  117. }
  118. //println("before polling index:", channel.ChannelInfo.MultiKeyPollingIndex)
  119. defer func() {
  120. if common.DebugEnabled {
  121. println(fmt.Sprintf("channel %d polling index: %d", channel.Id, channel.ChannelInfo.MultiKeyPollingIndex))
  122. }
  123. if !common.MemoryCacheEnabled {
  124. _ = channel.SaveChannelInfo()
  125. } else {
  126. // CacheUpdateChannel(channel)
  127. }
  128. }()
  129. // Start from the saved polling index and look for the next enabled key
  130. start := channelInfo.MultiKeyPollingIndex
  131. if start < 0 || start >= len(keys) {
  132. start = 0
  133. }
  134. for i := 0; i < len(keys); i++ {
  135. idx := (start + i) % len(keys)
  136. if getStatus(idx) == common.ChannelStatusEnabled {
  137. // update polling index for next call (point to the next position)
  138. channel.ChannelInfo.MultiKeyPollingIndex = (idx + 1) % len(keys)
  139. return keys[idx], idx, nil
  140. }
  141. }
  142. // Fallback – should not happen, but return first enabled key
  143. return keys[enabledIdx[0]], enabledIdx[0], nil
  144. default:
  145. // Unknown mode, default to first enabled key (or original key string)
  146. return keys[enabledIdx[0]], enabledIdx[0], nil
  147. }
  148. }
  149. func (channel *Channel) SaveChannelInfo() error {
  150. return DB.Model(channel).Update("channel_info", channel.ChannelInfo).Error
  151. }
  152. func (channel *Channel) GetModels() []string {
  153. if channel.Models == "" {
  154. return []string{}
  155. }
  156. return strings.Split(strings.Trim(channel.Models, ","), ",")
  157. }
  158. func (channel *Channel) GetGroups() []string {
  159. if channel.Group == "" {
  160. return []string{}
  161. }
  162. groups := strings.Split(strings.Trim(channel.Group, ","), ",")
  163. for i, group := range groups {
  164. groups[i] = strings.TrimSpace(group)
  165. }
  166. return groups
  167. }
  168. func (channel *Channel) GetOtherInfo() map[string]interface{} {
  169. otherInfo := make(map[string]interface{})
  170. if channel.OtherInfo != "" {
  171. err := json.Unmarshal([]byte(channel.OtherInfo), &otherInfo)
  172. if err != nil {
  173. common.SysError("failed to unmarshal other info: " + err.Error())
  174. }
  175. }
  176. return otherInfo
  177. }
  178. func (channel *Channel) SetOtherInfo(otherInfo map[string]interface{}) {
  179. otherInfoBytes, err := json.Marshal(otherInfo)
  180. if err != nil {
  181. common.SysError("failed to marshal other info: " + err.Error())
  182. return
  183. }
  184. channel.OtherInfo = string(otherInfoBytes)
  185. }
  186. func (channel *Channel) GetTag() string {
  187. if channel.Tag == nil {
  188. return ""
  189. }
  190. return *channel.Tag
  191. }
  192. func (channel *Channel) SetTag(tag string) {
  193. channel.Tag = &tag
  194. }
  195. func (channel *Channel) GetAutoBan() bool {
  196. if channel.AutoBan == nil {
  197. return false
  198. }
  199. return *channel.AutoBan == 1
  200. }
  201. func (channel *Channel) Save() error {
  202. return DB.Save(channel).Error
  203. }
  204. func GetAllChannels(startIdx int, num int, selectAll bool, idSort bool) ([]*Channel, error) {
  205. var channels []*Channel
  206. var err error
  207. order := "priority desc"
  208. if idSort {
  209. order = "id desc"
  210. }
  211. if selectAll {
  212. err = DB.Order(order).Find(&channels).Error
  213. } else {
  214. err = DB.Order(order).Limit(num).Offset(startIdx).Omit("key").Find(&channels).Error
  215. }
  216. return channels, err
  217. }
  218. func GetChannelsByTag(tag string, idSort bool) ([]*Channel, error) {
  219. var channels []*Channel
  220. order := "priority desc"
  221. if idSort {
  222. order = "id desc"
  223. }
  224. err := DB.Where("tag = ?", tag).Order(order).Find(&channels).Error
  225. return channels, err
  226. }
  227. func SearchChannels(keyword string, group string, model string, idSort bool) ([]*Channel, error) {
  228. var channels []*Channel
  229. modelsCol := "`models`"
  230. // 如果是 PostgreSQL,使用双引号
  231. if common.UsingPostgreSQL {
  232. modelsCol = `"models"`
  233. }
  234. baseURLCol := "`base_url`"
  235. // 如果是 PostgreSQL,使用双引号
  236. if common.UsingPostgreSQL {
  237. baseURLCol = `"base_url"`
  238. }
  239. order := "priority desc"
  240. if idSort {
  241. order = "id desc"
  242. }
  243. // 构造基础查询
  244. baseQuery := DB.Model(&Channel{}).Omit("key")
  245. // 构造WHERE子句
  246. var whereClause string
  247. var args []interface{}
  248. if group != "" && group != "null" {
  249. var groupCondition string
  250. if common.UsingMySQL {
  251. groupCondition = `CONCAT(',', ` + commonGroupCol + `, ',') LIKE ?`
  252. } else {
  253. // sqlite, PostgreSQL
  254. groupCondition = `(',' || ` + commonGroupCol + ` || ',') LIKE ?`
  255. }
  256. whereClause = "(id = ? OR name LIKE ? OR " + commonKeyCol + " = ? OR " + baseURLCol + " LIKE ?) AND " + modelsCol + ` LIKE ? AND ` + groupCondition
  257. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+keyword+"%", "%"+model+"%", "%,"+group+",%")
  258. } else {
  259. whereClause = "(id = ? OR name LIKE ? OR " + commonKeyCol + " = ? OR " + baseURLCol + " LIKE ?) AND " + modelsCol + " LIKE ?"
  260. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+keyword+"%", "%"+model+"%")
  261. }
  262. // 执行查询
  263. err := baseQuery.Where(whereClause, args...).Order(order).Find(&channels).Error
  264. if err != nil {
  265. return nil, err
  266. }
  267. return channels, nil
  268. }
  269. func GetChannelById(id int, selectAll bool) (*Channel, error) {
  270. channel := &Channel{Id: id}
  271. var err error = nil
  272. if selectAll {
  273. err = DB.First(channel, "id = ?", id).Error
  274. } else {
  275. err = DB.Omit("key").First(channel, "id = ?", id).Error
  276. }
  277. if err != nil {
  278. return nil, err
  279. }
  280. if channel == nil {
  281. return nil, errors.New("channel not found")
  282. }
  283. return channel, nil
  284. }
  285. func BatchInsertChannels(channels []Channel) error {
  286. var err error
  287. err = DB.Create(&channels).Error
  288. if err != nil {
  289. return err
  290. }
  291. for _, channel_ := range channels {
  292. err = channel_.AddAbilities()
  293. if err != nil {
  294. return err
  295. }
  296. }
  297. return nil
  298. }
  299. func BatchDeleteChannels(ids []int) error {
  300. //使用事务 删除channel表和channel_ability表
  301. tx := DB.Begin()
  302. err := tx.Where("id in (?)", ids).Delete(&Channel{}).Error
  303. if err != nil {
  304. // 回滚事务
  305. tx.Rollback()
  306. return err
  307. }
  308. err = tx.Where("channel_id in (?)", ids).Delete(&Ability{}).Error
  309. if err != nil {
  310. // 回滚事务
  311. tx.Rollback()
  312. return err
  313. }
  314. // 提交事务
  315. tx.Commit()
  316. return err
  317. }
  318. func (channel *Channel) GetPriority() int64 {
  319. if channel.Priority == nil {
  320. return 0
  321. }
  322. return *channel.Priority
  323. }
  324. func (channel *Channel) GetWeight() int {
  325. if channel.Weight == nil {
  326. return 0
  327. }
  328. return int(*channel.Weight)
  329. }
  330. func (channel *Channel) GetBaseURL() string {
  331. if channel.BaseURL == nil {
  332. return ""
  333. }
  334. return *channel.BaseURL
  335. }
  336. func (channel *Channel) GetModelMapping() string {
  337. if channel.ModelMapping == nil {
  338. return ""
  339. }
  340. return *channel.ModelMapping
  341. }
  342. func (channel *Channel) GetStatusCodeMapping() string {
  343. if channel.StatusCodeMapping == nil {
  344. return ""
  345. }
  346. return *channel.StatusCodeMapping
  347. }
  348. func (channel *Channel) Insert() error {
  349. var err error
  350. err = DB.Create(channel).Error
  351. if err != nil {
  352. return err
  353. }
  354. err = channel.AddAbilities()
  355. return err
  356. }
  357. func (channel *Channel) Update() error {
  358. var err error
  359. err = DB.Model(channel).Updates(channel).Error
  360. if err != nil {
  361. return err
  362. }
  363. DB.Model(channel).First(channel, "id = ?", channel.Id)
  364. err = channel.UpdateAbilities(nil)
  365. return err
  366. }
  367. func (channel *Channel) UpdateResponseTime(responseTime int64) {
  368. err := DB.Model(channel).Select("response_time", "test_time").Updates(Channel{
  369. TestTime: common.GetTimestamp(),
  370. ResponseTime: int(responseTime),
  371. }).Error
  372. if err != nil {
  373. common.SysError("failed to update response time: " + err.Error())
  374. }
  375. }
  376. func (channel *Channel) UpdateBalance(balance float64) {
  377. err := DB.Model(channel).Select("balance_updated_time", "balance").Updates(Channel{
  378. BalanceUpdatedTime: common.GetTimestamp(),
  379. Balance: balance,
  380. }).Error
  381. if err != nil {
  382. common.SysError("failed to update balance: " + err.Error())
  383. }
  384. }
  385. func (channel *Channel) Delete() error {
  386. var err error
  387. err = DB.Delete(channel).Error
  388. if err != nil {
  389. return err
  390. }
  391. err = channel.DeleteAbilities()
  392. return err
  393. }
  394. var channelStatusLock sync.Mutex
  395. // channelPollingLocks stores locks for each channel.id to ensure thread-safe polling
  396. var channelPollingLocks sync.Map
  397. // getChannelPollingLock returns or creates a mutex for the given channel ID
  398. func getChannelPollingLock(channelId int) *sync.Mutex {
  399. if lock, exists := channelPollingLocks.Load(channelId); exists {
  400. return lock.(*sync.Mutex)
  401. }
  402. // Create new lock for this channel
  403. newLock := &sync.Mutex{}
  404. actual, _ := channelPollingLocks.LoadOrStore(channelId, newLock)
  405. return actual.(*sync.Mutex)
  406. }
  407. // CleanupChannelPollingLocks removes locks for channels that no longer exist
  408. // This is optional and can be called periodically to prevent memory leaks
  409. func CleanupChannelPollingLocks() {
  410. var activeChannelIds []int
  411. DB.Model(&Channel{}).Pluck("id", &activeChannelIds)
  412. activeChannelSet := make(map[int]bool)
  413. for _, id := range activeChannelIds {
  414. activeChannelSet[id] = true
  415. }
  416. channelPollingLocks.Range(func(key, value interface{}) bool {
  417. channelId := key.(int)
  418. if !activeChannelSet[channelId] {
  419. channelPollingLocks.Delete(channelId)
  420. }
  421. return true
  422. })
  423. }
  424. func handlerMultiKeyUpdate(channel *Channel, usingKey string, status int) {
  425. keys := channel.getKeys()
  426. if len(keys) == 0 {
  427. channel.Status = status
  428. } else {
  429. var keyIndex int
  430. for i, key := range keys {
  431. if key == usingKey {
  432. keyIndex = i
  433. break
  434. }
  435. }
  436. if channel.ChannelInfo.MultiKeyStatusList == nil {
  437. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  438. }
  439. if status == common.ChannelStatusEnabled {
  440. delete(channel.ChannelInfo.MultiKeyStatusList, keyIndex)
  441. } else {
  442. channel.ChannelInfo.MultiKeyStatusList[keyIndex] = status
  443. }
  444. if len(channel.ChannelInfo.MultiKeyStatusList) >= channel.ChannelInfo.MultiKeySize {
  445. channel.Status = common.ChannelStatusAutoDisabled
  446. info := channel.GetOtherInfo()
  447. info["status_reason"] = "All keys are disabled"
  448. info["status_time"] = common.GetTimestamp()
  449. channel.SetOtherInfo(info)
  450. }
  451. }
  452. }
  453. func UpdateChannelStatus(channelId int, usingKey string, status int, reason string) bool {
  454. if common.MemoryCacheEnabled {
  455. channelStatusLock.Lock()
  456. defer channelStatusLock.Unlock()
  457. channelCache, _ := CacheGetChannel(channelId)
  458. if channelCache == nil {
  459. return false
  460. }
  461. if channelCache.ChannelInfo.IsMultiKey {
  462. // 如果是多Key模式,更新缓存中的状态
  463. handlerMultiKeyUpdate(channelCache, usingKey, status)
  464. //CacheUpdateChannel(channelCache)
  465. //return true
  466. } else {
  467. // 如果缓存渠道存在,且状态已是目标状态,直接返回
  468. if channelCache.Status == status {
  469. return false
  470. }
  471. // 如果缓存渠道不存在(说明已经被禁用),且要设置的状态不为启用,直接返回
  472. if status != common.ChannelStatusEnabled {
  473. return false
  474. }
  475. CacheUpdateChannelStatus(channelId, status)
  476. }
  477. }
  478. shouldUpdateAbilities := false
  479. defer func() {
  480. if shouldUpdateAbilities {
  481. err := UpdateAbilityStatus(channelId, status == common.ChannelStatusEnabled)
  482. if err != nil {
  483. common.SysError("failed to update ability status: " + err.Error())
  484. }
  485. }
  486. }()
  487. channel, err := GetChannelById(channelId, true)
  488. if err != nil {
  489. return false
  490. } else {
  491. if channel.Status == status {
  492. return false
  493. }
  494. if channel.ChannelInfo.IsMultiKey {
  495. beforeStatus := channel.Status
  496. handlerMultiKeyUpdate(channel, usingKey, status)
  497. if beforeStatus != channel.Status {
  498. shouldUpdateAbilities = true
  499. }
  500. } else {
  501. info := channel.GetOtherInfo()
  502. info["status_reason"] = reason
  503. info["status_time"] = common.GetTimestamp()
  504. channel.SetOtherInfo(info)
  505. channel.Status = status
  506. shouldUpdateAbilities = true
  507. }
  508. err = channel.Save()
  509. if err != nil {
  510. common.SysError("failed to update channel status: " + err.Error())
  511. return false
  512. }
  513. }
  514. return true
  515. }
  516. func EnableChannelByTag(tag string) error {
  517. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusEnabled).Error
  518. if err != nil {
  519. return err
  520. }
  521. err = UpdateAbilityStatusByTag(tag, true)
  522. return err
  523. }
  524. func DisableChannelByTag(tag string) error {
  525. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusManuallyDisabled).Error
  526. if err != nil {
  527. return err
  528. }
  529. err = UpdateAbilityStatusByTag(tag, false)
  530. return err
  531. }
  532. func EditChannelByTag(tag string, newTag *string, modelMapping *string, models *string, group *string, priority *int64, weight *uint) error {
  533. updateData := Channel{}
  534. shouldReCreateAbilities := false
  535. updatedTag := tag
  536. // 如果 newTag 不为空且不等于 tag,则更新 tag
  537. if newTag != nil && *newTag != tag {
  538. updateData.Tag = newTag
  539. updatedTag = *newTag
  540. }
  541. if modelMapping != nil && *modelMapping != "" {
  542. updateData.ModelMapping = modelMapping
  543. }
  544. if models != nil && *models != "" {
  545. shouldReCreateAbilities = true
  546. updateData.Models = *models
  547. }
  548. if group != nil && *group != "" {
  549. shouldReCreateAbilities = true
  550. updateData.Group = *group
  551. }
  552. if priority != nil {
  553. updateData.Priority = priority
  554. }
  555. if weight != nil {
  556. updateData.Weight = weight
  557. }
  558. err := DB.Model(&Channel{}).Where("tag = ?", tag).Updates(updateData).Error
  559. if err != nil {
  560. return err
  561. }
  562. if shouldReCreateAbilities {
  563. channels, err := GetChannelsByTag(updatedTag, false)
  564. if err == nil {
  565. for _, channel := range channels {
  566. err = channel.UpdateAbilities(nil)
  567. if err != nil {
  568. common.SysError("failed to update abilities: " + err.Error())
  569. }
  570. }
  571. }
  572. } else {
  573. err := UpdateAbilityByTag(tag, newTag, priority, weight)
  574. if err != nil {
  575. return err
  576. }
  577. }
  578. return nil
  579. }
  580. func UpdateChannelUsedQuota(id int, quota int) {
  581. if common.BatchUpdateEnabled {
  582. addNewRecord(BatchUpdateTypeChannelUsedQuota, id, quota)
  583. return
  584. }
  585. updateChannelUsedQuota(id, quota)
  586. }
  587. func updateChannelUsedQuota(id int, quota int) {
  588. err := DB.Model(&Channel{}).Where("id = ?", id).Update("used_quota", gorm.Expr("used_quota + ?", quota)).Error
  589. if err != nil {
  590. common.SysError("failed to update channel used quota: " + err.Error())
  591. }
  592. }
  593. func DeleteChannelByStatus(status int64) (int64, error) {
  594. result := DB.Where("status = ?", status).Delete(&Channel{})
  595. return result.RowsAffected, result.Error
  596. }
  597. func DeleteDisabledChannel() (int64, error) {
  598. result := DB.Where("status = ? or status = ?", common.ChannelStatusAutoDisabled, common.ChannelStatusManuallyDisabled).Delete(&Channel{})
  599. return result.RowsAffected, result.Error
  600. }
  601. func GetPaginatedTags(offset int, limit int) ([]*string, error) {
  602. var tags []*string
  603. err := DB.Model(&Channel{}).Select("DISTINCT tag").Where("tag != ''").Offset(offset).Limit(limit).Find(&tags).Error
  604. return tags, err
  605. }
  606. func SearchTags(keyword string, group string, model string, idSort bool) ([]*string, error) {
  607. var tags []*string
  608. modelsCol := "`models`"
  609. // 如果是 PostgreSQL,使用双引号
  610. if common.UsingPostgreSQL {
  611. modelsCol = `"models"`
  612. }
  613. baseURLCol := "`base_url`"
  614. // 如果是 PostgreSQL,使用双引号
  615. if common.UsingPostgreSQL {
  616. baseURLCol = `"base_url"`
  617. }
  618. order := "priority desc"
  619. if idSort {
  620. order = "id desc"
  621. }
  622. // 构造基础查询
  623. baseQuery := DB.Model(&Channel{}).Omit("key")
  624. // 构造WHERE子句
  625. var whereClause string
  626. var args []interface{}
  627. if group != "" && group != "null" {
  628. var groupCondition string
  629. if common.UsingMySQL {
  630. groupCondition = `CONCAT(',', ` + commonGroupCol + `, ',') LIKE ?`
  631. } else {
  632. // sqlite, PostgreSQL
  633. groupCondition = `(',' || ` + commonGroupCol + ` || ',') LIKE ?`
  634. }
  635. whereClause = "(id = ? OR name LIKE ? OR " + commonKeyCol + " = ? OR " + baseURLCol + " LIKE ?) AND " + modelsCol + ` LIKE ? AND ` + groupCondition
  636. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+keyword+"%", "%"+model+"%", "%,"+group+",%")
  637. } else {
  638. whereClause = "(id = ? OR name LIKE ? OR " + commonKeyCol + " = ? OR " + baseURLCol + " LIKE ?) AND " + modelsCol + " LIKE ?"
  639. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+keyword+"%", "%"+model+"%")
  640. }
  641. subQuery := baseQuery.Where(whereClause, args...).
  642. Select("tag").
  643. Where("tag != ''").
  644. Order(order)
  645. err := DB.Table("(?) as sub", subQuery).
  646. Select("DISTINCT tag").
  647. Find(&tags).Error
  648. if err != nil {
  649. return nil, err
  650. }
  651. return tags, nil
  652. }
  653. func (channel *Channel) ValidateSettings() error {
  654. channelParams := &dto.ChannelSettings{}
  655. if channel.Setting != nil && *channel.Setting != "" {
  656. err := json.Unmarshal([]byte(*channel.Setting), channelParams)
  657. if err != nil {
  658. return err
  659. }
  660. }
  661. return nil
  662. }
  663. func (channel *Channel) GetSetting() dto.ChannelSettings {
  664. setting := dto.ChannelSettings{}
  665. if channel.Setting != nil && *channel.Setting != "" {
  666. err := json.Unmarshal([]byte(*channel.Setting), &setting)
  667. if err != nil {
  668. common.SysError("failed to unmarshal setting: " + err.Error())
  669. channel.Setting = nil // 清空设置以避免后续错误
  670. _ = channel.Save() // 保存修改
  671. }
  672. }
  673. return setting
  674. }
  675. func (channel *Channel) SetSetting(setting dto.ChannelSettings) {
  676. settingBytes, err := json.Marshal(setting)
  677. if err != nil {
  678. common.SysError("failed to marshal setting: " + err.Error())
  679. return
  680. }
  681. channel.Setting = common.GetPointer[string](string(settingBytes))
  682. }
  683. func (channel *Channel) GetParamOverride() map[string]interface{} {
  684. paramOverride := make(map[string]interface{})
  685. if channel.ParamOverride != nil && *channel.ParamOverride != "" {
  686. err := json.Unmarshal([]byte(*channel.ParamOverride), &paramOverride)
  687. if err != nil {
  688. common.SysError("failed to unmarshal param override: " + err.Error())
  689. }
  690. }
  691. return paramOverride
  692. }
  693. func GetChannelsByIds(ids []int) ([]*Channel, error) {
  694. var channels []*Channel
  695. err := DB.Where("id in (?)", ids).Find(&channels).Error
  696. return channels, err
  697. }
  698. func BatchSetChannelTag(ids []int, tag *string) error {
  699. // 开启事务
  700. tx := DB.Begin()
  701. if tx.Error != nil {
  702. return tx.Error
  703. }
  704. // 更新标签
  705. err := tx.Model(&Channel{}).Where("id in (?)", ids).Update("tag", tag).Error
  706. if err != nil {
  707. tx.Rollback()
  708. return err
  709. }
  710. // update ability status
  711. channels, err := GetChannelsByIds(ids)
  712. if err != nil {
  713. tx.Rollback()
  714. return err
  715. }
  716. for _, channel := range channels {
  717. err = channel.UpdateAbilities(tx)
  718. if err != nil {
  719. tx.Rollback()
  720. return err
  721. }
  722. }
  723. // 提交事务
  724. return tx.Commit().Error
  725. }
  726. // CountAllChannels returns total channels in DB
  727. func CountAllChannels() (int64, error) {
  728. var total int64
  729. err := DB.Model(&Channel{}).Count(&total).Error
  730. return total, err
  731. }
  732. // CountAllTags returns number of non-empty distinct tags
  733. func CountAllTags() (int64, error) {
  734. var total int64
  735. err := DB.Model(&Channel{}).Where("tag is not null AND tag != ''").Distinct("tag").Count(&total).Error
  736. return total, err
  737. }
  738. // Get channels of specified type with pagination
  739. func GetChannelsByType(startIdx int, num int, idSort bool, channelType int) ([]*Channel, error) {
  740. var channels []*Channel
  741. order := "priority desc"
  742. if idSort {
  743. order = "id desc"
  744. }
  745. err := DB.Where("type = ?", channelType).Order(order).Limit(num).Offset(startIdx).Omit("key").Find(&channels).Error
  746. return channels, err
  747. }
  748. // Count channels of specific type
  749. func CountChannelsByType(channelType int) (int64, error) {
  750. var count int64
  751. err := DB.Model(&Channel{}).Where("type = ?", channelType).Count(&count).Error
  752. return count, err
  753. }
  754. // Return map[type]count for all channels
  755. func CountChannelsGroupByType() (map[int64]int64, error) {
  756. type result struct {
  757. Type int64 `gorm:"column:type"`
  758. Count int64 `gorm:"column:count"`
  759. }
  760. var results []result
  761. err := DB.Model(&Channel{}).Select("type, count(*) as count").Group("type").Find(&results).Error
  762. if err != nil {
  763. return nil, err
  764. }
  765. counts := make(map[int64]int64)
  766. for _, r := range results {
  767. counts[r.Type] = r.Count
  768. }
  769. return counts, nil
  770. }