channel.go 43 KB

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