channel.go 40 KB

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