channel.go 20 KB

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