channel.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "one-api/common"
  7. "one-api/constant"
  8. "one-api/model"
  9. "strconv"
  10. "strings"
  11. "github.com/gin-gonic/gin"
  12. )
  13. type OpenAIModel struct {
  14. ID string `json:"id"`
  15. Object string `json:"object"`
  16. Created int64 `json:"created"`
  17. OwnedBy string `json:"owned_by"`
  18. Permission []struct {
  19. ID string `json:"id"`
  20. Object string `json:"object"`
  21. Created int64 `json:"created"`
  22. AllowCreateEngine bool `json:"allow_create_engine"`
  23. AllowSampling bool `json:"allow_sampling"`
  24. AllowLogprobs bool `json:"allow_logprobs"`
  25. AllowSearchIndices bool `json:"allow_search_indices"`
  26. AllowView bool `json:"allow_view"`
  27. AllowFineTuning bool `json:"allow_fine_tuning"`
  28. Organization string `json:"organization"`
  29. Group string `json:"group"`
  30. IsBlocking bool `json:"is_blocking"`
  31. } `json:"permission"`
  32. Root string `json:"root"`
  33. Parent string `json:"parent"`
  34. }
  35. type OpenAIModelsResponse struct {
  36. Data []OpenAIModel `json:"data"`
  37. Success bool `json:"success"`
  38. }
  39. func parseStatusFilter(statusParam string) int {
  40. switch strings.ToLower(statusParam) {
  41. case "enabled", "1":
  42. return common.ChannelStatusEnabled
  43. case "disabled", "0":
  44. return 0
  45. default:
  46. return -1
  47. }
  48. }
  49. func GetAllChannels(c *gin.Context) {
  50. pageInfo := common.GetPageQuery(c)
  51. channelData := make([]*model.Channel, 0)
  52. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  53. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  54. statusParam := c.Query("status")
  55. // statusFilter: -1 all, 1 enabled, 0 disabled (include auto & manual)
  56. statusFilter := parseStatusFilter(statusParam)
  57. // type filter
  58. typeStr := c.Query("type")
  59. typeFilter := -1
  60. if typeStr != "" {
  61. if t, err := strconv.Atoi(typeStr); err == nil {
  62. typeFilter = t
  63. }
  64. }
  65. var total int64
  66. if enableTagMode {
  67. tags, err := model.GetPaginatedTags(pageInfo.GetStartIdx(), pageInfo.GetPageSize())
  68. if err != nil {
  69. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  70. return
  71. }
  72. for _, tag := range tags {
  73. if tag == nil || *tag == "" {
  74. continue
  75. }
  76. tagChannels, err := model.GetChannelsByTag(*tag, idSort)
  77. if err != nil {
  78. continue
  79. }
  80. filtered := make([]*model.Channel, 0)
  81. for _, ch := range tagChannels {
  82. if statusFilter == common.ChannelStatusEnabled && ch.Status != common.ChannelStatusEnabled {
  83. continue
  84. }
  85. if statusFilter == 0 && ch.Status == common.ChannelStatusEnabled {
  86. continue
  87. }
  88. if typeFilter >= 0 && ch.Type != typeFilter {
  89. continue
  90. }
  91. filtered = append(filtered, ch)
  92. }
  93. channelData = append(channelData, filtered...)
  94. }
  95. total, _ = model.CountAllTags()
  96. } else {
  97. baseQuery := model.DB.Model(&model.Channel{})
  98. if typeFilter >= 0 {
  99. baseQuery = baseQuery.Where("type = ?", typeFilter)
  100. }
  101. if statusFilter == common.ChannelStatusEnabled {
  102. baseQuery = baseQuery.Where("status = ?", common.ChannelStatusEnabled)
  103. } else if statusFilter == 0 {
  104. baseQuery = baseQuery.Where("status != ?", common.ChannelStatusEnabled)
  105. }
  106. baseQuery.Count(&total)
  107. order := "priority desc"
  108. if idSort {
  109. order = "id desc"
  110. }
  111. err := baseQuery.Order(order).Limit(pageInfo.GetPageSize()).Offset(pageInfo.GetStartIdx()).Omit("key").Find(&channelData).Error
  112. if err != nil {
  113. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  114. return
  115. }
  116. }
  117. countQuery := model.DB.Model(&model.Channel{})
  118. if statusFilter == common.ChannelStatusEnabled {
  119. countQuery = countQuery.Where("status = ?", common.ChannelStatusEnabled)
  120. } else if statusFilter == 0 {
  121. countQuery = countQuery.Where("status != ?", common.ChannelStatusEnabled)
  122. }
  123. var results []struct {
  124. Type int64
  125. Count int64
  126. }
  127. _ = countQuery.Select("type, count(*) as count").Group("type").Find(&results).Error
  128. typeCounts := make(map[int64]int64)
  129. for _, r := range results {
  130. typeCounts[r.Type] = r.Count
  131. }
  132. common.ApiSuccess(c, gin.H{
  133. "items": channelData,
  134. "total": total,
  135. "page": pageInfo.GetPage(),
  136. "page_size": pageInfo.GetPageSize(),
  137. "type_counts": typeCounts,
  138. })
  139. return
  140. }
  141. func FetchUpstreamModels(c *gin.Context) {
  142. id, err := strconv.Atoi(c.Param("id"))
  143. if err != nil {
  144. common.ApiError(c, err)
  145. return
  146. }
  147. channel, err := model.GetChannelById(id, true)
  148. if err != nil {
  149. common.ApiError(c, err)
  150. return
  151. }
  152. baseURL := constant.ChannelBaseURLs[channel.Type]
  153. if channel.GetBaseURL() != "" {
  154. baseURL = channel.GetBaseURL()
  155. }
  156. url := fmt.Sprintf("%s/v1/models", baseURL)
  157. switch channel.Type {
  158. case constant.ChannelTypeGemini:
  159. url = fmt.Sprintf("%s/v1beta/openai/models", baseURL)
  160. case constant.ChannelTypeAli:
  161. url = fmt.Sprintf("%s/compatible-mode/v1/models", baseURL)
  162. }
  163. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  164. if err != nil {
  165. common.ApiError(c, err)
  166. return
  167. }
  168. var result OpenAIModelsResponse
  169. if err = json.Unmarshal(body, &result); err != nil {
  170. c.JSON(http.StatusOK, gin.H{
  171. "success": false,
  172. "message": fmt.Sprintf("解析响应失败: %s", err.Error()),
  173. })
  174. return
  175. }
  176. var ids []string
  177. for _, model := range result.Data {
  178. id := model.ID
  179. if channel.Type == constant.ChannelTypeGemini {
  180. id = strings.TrimPrefix(id, "models/")
  181. }
  182. ids = append(ids, id)
  183. }
  184. c.JSON(http.StatusOK, gin.H{
  185. "success": true,
  186. "message": "",
  187. "data": ids,
  188. })
  189. }
  190. func FixChannelsAbilities(c *gin.Context) {
  191. success, fails, err := model.FixAbility()
  192. if err != nil {
  193. common.ApiError(c, err)
  194. return
  195. }
  196. c.JSON(http.StatusOK, gin.H{
  197. "success": true,
  198. "message": "",
  199. "data": gin.H{
  200. "success": success,
  201. "fails": fails,
  202. },
  203. })
  204. }
  205. func SearchChannels(c *gin.Context) {
  206. keyword := c.Query("keyword")
  207. group := c.Query("group")
  208. modelKeyword := c.Query("model")
  209. statusParam := c.Query("status")
  210. statusFilter := parseStatusFilter(statusParam)
  211. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  212. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  213. channelData := make([]*model.Channel, 0)
  214. if enableTagMode {
  215. tags, err := model.SearchTags(keyword, group, modelKeyword, idSort)
  216. if err != nil {
  217. c.JSON(http.StatusOK, gin.H{
  218. "success": false,
  219. "message": err.Error(),
  220. })
  221. return
  222. }
  223. for _, tag := range tags {
  224. if tag != nil && *tag != "" {
  225. tagChannel, err := model.GetChannelsByTag(*tag, idSort)
  226. if err == nil {
  227. channelData = append(channelData, tagChannel...)
  228. }
  229. }
  230. }
  231. } else {
  232. channels, err := model.SearchChannels(keyword, group, modelKeyword, idSort)
  233. if err != nil {
  234. c.JSON(http.StatusOK, gin.H{
  235. "success": false,
  236. "message": err.Error(),
  237. })
  238. return
  239. }
  240. channelData = channels
  241. }
  242. if statusFilter == common.ChannelStatusEnabled || statusFilter == 0 {
  243. filtered := make([]*model.Channel, 0, len(channelData))
  244. for _, ch := range channelData {
  245. if statusFilter == common.ChannelStatusEnabled && ch.Status != common.ChannelStatusEnabled {
  246. continue
  247. }
  248. if statusFilter == 0 && ch.Status == common.ChannelStatusEnabled {
  249. continue
  250. }
  251. filtered = append(filtered, ch)
  252. }
  253. channelData = filtered
  254. }
  255. // calculate type counts for search results
  256. typeCounts := make(map[int64]int64)
  257. for _, channel := range channelData {
  258. typeCounts[int64(channel.Type)]++
  259. }
  260. typeParam := c.Query("type")
  261. typeFilter := -1
  262. if typeParam != "" {
  263. if tp, err := strconv.Atoi(typeParam); err == nil {
  264. typeFilter = tp
  265. }
  266. }
  267. if typeFilter >= 0 {
  268. filtered := make([]*model.Channel, 0, len(channelData))
  269. for _, ch := range channelData {
  270. if ch.Type == typeFilter {
  271. filtered = append(filtered, ch)
  272. }
  273. }
  274. channelData = filtered
  275. }
  276. page, _ := strconv.Atoi(c.DefaultQuery("p", "1"))
  277. pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
  278. if page < 1 {
  279. page = 1
  280. }
  281. if pageSize <= 0 {
  282. pageSize = 20
  283. }
  284. total := len(channelData)
  285. startIdx := (page - 1) * pageSize
  286. if startIdx > total {
  287. startIdx = total
  288. }
  289. endIdx := startIdx + pageSize
  290. if endIdx > total {
  291. endIdx = total
  292. }
  293. pagedData := channelData[startIdx:endIdx]
  294. c.JSON(http.StatusOK, gin.H{
  295. "success": true,
  296. "message": "",
  297. "data": gin.H{
  298. "items": pagedData,
  299. "total": total,
  300. "type_counts": typeCounts,
  301. },
  302. })
  303. return
  304. }
  305. func GetChannel(c *gin.Context) {
  306. id, err := strconv.Atoi(c.Param("id"))
  307. if err != nil {
  308. common.ApiError(c, err)
  309. return
  310. }
  311. channel, err := model.GetChannelById(id, false)
  312. if err != nil {
  313. common.ApiError(c, err)
  314. return
  315. }
  316. c.JSON(http.StatusOK, gin.H{
  317. "success": true,
  318. "message": "",
  319. "data": channel,
  320. })
  321. return
  322. }
  323. // validateChannel 通用的渠道校验函数
  324. func validateChannel(channel *model.Channel, isAdd bool) error {
  325. // 校验 channel settings
  326. if err := channel.ValidateSettings(); err != nil {
  327. return fmt.Errorf("渠道额外设置[channel setting] 格式错误:%s", err.Error())
  328. }
  329. // 如果是添加操作,检查 channel 和 key 是否为空
  330. if isAdd {
  331. if channel == nil || channel.Key == "" {
  332. return fmt.Errorf("channel cannot be empty")
  333. }
  334. // 检查模型名称长度是否超过 255
  335. for _, m := range channel.GetModels() {
  336. if len(m) > 255 {
  337. return fmt.Errorf("模型名称过长: %s", m)
  338. }
  339. }
  340. }
  341. // VertexAI 特殊校验
  342. if channel.Type == constant.ChannelTypeVertexAi {
  343. if channel.Other == "" {
  344. return fmt.Errorf("部署地区不能为空")
  345. }
  346. regionMap, err := common.StrToMap(channel.Other)
  347. if err != nil {
  348. return fmt.Errorf("部署地区必须是标准的Json格式,例如{\"default\": \"us-central1\", \"region2\": \"us-east1\"}")
  349. }
  350. if regionMap["default"] == nil {
  351. return fmt.Errorf("部署地区必须包含default字段")
  352. }
  353. }
  354. return nil
  355. }
  356. type AddChannelRequest struct {
  357. Mode string `json:"mode"`
  358. MultiKeyMode constant.MultiKeyMode `json:"multi_key_mode"`
  359. Channel *model.Channel `json:"channel"`
  360. }
  361. func getVertexArrayKeys(keys string) ([]string, error) {
  362. if keys == "" {
  363. return nil, nil
  364. }
  365. var keyArray []interface{}
  366. err := common.Unmarshal([]byte(keys), &keyArray)
  367. if err != nil {
  368. return nil, fmt.Errorf("批量添加 Vertex AI 必须使用标准的JsonArray格式,例如[{key1}, {key2}...],请检查输入: %w", err)
  369. }
  370. cleanKeys := make([]string, 0, len(keyArray))
  371. for _, key := range keyArray {
  372. var keyStr string
  373. switch v := key.(type) {
  374. case string:
  375. keyStr = strings.TrimSpace(v)
  376. default:
  377. bytes, err := json.Marshal(v)
  378. if err != nil {
  379. return nil, fmt.Errorf("Vertex AI key JSON 编码失败: %w", err)
  380. }
  381. keyStr = string(bytes)
  382. }
  383. if keyStr != "" {
  384. cleanKeys = append(cleanKeys, keyStr)
  385. }
  386. }
  387. if len(cleanKeys) == 0 {
  388. return nil, fmt.Errorf("批量添加 Vertex AI 的 keys 不能为空")
  389. }
  390. return cleanKeys, nil
  391. }
  392. func AddChannel(c *gin.Context) {
  393. addChannelRequest := AddChannelRequest{}
  394. err := c.ShouldBindJSON(&addChannelRequest)
  395. if err != nil {
  396. common.ApiError(c, err)
  397. return
  398. }
  399. // 使用统一的校验函数
  400. if err := validateChannel(addChannelRequest.Channel, true); err != nil {
  401. c.JSON(http.StatusOK, gin.H{
  402. "success": false,
  403. "message": err.Error(),
  404. })
  405. return
  406. }
  407. addChannelRequest.Channel.CreatedTime = common.GetTimestamp()
  408. keys := make([]string, 0)
  409. switch addChannelRequest.Mode {
  410. case "multi_to_single":
  411. addChannelRequest.Channel.ChannelInfo.IsMultiKey = true
  412. addChannelRequest.Channel.ChannelInfo.MultiKeyMode = addChannelRequest.MultiKeyMode
  413. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi {
  414. array, err := getVertexArrayKeys(addChannelRequest.Channel.Key)
  415. if err != nil {
  416. c.JSON(http.StatusOK, gin.H{
  417. "success": false,
  418. "message": err.Error(),
  419. })
  420. return
  421. }
  422. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(array)
  423. addChannelRequest.Channel.Key = strings.Join(array, "\n")
  424. } else {
  425. cleanKeys := make([]string, 0)
  426. for _, key := range strings.Split(addChannelRequest.Channel.Key, "\n") {
  427. if key == "" {
  428. continue
  429. }
  430. key = strings.TrimSpace(key)
  431. cleanKeys = append(cleanKeys, key)
  432. }
  433. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(cleanKeys)
  434. addChannelRequest.Channel.Key = strings.Join(cleanKeys, "\n")
  435. }
  436. keys = []string{addChannelRequest.Channel.Key}
  437. case "batch":
  438. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi {
  439. // multi json
  440. keys, err = getVertexArrayKeys(addChannelRequest.Channel.Key)
  441. if err != nil {
  442. c.JSON(http.StatusOK, gin.H{
  443. "success": false,
  444. "message": err.Error(),
  445. })
  446. return
  447. }
  448. } else {
  449. keys = strings.Split(addChannelRequest.Channel.Key, "\n")
  450. }
  451. case "single":
  452. keys = []string{addChannelRequest.Channel.Key}
  453. default:
  454. c.JSON(http.StatusOK, gin.H{
  455. "success": false,
  456. "message": "不支持的添加模式",
  457. })
  458. return
  459. }
  460. channels := make([]model.Channel, 0, len(keys))
  461. for _, key := range keys {
  462. if key == "" {
  463. continue
  464. }
  465. localChannel := addChannelRequest.Channel
  466. localChannel.Key = key
  467. channels = append(channels, *localChannel)
  468. }
  469. err = model.BatchInsertChannels(channels)
  470. if err != nil {
  471. common.ApiError(c, err)
  472. return
  473. }
  474. c.JSON(http.StatusOK, gin.H{
  475. "success": true,
  476. "message": "",
  477. })
  478. return
  479. }
  480. func DeleteChannel(c *gin.Context) {
  481. id, _ := strconv.Atoi(c.Param("id"))
  482. channel := model.Channel{Id: id}
  483. err := channel.Delete()
  484. if err != nil {
  485. common.ApiError(c, err)
  486. return
  487. }
  488. model.InitChannelCache()
  489. c.JSON(http.StatusOK, gin.H{
  490. "success": true,
  491. "message": "",
  492. })
  493. return
  494. }
  495. func DeleteDisabledChannel(c *gin.Context) {
  496. rows, err := model.DeleteDisabledChannel()
  497. if err != nil {
  498. common.ApiError(c, err)
  499. return
  500. }
  501. model.InitChannelCache()
  502. c.JSON(http.StatusOK, gin.H{
  503. "success": true,
  504. "message": "",
  505. "data": rows,
  506. })
  507. return
  508. }
  509. type ChannelTag struct {
  510. Tag string `json:"tag"`
  511. NewTag *string `json:"new_tag"`
  512. Priority *int64 `json:"priority"`
  513. Weight *uint `json:"weight"`
  514. ModelMapping *string `json:"model_mapping"`
  515. Models *string `json:"models"`
  516. Groups *string `json:"groups"`
  517. }
  518. func DisableTagChannels(c *gin.Context) {
  519. channelTag := ChannelTag{}
  520. err := c.ShouldBindJSON(&channelTag)
  521. if err != nil || channelTag.Tag == "" {
  522. c.JSON(http.StatusOK, gin.H{
  523. "success": false,
  524. "message": "参数错误",
  525. })
  526. return
  527. }
  528. err = model.DisableChannelByTag(channelTag.Tag)
  529. if err != nil {
  530. common.ApiError(c, err)
  531. return
  532. }
  533. model.InitChannelCache()
  534. c.JSON(http.StatusOK, gin.H{
  535. "success": true,
  536. "message": "",
  537. })
  538. return
  539. }
  540. func EnableTagChannels(c *gin.Context) {
  541. channelTag := ChannelTag{}
  542. err := c.ShouldBindJSON(&channelTag)
  543. if err != nil || channelTag.Tag == "" {
  544. c.JSON(http.StatusOK, gin.H{
  545. "success": false,
  546. "message": "参数错误",
  547. })
  548. return
  549. }
  550. err = model.EnableChannelByTag(channelTag.Tag)
  551. if err != nil {
  552. common.ApiError(c, err)
  553. return
  554. }
  555. model.InitChannelCache()
  556. c.JSON(http.StatusOK, gin.H{
  557. "success": true,
  558. "message": "",
  559. })
  560. return
  561. }
  562. func EditTagChannels(c *gin.Context) {
  563. channelTag := ChannelTag{}
  564. err := c.ShouldBindJSON(&channelTag)
  565. if err != nil {
  566. c.JSON(http.StatusOK, gin.H{
  567. "success": false,
  568. "message": "参数错误",
  569. })
  570. return
  571. }
  572. if channelTag.Tag == "" {
  573. c.JSON(http.StatusOK, gin.H{
  574. "success": false,
  575. "message": "tag不能为空",
  576. })
  577. return
  578. }
  579. err = model.EditChannelByTag(channelTag.Tag, channelTag.NewTag, channelTag.ModelMapping, channelTag.Models, channelTag.Groups, channelTag.Priority, channelTag.Weight)
  580. if err != nil {
  581. common.ApiError(c, err)
  582. return
  583. }
  584. model.InitChannelCache()
  585. c.JSON(http.StatusOK, gin.H{
  586. "success": true,
  587. "message": "",
  588. })
  589. return
  590. }
  591. type ChannelBatch struct {
  592. Ids []int `json:"ids"`
  593. Tag *string `json:"tag"`
  594. }
  595. func DeleteChannelBatch(c *gin.Context) {
  596. channelBatch := ChannelBatch{}
  597. err := c.ShouldBindJSON(&channelBatch)
  598. if err != nil || len(channelBatch.Ids) == 0 {
  599. c.JSON(http.StatusOK, gin.H{
  600. "success": false,
  601. "message": "参数错误",
  602. })
  603. return
  604. }
  605. err = model.BatchDeleteChannels(channelBatch.Ids)
  606. if err != nil {
  607. common.ApiError(c, err)
  608. return
  609. }
  610. model.InitChannelCache()
  611. c.JSON(http.StatusOK, gin.H{
  612. "success": true,
  613. "message": "",
  614. "data": len(channelBatch.Ids),
  615. })
  616. return
  617. }
  618. type PatchChannel struct {
  619. model.Channel
  620. MultiKeyMode *string `json:"multi_key_mode"`
  621. }
  622. func UpdateChannel(c *gin.Context) {
  623. channel := PatchChannel{}
  624. err := c.ShouldBindJSON(&channel)
  625. if err != nil {
  626. common.ApiError(c, err)
  627. return
  628. }
  629. // 使用统一的校验函数
  630. if err := validateChannel(&channel.Channel, false); err != nil {
  631. c.JSON(http.StatusOK, gin.H{
  632. "success": false,
  633. "message": err.Error(),
  634. })
  635. return
  636. }
  637. // Preserve existing ChannelInfo to ensure multi-key channels keep correct state even if the client does not send ChannelInfo in the request.
  638. originChannel, err := model.GetChannelById(channel.Id, false)
  639. if err != nil {
  640. c.JSON(http.StatusOK, gin.H{
  641. "success": false,
  642. "message": err.Error(),
  643. })
  644. return
  645. }
  646. // Always copy the original ChannelInfo so that fields like IsMultiKey and MultiKeySize are retained.
  647. channel.ChannelInfo = originChannel.ChannelInfo
  648. // If the request explicitly specifies a new MultiKeyMode, apply it on top of the original info.
  649. if channel.MultiKeyMode != nil && *channel.MultiKeyMode != "" {
  650. channel.ChannelInfo.MultiKeyMode = constant.MultiKeyMode(*channel.MultiKeyMode)
  651. }
  652. err = channel.Update()
  653. if err != nil {
  654. common.ApiError(c, err)
  655. return
  656. }
  657. model.InitChannelCache()
  658. channel.Key = ""
  659. c.JSON(http.StatusOK, gin.H{
  660. "success": true,
  661. "message": "",
  662. "data": channel,
  663. })
  664. return
  665. }
  666. func FetchModels(c *gin.Context) {
  667. var req struct {
  668. BaseURL string `json:"base_url"`
  669. Type int `json:"type"`
  670. Key string `json:"key"`
  671. }
  672. if err := c.ShouldBindJSON(&req); err != nil {
  673. c.JSON(http.StatusBadRequest, gin.H{
  674. "success": false,
  675. "message": "Invalid request",
  676. })
  677. return
  678. }
  679. baseURL := req.BaseURL
  680. if baseURL == "" {
  681. baseURL = constant.ChannelBaseURLs[req.Type]
  682. }
  683. client := &http.Client{}
  684. url := fmt.Sprintf("%s/v1/models", baseURL)
  685. request, err := http.NewRequest("GET", url, nil)
  686. if err != nil {
  687. c.JSON(http.StatusInternalServerError, gin.H{
  688. "success": false,
  689. "message": err.Error(),
  690. })
  691. return
  692. }
  693. // remove line breaks and extra spaces.
  694. key := strings.TrimSpace(req.Key)
  695. // If the key contains a line break, only take the first part.
  696. key = strings.Split(key, "\n")[0]
  697. request.Header.Set("Authorization", "Bearer "+key)
  698. response, err := client.Do(request)
  699. if err != nil {
  700. c.JSON(http.StatusInternalServerError, gin.H{
  701. "success": false,
  702. "message": err.Error(),
  703. })
  704. return
  705. }
  706. //check status code
  707. if response.StatusCode != http.StatusOK {
  708. c.JSON(http.StatusInternalServerError, gin.H{
  709. "success": false,
  710. "message": "Failed to fetch models",
  711. })
  712. return
  713. }
  714. defer response.Body.Close()
  715. var result struct {
  716. Data []struct {
  717. ID string `json:"id"`
  718. } `json:"data"`
  719. }
  720. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  721. c.JSON(http.StatusInternalServerError, gin.H{
  722. "success": false,
  723. "message": err.Error(),
  724. })
  725. return
  726. }
  727. var models []string
  728. for _, model := range result.Data {
  729. models = append(models, model.ID)
  730. }
  731. c.JSON(http.StatusOK, gin.H{
  732. "success": true,
  733. "data": models,
  734. })
  735. }
  736. func BatchSetChannelTag(c *gin.Context) {
  737. channelBatch := ChannelBatch{}
  738. err := c.ShouldBindJSON(&channelBatch)
  739. if err != nil || len(channelBatch.Ids) == 0 {
  740. c.JSON(http.StatusOK, gin.H{
  741. "success": false,
  742. "message": "参数错误",
  743. })
  744. return
  745. }
  746. err = model.BatchSetChannelTag(channelBatch.Ids, channelBatch.Tag)
  747. if err != nil {
  748. common.ApiError(c, err)
  749. return
  750. }
  751. model.InitChannelCache()
  752. c.JSON(http.StatusOK, gin.H{
  753. "success": true,
  754. "message": "",
  755. "data": len(channelBatch.Ids),
  756. })
  757. return
  758. }
  759. func GetTagModels(c *gin.Context) {
  760. tag := c.Query("tag")
  761. if tag == "" {
  762. c.JSON(http.StatusBadRequest, gin.H{
  763. "success": false,
  764. "message": "tag不能为空",
  765. })
  766. return
  767. }
  768. channels, err := model.GetChannelsByTag(tag, false) // Assuming false for idSort is fine here
  769. if err != nil {
  770. c.JSON(http.StatusInternalServerError, gin.H{
  771. "success": false,
  772. "message": err.Error(),
  773. })
  774. return
  775. }
  776. var longestModels string
  777. maxLength := 0
  778. // Find the longest models string among all channels with the given tag
  779. for _, channel := range channels {
  780. if channel.Models != "" {
  781. currentModels := strings.Split(channel.Models, ",")
  782. if len(currentModels) > maxLength {
  783. maxLength = len(currentModels)
  784. longestModels = channel.Models
  785. }
  786. }
  787. }
  788. c.JSON(http.StatusOK, gin.H{
  789. "success": true,
  790. "message": "",
  791. "data": longestModels,
  792. })
  793. return
  794. }
  795. // CopyChannel handles cloning an existing channel with its key.
  796. // POST /api/channel/copy/:id
  797. // Optional query params:
  798. //
  799. // suffix - string appended to the original name (default "_复制")
  800. // reset_balance - bool, when true will reset balance & used_quota to 0 (default true)
  801. func CopyChannel(c *gin.Context) {
  802. id, err := strconv.Atoi(c.Param("id"))
  803. if err != nil {
  804. c.JSON(http.StatusOK, gin.H{"success": false, "message": "invalid id"})
  805. return
  806. }
  807. suffix := c.DefaultQuery("suffix", "_复制")
  808. resetBalance := true
  809. if rbStr := c.DefaultQuery("reset_balance", "true"); rbStr != "" {
  810. if v, err := strconv.ParseBool(rbStr); err == nil {
  811. resetBalance = v
  812. }
  813. }
  814. // fetch original channel with key
  815. origin, err := model.GetChannelById(id, true)
  816. if err != nil {
  817. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  818. return
  819. }
  820. // clone channel
  821. clone := *origin // shallow copy is sufficient as we will overwrite primitives
  822. clone.Id = 0 // let DB auto-generate
  823. clone.CreatedTime = common.GetTimestamp()
  824. clone.Name = origin.Name + suffix
  825. clone.TestTime = 0
  826. clone.ResponseTime = 0
  827. if resetBalance {
  828. clone.Balance = 0
  829. clone.UsedQuota = 0
  830. }
  831. // insert
  832. if err := model.BatchInsertChannels([]model.Channel{clone}); err != nil {
  833. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  834. return
  835. }
  836. model.InitChannelCache()
  837. // success
  838. c.JSON(http.StatusOK, gin.H{"success": true, "message": "", "data": gin.H{"id": clone.Id}})
  839. }