channel.go 40 KB

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