channel.go 40 KB

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