channel.go 36 KB

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