channel.go 40 KB

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