channel.go 38 KB

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