channel.go 41 KB

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