channel.go 37 KB

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