channel.go 42 KB

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