channel.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "one-api/common"
  7. "one-api/constant"
  8. "one-api/model"
  9. "strconv"
  10. "strings"
  11. "github.com/gin-gonic/gin"
  12. )
  13. type OpenAIModel struct {
  14. ID string `json:"id"`
  15. Object string `json:"object"`
  16. Created int64 `json:"created"`
  17. OwnedBy string `json:"owned_by"`
  18. Permission []struct {
  19. ID string `json:"id"`
  20. Object string `json:"object"`
  21. Created int64 `json:"created"`
  22. AllowCreateEngine bool `json:"allow_create_engine"`
  23. AllowSampling bool `json:"allow_sampling"`
  24. AllowLogprobs bool `json:"allow_logprobs"`
  25. AllowSearchIndices bool `json:"allow_search_indices"`
  26. AllowView bool `json:"allow_view"`
  27. AllowFineTuning bool `json:"allow_fine_tuning"`
  28. Organization string `json:"organization"`
  29. Group string `json:"group"`
  30. IsBlocking bool `json:"is_blocking"`
  31. } `json:"permission"`
  32. Root string `json:"root"`
  33. Parent string `json:"parent"`
  34. }
  35. type OpenAIModelsResponse struct {
  36. Data []OpenAIModel `json:"data"`
  37. Success bool `json:"success"`
  38. }
  39. func parseStatusFilter(statusParam string) int {
  40. switch strings.ToLower(statusParam) {
  41. case "enabled", "1":
  42. return common.ChannelStatusEnabled
  43. case "disabled", "0":
  44. return 0
  45. default:
  46. return -1
  47. }
  48. }
  49. func clearChannelInfo(channel *model.Channel) {
  50. if channel.ChannelInfo.IsMultiKey {
  51. channel.ChannelInfo.MultiKeyDisabledReason = nil
  52. channel.ChannelInfo.MultiKeyDisabledTime = nil
  53. }
  54. }
  55. func GetAllChannels(c *gin.Context) {
  56. pageInfo := common.GetPageQuery(c)
  57. channelData := make([]*model.Channel, 0)
  58. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  59. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  60. statusParam := c.Query("status")
  61. // statusFilter: -1 all, 1 enabled, 0 disabled (include auto & manual)
  62. statusFilter := parseStatusFilter(statusParam)
  63. // type filter
  64. typeStr := c.Query("type")
  65. typeFilter := -1
  66. if typeStr != "" {
  67. if t, err := strconv.Atoi(typeStr); err == nil {
  68. typeFilter = t
  69. }
  70. }
  71. var total int64
  72. if enableTagMode {
  73. tags, err := model.GetPaginatedTags(pageInfo.GetStartIdx(), pageInfo.GetPageSize())
  74. if err != nil {
  75. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  76. return
  77. }
  78. for _, tag := range tags {
  79. if tag == nil || *tag == "" {
  80. continue
  81. }
  82. tagChannels, err := model.GetChannelsByTag(*tag, idSort)
  83. if err != nil {
  84. continue
  85. }
  86. filtered := make([]*model.Channel, 0)
  87. for _, ch := range tagChannels {
  88. if statusFilter == common.ChannelStatusEnabled && ch.Status != common.ChannelStatusEnabled {
  89. continue
  90. }
  91. if statusFilter == 0 && ch.Status == common.ChannelStatusEnabled {
  92. continue
  93. }
  94. if typeFilter >= 0 && ch.Type != typeFilter {
  95. continue
  96. }
  97. filtered = append(filtered, ch)
  98. }
  99. channelData = append(channelData, filtered...)
  100. }
  101. total, _ = model.CountAllTags()
  102. } else {
  103. baseQuery := model.DB.Model(&model.Channel{})
  104. if typeFilter >= 0 {
  105. baseQuery = baseQuery.Where("type = ?", typeFilter)
  106. }
  107. if statusFilter == common.ChannelStatusEnabled {
  108. baseQuery = baseQuery.Where("status = ?", common.ChannelStatusEnabled)
  109. } else if statusFilter == 0 {
  110. baseQuery = baseQuery.Where("status != ?", common.ChannelStatusEnabled)
  111. }
  112. baseQuery.Count(&total)
  113. order := "priority desc"
  114. if idSort {
  115. order = "id desc"
  116. }
  117. err := baseQuery.Order(order).Limit(pageInfo.GetPageSize()).Offset(pageInfo.GetStartIdx()).Omit("key").Find(&channelData).Error
  118. if err != nil {
  119. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  120. return
  121. }
  122. }
  123. for _, datum := range channelData {
  124. clearChannelInfo(datum)
  125. }
  126. countQuery := model.DB.Model(&model.Channel{})
  127. if statusFilter == common.ChannelStatusEnabled {
  128. countQuery = countQuery.Where("status = ?", common.ChannelStatusEnabled)
  129. } else if statusFilter == 0 {
  130. countQuery = countQuery.Where("status != ?", common.ChannelStatusEnabled)
  131. }
  132. var results []struct {
  133. Type int64
  134. Count int64
  135. }
  136. _ = countQuery.Select("type, count(*) as count").Group("type").Find(&results).Error
  137. typeCounts := make(map[int64]int64)
  138. for _, r := range results {
  139. typeCounts[r.Type] = r.Count
  140. }
  141. common.ApiSuccess(c, gin.H{
  142. "items": channelData,
  143. "total": total,
  144. "page": pageInfo.GetPage(),
  145. "page_size": pageInfo.GetPageSize(),
  146. "type_counts": typeCounts,
  147. })
  148. return
  149. }
  150. func FetchUpstreamModels(c *gin.Context) {
  151. id, err := strconv.Atoi(c.Param("id"))
  152. if err != nil {
  153. common.ApiError(c, err)
  154. return
  155. }
  156. channel, err := model.GetChannelById(id, true)
  157. if err != nil {
  158. common.ApiError(c, err)
  159. return
  160. }
  161. baseURL := constant.ChannelBaseURLs[channel.Type]
  162. if channel.GetBaseURL() != "" {
  163. baseURL = channel.GetBaseURL()
  164. }
  165. var url string
  166. switch channel.Type {
  167. case constant.ChannelTypeGemini:
  168. // curl https://example.com/v1beta/models?key=$GEMINI_API_KEY
  169. url = fmt.Sprintf("%s/v1beta/openai/models", baseURL) // Remove key in url since we need to use AuthHeader
  170. case constant.ChannelTypeAli:
  171. url = fmt.Sprintf("%s/compatible-mode/v1/models", baseURL)
  172. default:
  173. url = fmt.Sprintf("%s/v1/models", baseURL)
  174. }
  175. // 获取响应体 - 根据渠道类型决定是否添加 AuthHeader
  176. var body []byte
  177. key := strings.Split(channel.Key, "\n")[0]
  178. if channel.Type == constant.ChannelTypeGemini {
  179. body, err = GetResponseBody("GET", url, channel, GetAuthHeader(key)) // Use AuthHeader since Gemini now forces it
  180. } else {
  181. body, err = GetResponseBody("GET", url, channel, GetAuthHeader(key))
  182. }
  183. if err != nil {
  184. common.ApiError(c, err)
  185. return
  186. }
  187. var result OpenAIModelsResponse
  188. if err = json.Unmarshal(body, &result); err != nil {
  189. c.JSON(http.StatusOK, gin.H{
  190. "success": false,
  191. "message": fmt.Sprintf("解析响应失败: %s", err.Error()),
  192. })
  193. return
  194. }
  195. var ids []string
  196. for _, model := range result.Data {
  197. id := model.ID
  198. if channel.Type == constant.ChannelTypeGemini {
  199. id = strings.TrimPrefix(id, "models/")
  200. }
  201. ids = append(ids, id)
  202. }
  203. c.JSON(http.StatusOK, gin.H{
  204. "success": true,
  205. "message": "",
  206. "data": ids,
  207. })
  208. }
  209. func FixChannelsAbilities(c *gin.Context) {
  210. success, fails, err := model.FixAbility()
  211. if err != nil {
  212. common.ApiError(c, err)
  213. return
  214. }
  215. c.JSON(http.StatusOK, gin.H{
  216. "success": true,
  217. "message": "",
  218. "data": gin.H{
  219. "success": success,
  220. "fails": fails,
  221. },
  222. })
  223. }
  224. func SearchChannels(c *gin.Context) {
  225. keyword := c.Query("keyword")
  226. group := c.Query("group")
  227. modelKeyword := c.Query("model")
  228. statusParam := c.Query("status")
  229. statusFilter := parseStatusFilter(statusParam)
  230. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  231. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  232. channelData := make([]*model.Channel, 0)
  233. if enableTagMode {
  234. tags, err := model.SearchTags(keyword, group, modelKeyword, idSort)
  235. if err != nil {
  236. c.JSON(http.StatusOK, gin.H{
  237. "success": false,
  238. "message": err.Error(),
  239. })
  240. return
  241. }
  242. for _, tag := range tags {
  243. if tag != nil && *tag != "" {
  244. tagChannel, err := model.GetChannelsByTag(*tag, idSort)
  245. if err == nil {
  246. channelData = append(channelData, tagChannel...)
  247. }
  248. }
  249. }
  250. } else {
  251. channels, err := model.SearchChannels(keyword, group, modelKeyword, idSort)
  252. if err != nil {
  253. c.JSON(http.StatusOK, gin.H{
  254. "success": false,
  255. "message": err.Error(),
  256. })
  257. return
  258. }
  259. channelData = channels
  260. }
  261. if statusFilter == common.ChannelStatusEnabled || statusFilter == 0 {
  262. filtered := make([]*model.Channel, 0, len(channelData))
  263. for _, ch := range channelData {
  264. if statusFilter == common.ChannelStatusEnabled && ch.Status != common.ChannelStatusEnabled {
  265. continue
  266. }
  267. if statusFilter == 0 && ch.Status == common.ChannelStatusEnabled {
  268. continue
  269. }
  270. filtered = append(filtered, ch)
  271. }
  272. channelData = filtered
  273. }
  274. // calculate type counts for search results
  275. typeCounts := make(map[int64]int64)
  276. for _, channel := range channelData {
  277. typeCounts[int64(channel.Type)]++
  278. }
  279. typeParam := c.Query("type")
  280. typeFilter := -1
  281. if typeParam != "" {
  282. if tp, err := strconv.Atoi(typeParam); err == nil {
  283. typeFilter = tp
  284. }
  285. }
  286. if typeFilter >= 0 {
  287. filtered := make([]*model.Channel, 0, len(channelData))
  288. for _, ch := range channelData {
  289. if ch.Type == typeFilter {
  290. filtered = append(filtered, ch)
  291. }
  292. }
  293. channelData = filtered
  294. }
  295. page, _ := strconv.Atoi(c.DefaultQuery("p", "1"))
  296. pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
  297. if page < 1 {
  298. page = 1
  299. }
  300. if pageSize <= 0 {
  301. pageSize = 20
  302. }
  303. total := len(channelData)
  304. startIdx := (page - 1) * pageSize
  305. if startIdx > total {
  306. startIdx = total
  307. }
  308. endIdx := startIdx + pageSize
  309. if endIdx > total {
  310. endIdx = total
  311. }
  312. pagedData := channelData[startIdx:endIdx]
  313. for _, datum := range pagedData {
  314. clearChannelInfo(datum)
  315. }
  316. c.JSON(http.StatusOK, gin.H{
  317. "success": true,
  318. "message": "",
  319. "data": gin.H{
  320. "items": pagedData,
  321. "total": total,
  322. "type_counts": typeCounts,
  323. },
  324. })
  325. return
  326. }
  327. func GetChannel(c *gin.Context) {
  328. id, err := strconv.Atoi(c.Param("id"))
  329. if err != nil {
  330. common.ApiError(c, err)
  331. return
  332. }
  333. channel, err := model.GetChannelById(id, false)
  334. if err != nil {
  335. common.ApiError(c, err)
  336. return
  337. }
  338. if channel != nil {
  339. clearChannelInfo(channel)
  340. }
  341. c.JSON(http.StatusOK, gin.H{
  342. "success": true,
  343. "message": "",
  344. "data": channel,
  345. })
  346. return
  347. }
  348. // GetChannelKey 验证2FA后获取渠道密钥
  349. func GetChannelKey(c *gin.Context) {
  350. type GetChannelKeyRequest struct {
  351. Code string `json:"code" binding:"required"`
  352. }
  353. var req GetChannelKeyRequest
  354. if err := c.ShouldBindJSON(&req); err != nil {
  355. common.ApiError(c, fmt.Errorf("参数错误: %v", err))
  356. return
  357. }
  358. userId := c.GetInt("id")
  359. channelId, err := strconv.Atoi(c.Param("id"))
  360. if err != nil {
  361. common.ApiError(c, fmt.Errorf("渠道ID格式错误: %v", err))
  362. return
  363. }
  364. // 获取2FA记录并验证
  365. twoFA, err := model.GetTwoFAByUserId(userId)
  366. if err != nil {
  367. common.ApiError(c, fmt.Errorf("获取2FA信息失败: %v", err))
  368. return
  369. }
  370. if twoFA == nil || !twoFA.IsEnabled {
  371. common.ApiError(c, fmt.Errorf("用户未启用2FA,无法查看密钥"))
  372. return
  373. }
  374. // 统一的2FA验证逻辑
  375. if !validateTwoFactorAuth(twoFA, req.Code) {
  376. common.ApiError(c, fmt.Errorf("验证码或备用码错误,请重试"))
  377. return
  378. }
  379. // 获取渠道信息(包含密钥)
  380. channel, err := model.GetChannelById(channelId, true)
  381. if err != nil {
  382. common.ApiError(c, fmt.Errorf("获取渠道信息失败: %v", err))
  383. return
  384. }
  385. if channel == nil {
  386. common.ApiError(c, fmt.Errorf("渠道不存在"))
  387. return
  388. }
  389. // 记录操作日志
  390. model.RecordLog(userId, model.LogTypeSystem, fmt.Sprintf("查看渠道密钥信息 (渠道ID: %d)", channelId))
  391. // 统一的成功响应格式
  392. c.JSON(http.StatusOK, gin.H{
  393. "success": true,
  394. "message": "验证成功",
  395. "data": map[string]interface{}{
  396. "key": channel.Key,
  397. },
  398. })
  399. }
  400. // validateTwoFactorAuth 统一的2FA验证函数
  401. func validateTwoFactorAuth(twoFA *model.TwoFA, code string) bool {
  402. // 尝试验证TOTP
  403. if cleanCode, err := common.ValidateNumericCode(code); err == nil {
  404. if isValid, _ := twoFA.ValidateTOTPAndUpdateUsage(cleanCode); isValid {
  405. return true
  406. }
  407. }
  408. // 尝试验证备用码
  409. if isValid, err := twoFA.ValidateBackupCodeAndUpdateUsage(code); err == nil && isValid {
  410. return true
  411. }
  412. return false
  413. }
  414. // validateChannel 通用的渠道校验函数
  415. func validateChannel(channel *model.Channel, isAdd bool) error {
  416. // 校验 channel settings
  417. if err := channel.ValidateSettings(); err != nil {
  418. return fmt.Errorf("渠道额外设置[channel setting] 格式错误:%s", err.Error())
  419. }
  420. // 如果是添加操作,检查 channel 和 key 是否为空
  421. if isAdd {
  422. if channel == nil || channel.Key == "" {
  423. return fmt.Errorf("channel cannot be empty")
  424. }
  425. // 检查模型名称长度是否超过 255
  426. for _, m := range channel.GetModels() {
  427. if len(m) > 255 {
  428. return fmt.Errorf("模型名称过长: %s", m)
  429. }
  430. }
  431. }
  432. // VertexAI 特殊校验
  433. if channel.Type == constant.ChannelTypeVertexAi {
  434. if channel.Other == "" {
  435. return fmt.Errorf("部署地区不能为空")
  436. }
  437. regionMap, err := common.StrToMap(channel.Other)
  438. if err != nil {
  439. return fmt.Errorf("部署地区必须是标准的Json格式,例如{\"default\": \"us-central1\", \"region2\": \"us-east1\"}")
  440. }
  441. if regionMap["default"] == nil {
  442. return fmt.Errorf("部署地区必须包含default字段")
  443. }
  444. }
  445. return nil
  446. }
  447. type AddChannelRequest struct {
  448. Mode string `json:"mode"`
  449. MultiKeyMode constant.MultiKeyMode `json:"multi_key_mode"`
  450. Channel *model.Channel `json:"channel"`
  451. }
  452. func getVertexArrayKeys(keys string) ([]string, error) {
  453. if keys == "" {
  454. return nil, nil
  455. }
  456. var keyArray []interface{}
  457. err := common.Unmarshal([]byte(keys), &keyArray)
  458. if err != nil {
  459. return nil, fmt.Errorf("批量添加 Vertex AI 必须使用标准的JsonArray格式,例如[{key1}, {key2}...],请检查输入: %w", err)
  460. }
  461. cleanKeys := make([]string, 0, len(keyArray))
  462. for _, key := range keyArray {
  463. var keyStr string
  464. switch v := key.(type) {
  465. case string:
  466. keyStr = strings.TrimSpace(v)
  467. default:
  468. bytes, err := json.Marshal(v)
  469. if err != nil {
  470. return nil, fmt.Errorf("Vertex AI key JSON 编码失败: %w", err)
  471. }
  472. keyStr = string(bytes)
  473. }
  474. if keyStr != "" {
  475. cleanKeys = append(cleanKeys, keyStr)
  476. }
  477. }
  478. if len(cleanKeys) == 0 {
  479. return nil, fmt.Errorf("批量添加 Vertex AI 的 keys 不能为空")
  480. }
  481. return cleanKeys, nil
  482. }
  483. func AddChannel(c *gin.Context) {
  484. addChannelRequest := AddChannelRequest{}
  485. err := c.ShouldBindJSON(&addChannelRequest)
  486. if err != nil {
  487. common.ApiError(c, err)
  488. return
  489. }
  490. // 使用统一的校验函数
  491. if err := validateChannel(addChannelRequest.Channel, true); err != nil {
  492. c.JSON(http.StatusOK, gin.H{
  493. "success": false,
  494. "message": err.Error(),
  495. })
  496. return
  497. }
  498. addChannelRequest.Channel.CreatedTime = common.GetTimestamp()
  499. keys := make([]string, 0)
  500. switch addChannelRequest.Mode {
  501. case "multi_to_single":
  502. addChannelRequest.Channel.ChannelInfo.IsMultiKey = true
  503. addChannelRequest.Channel.ChannelInfo.MultiKeyMode = addChannelRequest.MultiKeyMode
  504. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi {
  505. array, err := getVertexArrayKeys(addChannelRequest.Channel.Key)
  506. if err != nil {
  507. c.JSON(http.StatusOK, gin.H{
  508. "success": false,
  509. "message": err.Error(),
  510. })
  511. return
  512. }
  513. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(array)
  514. addChannelRequest.Channel.Key = strings.Join(array, "\n")
  515. } else {
  516. cleanKeys := make([]string, 0)
  517. for _, key := range strings.Split(addChannelRequest.Channel.Key, "\n") {
  518. if key == "" {
  519. continue
  520. }
  521. key = strings.TrimSpace(key)
  522. cleanKeys = append(cleanKeys, key)
  523. }
  524. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(cleanKeys)
  525. addChannelRequest.Channel.Key = strings.Join(cleanKeys, "\n")
  526. }
  527. keys = []string{addChannelRequest.Channel.Key}
  528. case "batch":
  529. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi {
  530. // multi json
  531. keys, err = getVertexArrayKeys(addChannelRequest.Channel.Key)
  532. if err != nil {
  533. c.JSON(http.StatusOK, gin.H{
  534. "success": false,
  535. "message": err.Error(),
  536. })
  537. return
  538. }
  539. } else {
  540. keys = strings.Split(addChannelRequest.Channel.Key, "\n")
  541. }
  542. case "single":
  543. keys = []string{addChannelRequest.Channel.Key}
  544. default:
  545. c.JSON(http.StatusOK, gin.H{
  546. "success": false,
  547. "message": "不支持的添加模式",
  548. })
  549. return
  550. }
  551. channels := make([]model.Channel, 0, len(keys))
  552. for _, key := range keys {
  553. if key == "" {
  554. continue
  555. }
  556. localChannel := addChannelRequest.Channel
  557. localChannel.Key = key
  558. channels = append(channels, *localChannel)
  559. }
  560. err = model.BatchInsertChannels(channels)
  561. if err != nil {
  562. common.ApiError(c, err)
  563. return
  564. }
  565. c.JSON(http.StatusOK, gin.H{
  566. "success": true,
  567. "message": "",
  568. })
  569. return
  570. }
  571. func DeleteChannel(c *gin.Context) {
  572. id, _ := strconv.Atoi(c.Param("id"))
  573. channel := model.Channel{Id: id}
  574. err := channel.Delete()
  575. if err != nil {
  576. common.ApiError(c, err)
  577. return
  578. }
  579. model.InitChannelCache()
  580. c.JSON(http.StatusOK, gin.H{
  581. "success": true,
  582. "message": "",
  583. })
  584. return
  585. }
  586. func DeleteDisabledChannel(c *gin.Context) {
  587. rows, err := model.DeleteDisabledChannel()
  588. if err != nil {
  589. common.ApiError(c, err)
  590. return
  591. }
  592. model.InitChannelCache()
  593. c.JSON(http.StatusOK, gin.H{
  594. "success": true,
  595. "message": "",
  596. "data": rows,
  597. })
  598. return
  599. }
  600. type ChannelTag struct {
  601. Tag string `json:"tag"`
  602. NewTag *string `json:"new_tag"`
  603. Priority *int64 `json:"priority"`
  604. Weight *uint `json:"weight"`
  605. ModelMapping *string `json:"model_mapping"`
  606. Models *string `json:"models"`
  607. Groups *string `json:"groups"`
  608. }
  609. func DisableTagChannels(c *gin.Context) {
  610. channelTag := ChannelTag{}
  611. err := c.ShouldBindJSON(&channelTag)
  612. if err != nil || channelTag.Tag == "" {
  613. c.JSON(http.StatusOK, gin.H{
  614. "success": false,
  615. "message": "参数错误",
  616. })
  617. return
  618. }
  619. err = model.DisableChannelByTag(channelTag.Tag)
  620. if err != nil {
  621. common.ApiError(c, err)
  622. return
  623. }
  624. model.InitChannelCache()
  625. c.JSON(http.StatusOK, gin.H{
  626. "success": true,
  627. "message": "",
  628. })
  629. return
  630. }
  631. func EnableTagChannels(c *gin.Context) {
  632. channelTag := ChannelTag{}
  633. err := c.ShouldBindJSON(&channelTag)
  634. if err != nil || channelTag.Tag == "" {
  635. c.JSON(http.StatusOK, gin.H{
  636. "success": false,
  637. "message": "参数错误",
  638. })
  639. return
  640. }
  641. err = model.EnableChannelByTag(channelTag.Tag)
  642. if err != nil {
  643. common.ApiError(c, err)
  644. return
  645. }
  646. model.InitChannelCache()
  647. c.JSON(http.StatusOK, gin.H{
  648. "success": true,
  649. "message": "",
  650. })
  651. return
  652. }
  653. func EditTagChannels(c *gin.Context) {
  654. channelTag := ChannelTag{}
  655. err := c.ShouldBindJSON(&channelTag)
  656. if err != nil {
  657. c.JSON(http.StatusOK, gin.H{
  658. "success": false,
  659. "message": "参数错误",
  660. })
  661. return
  662. }
  663. if channelTag.Tag == "" {
  664. c.JSON(http.StatusOK, gin.H{
  665. "success": false,
  666. "message": "tag不能为空",
  667. })
  668. return
  669. }
  670. err = model.EditChannelByTag(channelTag.Tag, channelTag.NewTag, channelTag.ModelMapping, channelTag.Models, channelTag.Groups, channelTag.Priority, channelTag.Weight)
  671. if err != nil {
  672. common.ApiError(c, err)
  673. return
  674. }
  675. model.InitChannelCache()
  676. c.JSON(http.StatusOK, gin.H{
  677. "success": true,
  678. "message": "",
  679. })
  680. return
  681. }
  682. type ChannelBatch struct {
  683. Ids []int `json:"ids"`
  684. Tag *string `json:"tag"`
  685. }
  686. func DeleteChannelBatch(c *gin.Context) {
  687. channelBatch := ChannelBatch{}
  688. err := c.ShouldBindJSON(&channelBatch)
  689. if err != nil || len(channelBatch.Ids) == 0 {
  690. c.JSON(http.StatusOK, gin.H{
  691. "success": false,
  692. "message": "参数错误",
  693. })
  694. return
  695. }
  696. err = model.BatchDeleteChannels(channelBatch.Ids)
  697. if err != nil {
  698. common.ApiError(c, err)
  699. return
  700. }
  701. model.InitChannelCache()
  702. c.JSON(http.StatusOK, gin.H{
  703. "success": true,
  704. "message": "",
  705. "data": len(channelBatch.Ids),
  706. })
  707. return
  708. }
  709. type PatchChannel struct {
  710. model.Channel
  711. MultiKeyMode *string `json:"multi_key_mode"`
  712. KeyMode *string `json:"key_mode"` // 多key模式下密钥覆盖或者追加
  713. }
  714. func UpdateChannel(c *gin.Context) {
  715. channel := PatchChannel{}
  716. err := c.ShouldBindJSON(&channel)
  717. if err != nil {
  718. common.ApiError(c, err)
  719. return
  720. }
  721. // 使用统一的校验函数
  722. if err := validateChannel(&channel.Channel, false); err != nil {
  723. c.JSON(http.StatusOK, gin.H{
  724. "success": false,
  725. "message": err.Error(),
  726. })
  727. return
  728. }
  729. // Preserve existing ChannelInfo to ensure multi-key channels keep correct state even if the client does not send ChannelInfo in the request.
  730. originChannel, err := model.GetChannelById(channel.Id, true)
  731. if err != nil {
  732. c.JSON(http.StatusOK, gin.H{
  733. "success": false,
  734. "message": err.Error(),
  735. })
  736. return
  737. }
  738. // Always copy the original ChannelInfo so that fields like IsMultiKey and MultiKeySize are retained.
  739. channel.ChannelInfo = originChannel.ChannelInfo
  740. // If the request explicitly specifies a new MultiKeyMode, apply it on top of the original info.
  741. if channel.MultiKeyMode != nil && *channel.MultiKeyMode != "" {
  742. channel.ChannelInfo.MultiKeyMode = constant.MultiKeyMode(*channel.MultiKeyMode)
  743. }
  744. // 处理多key模式下的密钥追加/覆盖逻辑
  745. if channel.KeyMode != nil && channel.ChannelInfo.IsMultiKey {
  746. switch *channel.KeyMode {
  747. case "append":
  748. // 追加模式:将新密钥添加到现有密钥列表
  749. if originChannel.Key != "" {
  750. var newKeys []string
  751. var existingKeys []string
  752. // 解析现有密钥
  753. if strings.HasPrefix(strings.TrimSpace(originChannel.Key), "[") {
  754. // JSON数组格式
  755. var arr []json.RawMessage
  756. if err := json.Unmarshal([]byte(strings.TrimSpace(originChannel.Key)), &arr); err == nil {
  757. existingKeys = make([]string, len(arr))
  758. for i, v := range arr {
  759. existingKeys[i] = string(v)
  760. }
  761. }
  762. } else {
  763. // 换行分隔格式
  764. existingKeys = strings.Split(strings.Trim(originChannel.Key, "\n"), "\n")
  765. }
  766. // 处理 Vertex AI 的特殊情况
  767. if channel.Type == constant.ChannelTypeVertexAi {
  768. // 尝试解析新密钥为JSON数组
  769. if strings.HasPrefix(strings.TrimSpace(channel.Key), "[") {
  770. array, err := getVertexArrayKeys(channel.Key)
  771. if err != nil {
  772. c.JSON(http.StatusOK, gin.H{
  773. "success": false,
  774. "message": "追加密钥解析失败: " + err.Error(),
  775. })
  776. return
  777. }
  778. newKeys = array
  779. } else {
  780. // 单个JSON密钥
  781. newKeys = []string{channel.Key}
  782. }
  783. // 合并密钥
  784. allKeys := append(existingKeys, newKeys...)
  785. channel.Key = strings.Join(allKeys, "\n")
  786. } else {
  787. // 普通渠道的处理
  788. inputKeys := strings.Split(channel.Key, "\n")
  789. for _, key := range inputKeys {
  790. key = strings.TrimSpace(key)
  791. if key != "" {
  792. newKeys = append(newKeys, key)
  793. }
  794. }
  795. // 合并密钥
  796. allKeys := append(existingKeys, newKeys...)
  797. channel.Key = strings.Join(allKeys, "\n")
  798. }
  799. }
  800. case "replace":
  801. // 覆盖模式:直接使用新密钥(默认行为,不需要特殊处理)
  802. }
  803. }
  804. err = channel.Update()
  805. if err != nil {
  806. common.ApiError(c, err)
  807. return
  808. }
  809. model.InitChannelCache()
  810. channel.Key = ""
  811. clearChannelInfo(&channel.Channel)
  812. c.JSON(http.StatusOK, gin.H{
  813. "success": true,
  814. "message": "",
  815. "data": channel,
  816. })
  817. return
  818. }
  819. func FetchModels(c *gin.Context) {
  820. var req struct {
  821. BaseURL string `json:"base_url"`
  822. Type int `json:"type"`
  823. Key string `json:"key"`
  824. }
  825. if err := c.ShouldBindJSON(&req); err != nil {
  826. c.JSON(http.StatusBadRequest, gin.H{
  827. "success": false,
  828. "message": "Invalid request",
  829. })
  830. return
  831. }
  832. baseURL := req.BaseURL
  833. if baseURL == "" {
  834. baseURL = constant.ChannelBaseURLs[req.Type]
  835. }
  836. client := &http.Client{}
  837. url := fmt.Sprintf("%s/v1/models", baseURL)
  838. request, err := http.NewRequest("GET", url, nil)
  839. if err != nil {
  840. c.JSON(http.StatusInternalServerError, gin.H{
  841. "success": false,
  842. "message": err.Error(),
  843. })
  844. return
  845. }
  846. // remove line breaks and extra spaces.
  847. key := strings.TrimSpace(req.Key)
  848. // If the key contains a line break, only take the first part.
  849. key = strings.Split(key, "\n")[0]
  850. request.Header.Set("Authorization", "Bearer "+key)
  851. response, err := client.Do(request)
  852. if err != nil {
  853. c.JSON(http.StatusInternalServerError, gin.H{
  854. "success": false,
  855. "message": err.Error(),
  856. })
  857. return
  858. }
  859. //check status code
  860. if response.StatusCode != http.StatusOK {
  861. c.JSON(http.StatusInternalServerError, gin.H{
  862. "success": false,
  863. "message": "Failed to fetch models",
  864. })
  865. return
  866. }
  867. defer response.Body.Close()
  868. var result struct {
  869. Data []struct {
  870. ID string `json:"id"`
  871. } `json:"data"`
  872. }
  873. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  874. c.JSON(http.StatusInternalServerError, gin.H{
  875. "success": false,
  876. "message": err.Error(),
  877. })
  878. return
  879. }
  880. var models []string
  881. for _, model := range result.Data {
  882. models = append(models, model.ID)
  883. }
  884. c.JSON(http.StatusOK, gin.H{
  885. "success": true,
  886. "data": models,
  887. })
  888. }
  889. func BatchSetChannelTag(c *gin.Context) {
  890. channelBatch := ChannelBatch{}
  891. err := c.ShouldBindJSON(&channelBatch)
  892. if err != nil || len(channelBatch.Ids) == 0 {
  893. c.JSON(http.StatusOK, gin.H{
  894. "success": false,
  895. "message": "参数错误",
  896. })
  897. return
  898. }
  899. err = model.BatchSetChannelTag(channelBatch.Ids, channelBatch.Tag)
  900. if err != nil {
  901. common.ApiError(c, err)
  902. return
  903. }
  904. model.InitChannelCache()
  905. c.JSON(http.StatusOK, gin.H{
  906. "success": true,
  907. "message": "",
  908. "data": len(channelBatch.Ids),
  909. })
  910. return
  911. }
  912. func GetTagModels(c *gin.Context) {
  913. tag := c.Query("tag")
  914. if tag == "" {
  915. c.JSON(http.StatusBadRequest, gin.H{
  916. "success": false,
  917. "message": "tag不能为空",
  918. })
  919. return
  920. }
  921. channels, err := model.GetChannelsByTag(tag, false) // Assuming false for idSort is fine here
  922. if err != nil {
  923. c.JSON(http.StatusInternalServerError, gin.H{
  924. "success": false,
  925. "message": err.Error(),
  926. })
  927. return
  928. }
  929. var longestModels string
  930. maxLength := 0
  931. // Find the longest models string among all channels with the given tag
  932. for _, channel := range channels {
  933. if channel.Models != "" {
  934. currentModels := strings.Split(channel.Models, ",")
  935. if len(currentModels) > maxLength {
  936. maxLength = len(currentModels)
  937. longestModels = channel.Models
  938. }
  939. }
  940. }
  941. c.JSON(http.StatusOK, gin.H{
  942. "success": true,
  943. "message": "",
  944. "data": longestModels,
  945. })
  946. return
  947. }
  948. // CopyChannel handles cloning an existing channel with its key.
  949. // POST /api/channel/copy/:id
  950. // Optional query params:
  951. //
  952. // suffix - string appended to the original name (default "_复制")
  953. // reset_balance - bool, when true will reset balance & used_quota to 0 (default true)
  954. func CopyChannel(c *gin.Context) {
  955. id, err := strconv.Atoi(c.Param("id"))
  956. if err != nil {
  957. c.JSON(http.StatusOK, gin.H{"success": false, "message": "invalid id"})
  958. return
  959. }
  960. suffix := c.DefaultQuery("suffix", "_复制")
  961. resetBalance := true
  962. if rbStr := c.DefaultQuery("reset_balance", "true"); rbStr != "" {
  963. if v, err := strconv.ParseBool(rbStr); err == nil {
  964. resetBalance = v
  965. }
  966. }
  967. // fetch original channel with key
  968. origin, err := model.GetChannelById(id, true)
  969. if err != nil {
  970. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  971. return
  972. }
  973. // clone channel
  974. clone := *origin // shallow copy is sufficient as we will overwrite primitives
  975. clone.Id = 0 // let DB auto-generate
  976. clone.CreatedTime = common.GetTimestamp()
  977. clone.Name = origin.Name + suffix
  978. clone.TestTime = 0
  979. clone.ResponseTime = 0
  980. if resetBalance {
  981. clone.Balance = 0
  982. clone.UsedQuota = 0
  983. }
  984. // insert
  985. if err := model.BatchInsertChannels([]model.Channel{clone}); err != nil {
  986. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  987. return
  988. }
  989. model.InitChannelCache()
  990. // success
  991. c.JSON(http.StatusOK, gin.H{"success": true, "message": "", "data": gin.H{"id": clone.Id}})
  992. }
  993. // MultiKeyManageRequest represents the request for multi-key management operations
  994. type MultiKeyManageRequest struct {
  995. ChannelId int `json:"channel_id"`
  996. Action string `json:"action"` // "disable_key", "enable_key", "delete_disabled_keys", "get_key_status"
  997. KeyIndex *int `json:"key_index,omitempty"` // for disable_key and enable_key actions
  998. Page int `json:"page,omitempty"` // for get_key_status pagination
  999. PageSize int `json:"page_size,omitempty"` // for get_key_status pagination
  1000. Status *int `json:"status,omitempty"` // for get_key_status filtering: 1=enabled, 2=manual_disabled, 3=auto_disabled, nil=all
  1001. }
  1002. // MultiKeyStatusResponse represents the response for key status query
  1003. type MultiKeyStatusResponse struct {
  1004. Keys []KeyStatus `json:"keys"`
  1005. Total int `json:"total"`
  1006. Page int `json:"page"`
  1007. PageSize int `json:"page_size"`
  1008. TotalPages int `json:"total_pages"`
  1009. // Statistics
  1010. EnabledCount int `json:"enabled_count"`
  1011. ManualDisabledCount int `json:"manual_disabled_count"`
  1012. AutoDisabledCount int `json:"auto_disabled_count"`
  1013. }
  1014. type KeyStatus struct {
  1015. Index int `json:"index"`
  1016. Status int `json:"status"` // 1: enabled, 2: disabled
  1017. DisabledTime int64 `json:"disabled_time,omitempty"`
  1018. Reason string `json:"reason,omitempty"`
  1019. KeyPreview string `json:"key_preview"` // first 10 chars of key for identification
  1020. }
  1021. // ManageMultiKeys handles multi-key management operations
  1022. func ManageMultiKeys(c *gin.Context) {
  1023. request := MultiKeyManageRequest{}
  1024. err := c.ShouldBindJSON(&request)
  1025. if err != nil {
  1026. common.ApiError(c, err)
  1027. return
  1028. }
  1029. channel, err := model.GetChannelById(request.ChannelId, true)
  1030. if err != nil {
  1031. c.JSON(http.StatusOK, gin.H{
  1032. "success": false,
  1033. "message": "渠道不存在",
  1034. })
  1035. return
  1036. }
  1037. if !channel.ChannelInfo.IsMultiKey {
  1038. c.JSON(http.StatusOK, gin.H{
  1039. "success": false,
  1040. "message": "该渠道不是多密钥模式",
  1041. })
  1042. return
  1043. }
  1044. lock := model.GetChannelPollingLock(channel.Id)
  1045. lock.Lock()
  1046. defer lock.Unlock()
  1047. switch request.Action {
  1048. case "get_key_status":
  1049. keys := channel.GetKeys()
  1050. // Default pagination parameters
  1051. page := request.Page
  1052. pageSize := request.PageSize
  1053. if page <= 0 {
  1054. page = 1
  1055. }
  1056. if pageSize <= 0 {
  1057. pageSize = 50 // Default page size
  1058. }
  1059. // Statistics for all keys (unchanged by filtering)
  1060. var enabledCount, manualDisabledCount, autoDisabledCount int
  1061. // Build all key status data first
  1062. var allKeyStatusList []KeyStatus
  1063. for i, key := range keys {
  1064. status := 1 // default enabled
  1065. var disabledTime int64
  1066. var reason string
  1067. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1068. if s, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists {
  1069. status = s
  1070. }
  1071. }
  1072. // Count for statistics (all keys)
  1073. switch status {
  1074. case 1:
  1075. enabledCount++
  1076. case 2:
  1077. manualDisabledCount++
  1078. case 3:
  1079. autoDisabledCount++
  1080. }
  1081. if status != 1 {
  1082. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1083. disabledTime = channel.ChannelInfo.MultiKeyDisabledTime[i]
  1084. }
  1085. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1086. reason = channel.ChannelInfo.MultiKeyDisabledReason[i]
  1087. }
  1088. }
  1089. // Create key preview (first 10 chars)
  1090. keyPreview := key
  1091. if len(key) > 10 {
  1092. keyPreview = key[:10] + "..."
  1093. }
  1094. allKeyStatusList = append(allKeyStatusList, KeyStatus{
  1095. Index: i,
  1096. Status: status,
  1097. DisabledTime: disabledTime,
  1098. Reason: reason,
  1099. KeyPreview: keyPreview,
  1100. })
  1101. }
  1102. // Apply status filter if specified
  1103. var filteredKeyStatusList []KeyStatus
  1104. if request.Status != nil {
  1105. for _, keyStatus := range allKeyStatusList {
  1106. if keyStatus.Status == *request.Status {
  1107. filteredKeyStatusList = append(filteredKeyStatusList, keyStatus)
  1108. }
  1109. }
  1110. } else {
  1111. filteredKeyStatusList = allKeyStatusList
  1112. }
  1113. // Calculate pagination based on filtered results
  1114. filteredTotal := len(filteredKeyStatusList)
  1115. totalPages := (filteredTotal + pageSize - 1) / pageSize
  1116. if totalPages == 0 {
  1117. totalPages = 1
  1118. }
  1119. if page > totalPages {
  1120. page = totalPages
  1121. }
  1122. // Calculate range for current page
  1123. start := (page - 1) * pageSize
  1124. end := start + pageSize
  1125. if end > filteredTotal {
  1126. end = filteredTotal
  1127. }
  1128. // Get the page data
  1129. var pageKeyStatusList []KeyStatus
  1130. if start < filteredTotal {
  1131. pageKeyStatusList = filteredKeyStatusList[start:end]
  1132. }
  1133. c.JSON(http.StatusOK, gin.H{
  1134. "success": true,
  1135. "message": "",
  1136. "data": MultiKeyStatusResponse{
  1137. Keys: pageKeyStatusList,
  1138. Total: filteredTotal, // Total of filtered results
  1139. Page: page,
  1140. PageSize: pageSize,
  1141. TotalPages: totalPages,
  1142. EnabledCount: enabledCount, // Overall statistics
  1143. ManualDisabledCount: manualDisabledCount, // Overall statistics
  1144. AutoDisabledCount: autoDisabledCount, // Overall statistics
  1145. },
  1146. })
  1147. return
  1148. case "disable_key":
  1149. if request.KeyIndex == nil {
  1150. c.JSON(http.StatusOK, gin.H{
  1151. "success": false,
  1152. "message": "未指定要禁用的密钥索引",
  1153. })
  1154. return
  1155. }
  1156. keyIndex := *request.KeyIndex
  1157. if keyIndex < 0 || keyIndex >= channel.ChannelInfo.MultiKeySize {
  1158. c.JSON(http.StatusOK, gin.H{
  1159. "success": false,
  1160. "message": "密钥索引超出范围",
  1161. })
  1162. return
  1163. }
  1164. if channel.ChannelInfo.MultiKeyStatusList == nil {
  1165. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  1166. }
  1167. if channel.ChannelInfo.MultiKeyDisabledTime == nil {
  1168. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  1169. }
  1170. if channel.ChannelInfo.MultiKeyDisabledReason == nil {
  1171. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  1172. }
  1173. channel.ChannelInfo.MultiKeyStatusList[keyIndex] = 2 // disabled
  1174. err = channel.Update()
  1175. if err != nil {
  1176. common.ApiError(c, err)
  1177. return
  1178. }
  1179. model.InitChannelCache()
  1180. c.JSON(http.StatusOK, gin.H{
  1181. "success": true,
  1182. "message": "密钥已禁用",
  1183. })
  1184. return
  1185. case "enable_key":
  1186. if request.KeyIndex == nil {
  1187. c.JSON(http.StatusOK, gin.H{
  1188. "success": false,
  1189. "message": "未指定要启用的密钥索引",
  1190. })
  1191. return
  1192. }
  1193. keyIndex := *request.KeyIndex
  1194. if keyIndex < 0 || keyIndex >= channel.ChannelInfo.MultiKeySize {
  1195. c.JSON(http.StatusOK, gin.H{
  1196. "success": false,
  1197. "message": "密钥索引超出范围",
  1198. })
  1199. return
  1200. }
  1201. // 从状态列表中删除该密钥的记录,使其回到默认启用状态
  1202. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1203. delete(channel.ChannelInfo.MultiKeyStatusList, keyIndex)
  1204. }
  1205. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1206. delete(channel.ChannelInfo.MultiKeyDisabledTime, keyIndex)
  1207. }
  1208. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1209. delete(channel.ChannelInfo.MultiKeyDisabledReason, keyIndex)
  1210. }
  1211. err = channel.Update()
  1212. if err != nil {
  1213. common.ApiError(c, err)
  1214. return
  1215. }
  1216. model.InitChannelCache()
  1217. c.JSON(http.StatusOK, gin.H{
  1218. "success": true,
  1219. "message": "密钥已启用",
  1220. })
  1221. return
  1222. case "enable_all_keys":
  1223. // 清空所有禁用状态,使所有密钥回到默认启用状态
  1224. var enabledCount int
  1225. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1226. enabledCount = len(channel.ChannelInfo.MultiKeyStatusList)
  1227. }
  1228. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  1229. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  1230. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  1231. err = channel.Update()
  1232. if err != nil {
  1233. common.ApiError(c, err)
  1234. return
  1235. }
  1236. model.InitChannelCache()
  1237. c.JSON(http.StatusOK, gin.H{
  1238. "success": true,
  1239. "message": fmt.Sprintf("已启用 %d 个密钥", enabledCount),
  1240. })
  1241. return
  1242. case "disable_all_keys":
  1243. // 禁用所有启用的密钥
  1244. if channel.ChannelInfo.MultiKeyStatusList == nil {
  1245. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  1246. }
  1247. if channel.ChannelInfo.MultiKeyDisabledTime == nil {
  1248. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  1249. }
  1250. if channel.ChannelInfo.MultiKeyDisabledReason == nil {
  1251. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  1252. }
  1253. var disabledCount int
  1254. for i := 0; i < channel.ChannelInfo.MultiKeySize; i++ {
  1255. status := 1 // default enabled
  1256. if s, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists {
  1257. status = s
  1258. }
  1259. // 只禁用当前启用的密钥
  1260. if status == 1 {
  1261. channel.ChannelInfo.MultiKeyStatusList[i] = 2 // disabled
  1262. disabledCount++
  1263. }
  1264. }
  1265. if disabledCount == 0 {
  1266. c.JSON(http.StatusOK, gin.H{
  1267. "success": false,
  1268. "message": "没有可禁用的密钥",
  1269. })
  1270. return
  1271. }
  1272. err = channel.Update()
  1273. if err != nil {
  1274. common.ApiError(c, err)
  1275. return
  1276. }
  1277. model.InitChannelCache()
  1278. c.JSON(http.StatusOK, gin.H{
  1279. "success": true,
  1280. "message": fmt.Sprintf("已禁用 %d 个密钥", disabledCount),
  1281. })
  1282. return
  1283. case "delete_disabled_keys":
  1284. keys := channel.GetKeys()
  1285. var remainingKeys []string
  1286. var deletedCount int
  1287. var newStatusList = make(map[int]int)
  1288. var newDisabledTime = make(map[int]int64)
  1289. var newDisabledReason = make(map[int]string)
  1290. newIndex := 0
  1291. for i, key := range keys {
  1292. status := 1 // default enabled
  1293. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1294. if s, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists {
  1295. status = s
  1296. }
  1297. }
  1298. // 只删除自动禁用(status == 3)的密钥,保留启用(status == 1)和手动禁用(status == 2)的密钥
  1299. if status == 3 {
  1300. deletedCount++
  1301. } else {
  1302. remainingKeys = append(remainingKeys, key)
  1303. // 保留非自动禁用密钥的状态信息,重新索引
  1304. if status != 1 {
  1305. newStatusList[newIndex] = status
  1306. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1307. if t, exists := channel.ChannelInfo.MultiKeyDisabledTime[i]; exists {
  1308. newDisabledTime[newIndex] = t
  1309. }
  1310. }
  1311. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1312. if r, exists := channel.ChannelInfo.MultiKeyDisabledReason[i]; exists {
  1313. newDisabledReason[newIndex] = r
  1314. }
  1315. }
  1316. }
  1317. newIndex++
  1318. }
  1319. }
  1320. if deletedCount == 0 {
  1321. c.JSON(http.StatusOK, gin.H{
  1322. "success": false,
  1323. "message": "没有需要删除的自动禁用密钥",
  1324. })
  1325. return
  1326. }
  1327. // Update channel with remaining keys
  1328. channel.Key = strings.Join(remainingKeys, "\n")
  1329. channel.ChannelInfo.MultiKeySize = len(remainingKeys)
  1330. channel.ChannelInfo.MultiKeyStatusList = newStatusList
  1331. channel.ChannelInfo.MultiKeyDisabledTime = newDisabledTime
  1332. channel.ChannelInfo.MultiKeyDisabledReason = newDisabledReason
  1333. err = channel.Update()
  1334. if err != nil {
  1335. common.ApiError(c, err)
  1336. return
  1337. }
  1338. model.InitChannelCache()
  1339. c.JSON(http.StatusOK, gin.H{
  1340. "success": true,
  1341. "message": fmt.Sprintf("已删除 %d 个自动禁用的密钥", deletedCount),
  1342. "data": deletedCount,
  1343. })
  1344. return
  1345. default:
  1346. c.JSON(http.StatusOK, gin.H{
  1347. "success": false,
  1348. "message": "不支持的操作",
  1349. })
  1350. return
  1351. }
  1352. }