channel.go 27 KB

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