channel.go 20 KB

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