channel.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  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. ParamOverride *string `json:"param_override"`
  601. HeaderOverride *string `json:"header_override"`
  602. }
  603. func DisableTagChannels(c *gin.Context) {
  604. channelTag := ChannelTag{}
  605. err := c.ShouldBindJSON(&channelTag)
  606. if err != nil || channelTag.Tag == "" {
  607. c.JSON(http.StatusOK, gin.H{
  608. "success": false,
  609. "message": "参数错误",
  610. })
  611. return
  612. }
  613. err = model.DisableChannelByTag(channelTag.Tag)
  614. if err != nil {
  615. common.ApiError(c, err)
  616. return
  617. }
  618. model.InitChannelCache()
  619. c.JSON(http.StatusOK, gin.H{
  620. "success": true,
  621. "message": "",
  622. })
  623. return
  624. }
  625. func EnableTagChannels(c *gin.Context) {
  626. channelTag := ChannelTag{}
  627. err := c.ShouldBindJSON(&channelTag)
  628. if err != nil || channelTag.Tag == "" {
  629. c.JSON(http.StatusOK, gin.H{
  630. "success": false,
  631. "message": "参数错误",
  632. })
  633. return
  634. }
  635. err = model.EnableChannelByTag(channelTag.Tag)
  636. if err != nil {
  637. common.ApiError(c, err)
  638. return
  639. }
  640. model.InitChannelCache()
  641. c.JSON(http.StatusOK, gin.H{
  642. "success": true,
  643. "message": "",
  644. })
  645. return
  646. }
  647. func EditTagChannels(c *gin.Context) {
  648. channelTag := ChannelTag{}
  649. err := c.ShouldBindJSON(&channelTag)
  650. if err != nil {
  651. c.JSON(http.StatusOK, gin.H{
  652. "success": false,
  653. "message": "参数错误",
  654. })
  655. return
  656. }
  657. if channelTag.Tag == "" {
  658. c.JSON(http.StatusOK, gin.H{
  659. "success": false,
  660. "message": "tag不能为空",
  661. })
  662. return
  663. }
  664. if channelTag.ParamOverride != nil {
  665. trimmed := strings.TrimSpace(*channelTag.ParamOverride)
  666. if trimmed != "" && !json.Valid([]byte(trimmed)) {
  667. c.JSON(http.StatusOK, gin.H{
  668. "success": false,
  669. "message": "参数覆盖必须是合法的 JSON 格式",
  670. })
  671. return
  672. }
  673. channelTag.ParamOverride = common.GetPointer[string](trimmed)
  674. }
  675. if channelTag.HeaderOverride != nil {
  676. trimmed := strings.TrimSpace(*channelTag.HeaderOverride)
  677. if trimmed != "" && !json.Valid([]byte(trimmed)) {
  678. c.JSON(http.StatusOK, gin.H{
  679. "success": false,
  680. "message": "请求头覆盖必须是合法的 JSON 格式",
  681. })
  682. return
  683. }
  684. channelTag.HeaderOverride = common.GetPointer[string](trimmed)
  685. }
  686. err = model.EditChannelByTag(channelTag.Tag, channelTag.NewTag, channelTag.ModelMapping, channelTag.Models, channelTag.Groups, channelTag.Priority, channelTag.Weight, channelTag.ParamOverride, channelTag.HeaderOverride)
  687. if err != nil {
  688. common.ApiError(c, err)
  689. return
  690. }
  691. model.InitChannelCache()
  692. c.JSON(http.StatusOK, gin.H{
  693. "success": true,
  694. "message": "",
  695. })
  696. return
  697. }
  698. type ChannelBatch struct {
  699. Ids []int `json:"ids"`
  700. Tag *string `json:"tag"`
  701. }
  702. func DeleteChannelBatch(c *gin.Context) {
  703. channelBatch := ChannelBatch{}
  704. err := c.ShouldBindJSON(&channelBatch)
  705. if err != nil || len(channelBatch.Ids) == 0 {
  706. c.JSON(http.StatusOK, gin.H{
  707. "success": false,
  708. "message": "参数错误",
  709. })
  710. return
  711. }
  712. err = model.BatchDeleteChannels(channelBatch.Ids)
  713. if err != nil {
  714. common.ApiError(c, err)
  715. return
  716. }
  717. model.InitChannelCache()
  718. c.JSON(http.StatusOK, gin.H{
  719. "success": true,
  720. "message": "",
  721. "data": len(channelBatch.Ids),
  722. })
  723. return
  724. }
  725. type PatchChannel struct {
  726. model.Channel
  727. MultiKeyMode *string `json:"multi_key_mode"`
  728. KeyMode *string `json:"key_mode"` // 多key模式下密钥覆盖或者追加
  729. }
  730. func UpdateChannel(c *gin.Context) {
  731. channel := PatchChannel{}
  732. err := c.ShouldBindJSON(&channel)
  733. if err != nil {
  734. common.ApiError(c, err)
  735. return
  736. }
  737. // 使用统一的校验函数
  738. if err := validateChannel(&channel.Channel, false); err != nil {
  739. c.JSON(http.StatusOK, gin.H{
  740. "success": false,
  741. "message": err.Error(),
  742. })
  743. return
  744. }
  745. // Preserve existing ChannelInfo to ensure multi-key channels keep correct state even if the client does not send ChannelInfo in the request.
  746. originChannel, err := model.GetChannelById(channel.Id, true)
  747. if err != nil {
  748. c.JSON(http.StatusOK, gin.H{
  749. "success": false,
  750. "message": err.Error(),
  751. })
  752. return
  753. }
  754. // Always copy the original ChannelInfo so that fields like IsMultiKey and MultiKeySize are retained.
  755. channel.ChannelInfo = originChannel.ChannelInfo
  756. // If the request explicitly specifies a new MultiKeyMode, apply it on top of the original info.
  757. if channel.MultiKeyMode != nil && *channel.MultiKeyMode != "" {
  758. channel.ChannelInfo.MultiKeyMode = constant.MultiKeyMode(*channel.MultiKeyMode)
  759. }
  760. // 处理多key模式下的密钥追加/覆盖逻辑
  761. if channel.KeyMode != nil && channel.ChannelInfo.IsMultiKey {
  762. switch *channel.KeyMode {
  763. case "append":
  764. // 追加模式:将新密钥添加到现有密钥列表
  765. if originChannel.Key != "" {
  766. var newKeys []string
  767. var existingKeys []string
  768. // 解析现有密钥
  769. if strings.HasPrefix(strings.TrimSpace(originChannel.Key), "[") {
  770. // JSON数组格式
  771. var arr []json.RawMessage
  772. if err := json.Unmarshal([]byte(strings.TrimSpace(originChannel.Key)), &arr); err == nil {
  773. existingKeys = make([]string, len(arr))
  774. for i, v := range arr {
  775. existingKeys[i] = string(v)
  776. }
  777. }
  778. } else {
  779. // 换行分隔格式
  780. existingKeys = strings.Split(strings.Trim(originChannel.Key, "\n"), "\n")
  781. }
  782. // 处理 Vertex AI 的特殊情况
  783. if channel.Type == constant.ChannelTypeVertexAi && channel.GetOtherSettings().VertexKeyType != dto.VertexKeyTypeAPIKey {
  784. // 尝试解析新密钥为JSON数组
  785. if strings.HasPrefix(strings.TrimSpace(channel.Key), "[") {
  786. array, err := getVertexArrayKeys(channel.Key)
  787. if err != nil {
  788. c.JSON(http.StatusOK, gin.H{
  789. "success": false,
  790. "message": "追加密钥解析失败: " + err.Error(),
  791. })
  792. return
  793. }
  794. newKeys = array
  795. } else {
  796. // 单个JSON密钥
  797. newKeys = []string{channel.Key}
  798. }
  799. // 合并密钥
  800. allKeys := append(existingKeys, newKeys...)
  801. channel.Key = strings.Join(allKeys, "\n")
  802. } else {
  803. // 普通渠道的处理
  804. inputKeys := strings.Split(channel.Key, "\n")
  805. for _, key := range inputKeys {
  806. key = strings.TrimSpace(key)
  807. if key != "" {
  808. newKeys = append(newKeys, key)
  809. }
  810. }
  811. // 合并密钥
  812. allKeys := append(existingKeys, newKeys...)
  813. channel.Key = strings.Join(allKeys, "\n")
  814. }
  815. }
  816. case "replace":
  817. // 覆盖模式:直接使用新密钥(默认行为,不需要特殊处理)
  818. }
  819. }
  820. err = channel.Update()
  821. if err != nil {
  822. common.ApiError(c, err)
  823. return
  824. }
  825. model.InitChannelCache()
  826. service.ResetProxyClientCache()
  827. channel.Key = ""
  828. clearChannelInfo(&channel.Channel)
  829. c.JSON(http.StatusOK, gin.H{
  830. "success": true,
  831. "message": "",
  832. "data": channel,
  833. })
  834. return
  835. }
  836. func FetchModels(c *gin.Context) {
  837. var req struct {
  838. BaseURL string `json:"base_url"`
  839. Type int `json:"type"`
  840. Key string `json:"key"`
  841. }
  842. if err := c.ShouldBindJSON(&req); err != nil {
  843. c.JSON(http.StatusBadRequest, gin.H{
  844. "success": false,
  845. "message": "Invalid request",
  846. })
  847. return
  848. }
  849. baseURL := req.BaseURL
  850. if baseURL == "" {
  851. baseURL = constant.ChannelBaseURLs[req.Type]
  852. }
  853. client := &http.Client{}
  854. url := fmt.Sprintf("%s/v1/models", baseURL)
  855. request, err := http.NewRequest("GET", url, nil)
  856. if err != nil {
  857. c.JSON(http.StatusInternalServerError, gin.H{
  858. "success": false,
  859. "message": err.Error(),
  860. })
  861. return
  862. }
  863. // remove line breaks and extra spaces.
  864. key := strings.TrimSpace(req.Key)
  865. // If the key contains a line break, only take the first part.
  866. key = strings.Split(key, "\n")[0]
  867. request.Header.Set("Authorization", "Bearer "+key)
  868. response, err := client.Do(request)
  869. if err != nil {
  870. c.JSON(http.StatusInternalServerError, gin.H{
  871. "success": false,
  872. "message": err.Error(),
  873. })
  874. return
  875. }
  876. //check status code
  877. if response.StatusCode != http.StatusOK {
  878. c.JSON(http.StatusInternalServerError, gin.H{
  879. "success": false,
  880. "message": "Failed to fetch models",
  881. })
  882. return
  883. }
  884. defer response.Body.Close()
  885. var result struct {
  886. Data []struct {
  887. ID string `json:"id"`
  888. } `json:"data"`
  889. }
  890. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  891. c.JSON(http.StatusInternalServerError, gin.H{
  892. "success": false,
  893. "message": err.Error(),
  894. })
  895. return
  896. }
  897. var models []string
  898. for _, model := range result.Data {
  899. models = append(models, model.ID)
  900. }
  901. c.JSON(http.StatusOK, gin.H{
  902. "success": true,
  903. "data": models,
  904. })
  905. }
  906. func BatchSetChannelTag(c *gin.Context) {
  907. channelBatch := ChannelBatch{}
  908. err := c.ShouldBindJSON(&channelBatch)
  909. if err != nil || len(channelBatch.Ids) == 0 {
  910. c.JSON(http.StatusOK, gin.H{
  911. "success": false,
  912. "message": "参数错误",
  913. })
  914. return
  915. }
  916. err = model.BatchSetChannelTag(channelBatch.Ids, channelBatch.Tag)
  917. if err != nil {
  918. common.ApiError(c, err)
  919. return
  920. }
  921. model.InitChannelCache()
  922. c.JSON(http.StatusOK, gin.H{
  923. "success": true,
  924. "message": "",
  925. "data": len(channelBatch.Ids),
  926. })
  927. return
  928. }
  929. func GetTagModels(c *gin.Context) {
  930. tag := c.Query("tag")
  931. if tag == "" {
  932. c.JSON(http.StatusBadRequest, gin.H{
  933. "success": false,
  934. "message": "tag不能为空",
  935. })
  936. return
  937. }
  938. channels, err := model.GetChannelsByTag(tag, false) // Assuming false for idSort is fine here
  939. if err != nil {
  940. c.JSON(http.StatusInternalServerError, gin.H{
  941. "success": false,
  942. "message": err.Error(),
  943. })
  944. return
  945. }
  946. var longestModels string
  947. maxLength := 0
  948. // Find the longest models string among all channels with the given tag
  949. for _, channel := range channels {
  950. if channel.Models != "" {
  951. currentModels := strings.Split(channel.Models, ",")
  952. if len(currentModels) > maxLength {
  953. maxLength = len(currentModels)
  954. longestModels = channel.Models
  955. }
  956. }
  957. }
  958. c.JSON(http.StatusOK, gin.H{
  959. "success": true,
  960. "message": "",
  961. "data": longestModels,
  962. })
  963. return
  964. }
  965. // CopyChannel handles cloning an existing channel with its key.
  966. // POST /api/channel/copy/:id
  967. // Optional query params:
  968. //
  969. // suffix - string appended to the original name (default "_复制")
  970. // reset_balance - bool, when true will reset balance & used_quota to 0 (default true)
  971. func CopyChannel(c *gin.Context) {
  972. id, err := strconv.Atoi(c.Param("id"))
  973. if err != nil {
  974. c.JSON(http.StatusOK, gin.H{"success": false, "message": "invalid id"})
  975. return
  976. }
  977. suffix := c.DefaultQuery("suffix", "_复制")
  978. resetBalance := true
  979. if rbStr := c.DefaultQuery("reset_balance", "true"); rbStr != "" {
  980. if v, err := strconv.ParseBool(rbStr); err == nil {
  981. resetBalance = v
  982. }
  983. }
  984. // fetch original channel with key
  985. origin, err := model.GetChannelById(id, true)
  986. if err != nil {
  987. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  988. return
  989. }
  990. // clone channel
  991. clone := *origin // shallow copy is sufficient as we will overwrite primitives
  992. clone.Id = 0 // let DB auto-generate
  993. clone.CreatedTime = common.GetTimestamp()
  994. clone.Name = origin.Name + suffix
  995. clone.TestTime = 0
  996. clone.ResponseTime = 0
  997. if resetBalance {
  998. clone.Balance = 0
  999. clone.UsedQuota = 0
  1000. }
  1001. // insert
  1002. if err := model.BatchInsertChannels([]model.Channel{clone}); err != nil {
  1003. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  1004. return
  1005. }
  1006. model.InitChannelCache()
  1007. // success
  1008. c.JSON(http.StatusOK, gin.H{"success": true, "message": "", "data": gin.H{"id": clone.Id}})
  1009. }
  1010. // MultiKeyManageRequest represents the request for multi-key management operations
  1011. type MultiKeyManageRequest struct {
  1012. ChannelId int `json:"channel_id"`
  1013. Action string `json:"action"` // "disable_key", "enable_key", "delete_key", "delete_disabled_keys", "get_key_status"
  1014. KeyIndex *int `json:"key_index,omitempty"` // for disable_key, enable_key, and delete_key actions
  1015. Page int `json:"page,omitempty"` // for get_key_status pagination
  1016. PageSize int `json:"page_size,omitempty"` // for get_key_status pagination
  1017. Status *int `json:"status,omitempty"` // for get_key_status filtering: 1=enabled, 2=manual_disabled, 3=auto_disabled, nil=all
  1018. }
  1019. // MultiKeyStatusResponse represents the response for key status query
  1020. type MultiKeyStatusResponse struct {
  1021. Keys []KeyStatus `json:"keys"`
  1022. Total int `json:"total"`
  1023. Page int `json:"page"`
  1024. PageSize int `json:"page_size"`
  1025. TotalPages int `json:"total_pages"`
  1026. // Statistics
  1027. EnabledCount int `json:"enabled_count"`
  1028. ManualDisabledCount int `json:"manual_disabled_count"`
  1029. AutoDisabledCount int `json:"auto_disabled_count"`
  1030. }
  1031. type KeyStatus struct {
  1032. Index int `json:"index"`
  1033. Status int `json:"status"` // 1: enabled, 2: disabled
  1034. DisabledTime int64 `json:"disabled_time,omitempty"`
  1035. Reason string `json:"reason,omitempty"`
  1036. KeyPreview string `json:"key_preview"` // first 10 chars of key for identification
  1037. }
  1038. // ManageMultiKeys handles multi-key management operations
  1039. func ManageMultiKeys(c *gin.Context) {
  1040. request := MultiKeyManageRequest{}
  1041. err := c.ShouldBindJSON(&request)
  1042. if err != nil {
  1043. common.ApiError(c, err)
  1044. return
  1045. }
  1046. channel, err := model.GetChannelById(request.ChannelId, true)
  1047. if err != nil {
  1048. c.JSON(http.StatusOK, gin.H{
  1049. "success": false,
  1050. "message": "渠道不存在",
  1051. })
  1052. return
  1053. }
  1054. if !channel.ChannelInfo.IsMultiKey {
  1055. c.JSON(http.StatusOK, gin.H{
  1056. "success": false,
  1057. "message": "该渠道不是多密钥模式",
  1058. })
  1059. return
  1060. }
  1061. lock := model.GetChannelPollingLock(channel.Id)
  1062. lock.Lock()
  1063. defer lock.Unlock()
  1064. switch request.Action {
  1065. case "get_key_status":
  1066. keys := channel.GetKeys()
  1067. // Default pagination parameters
  1068. page := request.Page
  1069. pageSize := request.PageSize
  1070. if page <= 0 {
  1071. page = 1
  1072. }
  1073. if pageSize <= 0 {
  1074. pageSize = 50 // Default page size
  1075. }
  1076. // Statistics for all keys (unchanged by filtering)
  1077. var enabledCount, manualDisabledCount, autoDisabledCount int
  1078. // Build all key status data first
  1079. var allKeyStatusList []KeyStatus
  1080. for i, key := range keys {
  1081. status := 1 // default enabled
  1082. var disabledTime int64
  1083. var reason string
  1084. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1085. if s, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists {
  1086. status = s
  1087. }
  1088. }
  1089. // Count for statistics (all keys)
  1090. switch status {
  1091. case 1:
  1092. enabledCount++
  1093. case 2:
  1094. manualDisabledCount++
  1095. case 3:
  1096. autoDisabledCount++
  1097. }
  1098. if status != 1 {
  1099. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1100. disabledTime = channel.ChannelInfo.MultiKeyDisabledTime[i]
  1101. }
  1102. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1103. reason = channel.ChannelInfo.MultiKeyDisabledReason[i]
  1104. }
  1105. }
  1106. // Create key preview (first 10 chars)
  1107. keyPreview := key
  1108. if len(key) > 10 {
  1109. keyPreview = key[:10] + "..."
  1110. }
  1111. allKeyStatusList = append(allKeyStatusList, KeyStatus{
  1112. Index: i,
  1113. Status: status,
  1114. DisabledTime: disabledTime,
  1115. Reason: reason,
  1116. KeyPreview: keyPreview,
  1117. })
  1118. }
  1119. // Apply status filter if specified
  1120. var filteredKeyStatusList []KeyStatus
  1121. if request.Status != nil {
  1122. for _, keyStatus := range allKeyStatusList {
  1123. if keyStatus.Status == *request.Status {
  1124. filteredKeyStatusList = append(filteredKeyStatusList, keyStatus)
  1125. }
  1126. }
  1127. } else {
  1128. filteredKeyStatusList = allKeyStatusList
  1129. }
  1130. // Calculate pagination based on filtered results
  1131. filteredTotal := len(filteredKeyStatusList)
  1132. totalPages := (filteredTotal + pageSize - 1) / pageSize
  1133. if totalPages == 0 {
  1134. totalPages = 1
  1135. }
  1136. if page > totalPages {
  1137. page = totalPages
  1138. }
  1139. // Calculate range for current page
  1140. start := (page - 1) * pageSize
  1141. end := start + pageSize
  1142. if end > filteredTotal {
  1143. end = filteredTotal
  1144. }
  1145. // Get the page data
  1146. var pageKeyStatusList []KeyStatus
  1147. if start < filteredTotal {
  1148. pageKeyStatusList = filteredKeyStatusList[start:end]
  1149. }
  1150. c.JSON(http.StatusOK, gin.H{
  1151. "success": true,
  1152. "message": "",
  1153. "data": MultiKeyStatusResponse{
  1154. Keys: pageKeyStatusList,
  1155. Total: filteredTotal, // Total of filtered results
  1156. Page: page,
  1157. PageSize: pageSize,
  1158. TotalPages: totalPages,
  1159. EnabledCount: enabledCount, // Overall statistics
  1160. ManualDisabledCount: manualDisabledCount, // Overall statistics
  1161. AutoDisabledCount: autoDisabledCount, // Overall statistics
  1162. },
  1163. })
  1164. return
  1165. case "disable_key":
  1166. if request.KeyIndex == nil {
  1167. c.JSON(http.StatusOK, gin.H{
  1168. "success": false,
  1169. "message": "未指定要禁用的密钥索引",
  1170. })
  1171. return
  1172. }
  1173. keyIndex := *request.KeyIndex
  1174. if keyIndex < 0 || keyIndex >= channel.ChannelInfo.MultiKeySize {
  1175. c.JSON(http.StatusOK, gin.H{
  1176. "success": false,
  1177. "message": "密钥索引超出范围",
  1178. })
  1179. return
  1180. }
  1181. if channel.ChannelInfo.MultiKeyStatusList == nil {
  1182. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  1183. }
  1184. if channel.ChannelInfo.MultiKeyDisabledTime == nil {
  1185. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  1186. }
  1187. if channel.ChannelInfo.MultiKeyDisabledReason == nil {
  1188. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  1189. }
  1190. channel.ChannelInfo.MultiKeyStatusList[keyIndex] = 2 // disabled
  1191. err = channel.Update()
  1192. if err != nil {
  1193. common.ApiError(c, err)
  1194. return
  1195. }
  1196. model.InitChannelCache()
  1197. c.JSON(http.StatusOK, gin.H{
  1198. "success": true,
  1199. "message": "密钥已禁用",
  1200. })
  1201. return
  1202. case "enable_key":
  1203. if request.KeyIndex == nil {
  1204. c.JSON(http.StatusOK, gin.H{
  1205. "success": false,
  1206. "message": "未指定要启用的密钥索引",
  1207. })
  1208. return
  1209. }
  1210. keyIndex := *request.KeyIndex
  1211. if keyIndex < 0 || keyIndex >= channel.ChannelInfo.MultiKeySize {
  1212. c.JSON(http.StatusOK, gin.H{
  1213. "success": false,
  1214. "message": "密钥索引超出范围",
  1215. })
  1216. return
  1217. }
  1218. // 从状态列表中删除该密钥的记录,使其回到默认启用状态
  1219. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1220. delete(channel.ChannelInfo.MultiKeyStatusList, keyIndex)
  1221. }
  1222. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1223. delete(channel.ChannelInfo.MultiKeyDisabledTime, keyIndex)
  1224. }
  1225. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1226. delete(channel.ChannelInfo.MultiKeyDisabledReason, keyIndex)
  1227. }
  1228. err = channel.Update()
  1229. if err != nil {
  1230. common.ApiError(c, err)
  1231. return
  1232. }
  1233. model.InitChannelCache()
  1234. c.JSON(http.StatusOK, gin.H{
  1235. "success": true,
  1236. "message": "密钥已启用",
  1237. })
  1238. return
  1239. case "enable_all_keys":
  1240. // 清空所有禁用状态,使所有密钥回到默认启用状态
  1241. var enabledCount int
  1242. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1243. enabledCount = len(channel.ChannelInfo.MultiKeyStatusList)
  1244. }
  1245. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  1246. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  1247. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  1248. err = channel.Update()
  1249. if err != nil {
  1250. common.ApiError(c, err)
  1251. return
  1252. }
  1253. model.InitChannelCache()
  1254. c.JSON(http.StatusOK, gin.H{
  1255. "success": true,
  1256. "message": fmt.Sprintf("已启用 %d 个密钥", enabledCount),
  1257. })
  1258. return
  1259. case "disable_all_keys":
  1260. // 禁用所有启用的密钥
  1261. if channel.ChannelInfo.MultiKeyStatusList == nil {
  1262. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  1263. }
  1264. if channel.ChannelInfo.MultiKeyDisabledTime == nil {
  1265. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  1266. }
  1267. if channel.ChannelInfo.MultiKeyDisabledReason == nil {
  1268. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  1269. }
  1270. var disabledCount int
  1271. for i := 0; i < channel.ChannelInfo.MultiKeySize; i++ {
  1272. status := 1 // default enabled
  1273. if s, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists {
  1274. status = s
  1275. }
  1276. // 只禁用当前启用的密钥
  1277. if status == 1 {
  1278. channel.ChannelInfo.MultiKeyStatusList[i] = 2 // disabled
  1279. disabledCount++
  1280. }
  1281. }
  1282. if disabledCount == 0 {
  1283. c.JSON(http.StatusOK, gin.H{
  1284. "success": false,
  1285. "message": "没有可禁用的密钥",
  1286. })
  1287. return
  1288. }
  1289. err = channel.Update()
  1290. if err != nil {
  1291. common.ApiError(c, err)
  1292. return
  1293. }
  1294. model.InitChannelCache()
  1295. c.JSON(http.StatusOK, gin.H{
  1296. "success": true,
  1297. "message": fmt.Sprintf("已禁用 %d 个密钥", disabledCount),
  1298. })
  1299. return
  1300. case "delete_key":
  1301. if request.KeyIndex == nil {
  1302. c.JSON(http.StatusOK, gin.H{
  1303. "success": false,
  1304. "message": "未指定要删除的密钥索引",
  1305. })
  1306. return
  1307. }
  1308. keyIndex := *request.KeyIndex
  1309. if keyIndex < 0 || keyIndex >= channel.ChannelInfo.MultiKeySize {
  1310. c.JSON(http.StatusOK, gin.H{
  1311. "success": false,
  1312. "message": "密钥索引超出范围",
  1313. })
  1314. return
  1315. }
  1316. keys := channel.GetKeys()
  1317. var remainingKeys []string
  1318. var newStatusList = make(map[int]int)
  1319. var newDisabledTime = make(map[int]int64)
  1320. var newDisabledReason = make(map[int]string)
  1321. newIndex := 0
  1322. for i, key := range keys {
  1323. // 跳过要删除的密钥
  1324. if i == keyIndex {
  1325. continue
  1326. }
  1327. remainingKeys = append(remainingKeys, key)
  1328. // 保留其他密钥的状态信息,重新索引
  1329. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1330. if status, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists && status != 1 {
  1331. newStatusList[newIndex] = status
  1332. }
  1333. }
  1334. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1335. if t, exists := channel.ChannelInfo.MultiKeyDisabledTime[i]; exists {
  1336. newDisabledTime[newIndex] = t
  1337. }
  1338. }
  1339. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1340. if r, exists := channel.ChannelInfo.MultiKeyDisabledReason[i]; exists {
  1341. newDisabledReason[newIndex] = r
  1342. }
  1343. }
  1344. newIndex++
  1345. }
  1346. if len(remainingKeys) == 0 {
  1347. c.JSON(http.StatusOK, gin.H{
  1348. "success": false,
  1349. "message": "不能删除最后一个密钥",
  1350. })
  1351. return
  1352. }
  1353. // Update channel with remaining keys
  1354. channel.Key = strings.Join(remainingKeys, "\n")
  1355. channel.ChannelInfo.MultiKeySize = len(remainingKeys)
  1356. channel.ChannelInfo.MultiKeyStatusList = newStatusList
  1357. channel.ChannelInfo.MultiKeyDisabledTime = newDisabledTime
  1358. channel.ChannelInfo.MultiKeyDisabledReason = newDisabledReason
  1359. err = channel.Update()
  1360. if err != nil {
  1361. common.ApiError(c, err)
  1362. return
  1363. }
  1364. model.InitChannelCache()
  1365. c.JSON(http.StatusOK, gin.H{
  1366. "success": true,
  1367. "message": "密钥已删除",
  1368. })
  1369. return
  1370. case "delete_disabled_keys":
  1371. keys := channel.GetKeys()
  1372. var remainingKeys []string
  1373. var deletedCount int
  1374. var newStatusList = make(map[int]int)
  1375. var newDisabledTime = make(map[int]int64)
  1376. var newDisabledReason = make(map[int]string)
  1377. newIndex := 0
  1378. for i, key := range keys {
  1379. status := 1 // default enabled
  1380. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1381. if s, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists {
  1382. status = s
  1383. }
  1384. }
  1385. // 只删除自动禁用(status == 3)的密钥,保留启用(status == 1)和手动禁用(status == 2)的密钥
  1386. if status == 3 {
  1387. deletedCount++
  1388. } else {
  1389. remainingKeys = append(remainingKeys, key)
  1390. // 保留非自动禁用密钥的状态信息,重新索引
  1391. if status != 1 {
  1392. newStatusList[newIndex] = status
  1393. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1394. if t, exists := channel.ChannelInfo.MultiKeyDisabledTime[i]; exists {
  1395. newDisabledTime[newIndex] = t
  1396. }
  1397. }
  1398. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1399. if r, exists := channel.ChannelInfo.MultiKeyDisabledReason[i]; exists {
  1400. newDisabledReason[newIndex] = r
  1401. }
  1402. }
  1403. }
  1404. newIndex++
  1405. }
  1406. }
  1407. if deletedCount == 0 {
  1408. c.JSON(http.StatusOK, gin.H{
  1409. "success": false,
  1410. "message": "没有需要删除的自动禁用密钥",
  1411. })
  1412. return
  1413. }
  1414. // Update channel with remaining keys
  1415. channel.Key = strings.Join(remainingKeys, "\n")
  1416. channel.ChannelInfo.MultiKeySize = len(remainingKeys)
  1417. channel.ChannelInfo.MultiKeyStatusList = newStatusList
  1418. channel.ChannelInfo.MultiKeyDisabledTime = newDisabledTime
  1419. channel.ChannelInfo.MultiKeyDisabledReason = newDisabledReason
  1420. err = channel.Update()
  1421. if err != nil {
  1422. common.ApiError(c, err)
  1423. return
  1424. }
  1425. model.InitChannelCache()
  1426. c.JSON(http.StatusOK, gin.H{
  1427. "success": true,
  1428. "message": fmt.Sprintf("已删除 %d 个自动禁用的密钥", deletedCount),
  1429. "data": deletedCount,
  1430. })
  1431. return
  1432. default:
  1433. c.JSON(http.StatusOK, gin.H{
  1434. "success": false,
  1435. "message": "不支持的操作",
  1436. })
  1437. return
  1438. }
  1439. }