channel.go 38 KB

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