channel.go 38 KB

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