channel.go 22 KB

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