channel.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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. p, _ := strconv.Atoi(c.Query("p"))
  51. pageSize, _ := strconv.Atoi(c.Query("page_size"))
  52. if p < 1 {
  53. p = 1
  54. }
  55. if pageSize < 1 {
  56. pageSize = common.ItemsPerPage
  57. }
  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((p-1)*pageSize, pageSize)
  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(pageSize).Offset((p - 1) * pageSize).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. countQuery := model.DB.Model(&model.Channel{})
  125. if statusFilter == common.ChannelStatusEnabled {
  126. countQuery = countQuery.Where("status = ?", common.ChannelStatusEnabled)
  127. } else if statusFilter == 0 {
  128. countQuery = countQuery.Where("status != ?", common.ChannelStatusEnabled)
  129. }
  130. var results []struct {
  131. Type int64
  132. Count int64
  133. }
  134. _ = countQuery.Select("type, count(*) as count").Group("type").Find(&results).Error
  135. typeCounts := make(map[int64]int64)
  136. for _, r := range results {
  137. typeCounts[r.Type] = r.Count
  138. }
  139. c.JSON(http.StatusOK, gin.H{
  140. "success": true,
  141. "message": "",
  142. "data": gin.H{
  143. "items": channelData,
  144. "total": total,
  145. "page": p,
  146. "page_size": pageSize,
  147. "type_counts": typeCounts,
  148. },
  149. })
  150. return
  151. }
  152. func FetchUpstreamModels(c *gin.Context) {
  153. id, err := strconv.Atoi(c.Param("id"))
  154. if err != nil {
  155. c.JSON(http.StatusOK, gin.H{
  156. "success": false,
  157. "message": err.Error(),
  158. })
  159. return
  160. }
  161. channel, err := model.GetChannelById(id, true)
  162. if err != nil {
  163. c.JSON(http.StatusOK, gin.H{
  164. "success": false,
  165. "message": err.Error(),
  166. })
  167. return
  168. }
  169. baseURL := constant.ChannelBaseURLs[channel.Type]
  170. if channel.GetBaseURL() != "" {
  171. baseURL = channel.GetBaseURL()
  172. }
  173. url := fmt.Sprintf("%s/v1/models", baseURL)
  174. switch channel.Type {
  175. case constant.ChannelTypeGemini:
  176. url = fmt.Sprintf("%s/v1beta/openai/models", baseURL)
  177. case constant.ChannelTypeAli:
  178. url = fmt.Sprintf("%s/compatible-mode/v1/models", baseURL)
  179. }
  180. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  181. if err != nil {
  182. c.JSON(http.StatusOK, gin.H{
  183. "success": false,
  184. "message": err.Error(),
  185. })
  186. return
  187. }
  188. var result OpenAIModelsResponse
  189. if err = json.Unmarshal(body, &result); err != nil {
  190. c.JSON(http.StatusOK, gin.H{
  191. "success": false,
  192. "message": fmt.Sprintf("解析响应失败: %s", err.Error()),
  193. })
  194. return
  195. }
  196. var ids []string
  197. for _, model := range result.Data {
  198. id := model.ID
  199. if channel.Type == constant.ChannelTypeGemini {
  200. id = strings.TrimPrefix(id, "models/")
  201. }
  202. ids = append(ids, id)
  203. }
  204. c.JSON(http.StatusOK, gin.H{
  205. "success": true,
  206. "message": "",
  207. "data": ids,
  208. })
  209. }
  210. func FixChannelsAbilities(c *gin.Context) {
  211. success, fails, err := model.FixAbility()
  212. if err != nil {
  213. c.JSON(http.StatusOK, gin.H{
  214. "success": false,
  215. "message": err.Error(),
  216. })
  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. c.JSON(http.StatusOK, gin.H{
  318. "success": true,
  319. "message": "",
  320. "data": gin.H{
  321. "items": pagedData,
  322. "total": total,
  323. "type_counts": typeCounts,
  324. },
  325. })
  326. return
  327. }
  328. func GetChannel(c *gin.Context) {
  329. id, err := strconv.Atoi(c.Param("id"))
  330. if err != nil {
  331. c.JSON(http.StatusOK, gin.H{
  332. "success": false,
  333. "message": err.Error(),
  334. })
  335. return
  336. }
  337. channel, err := model.GetChannelById(id, false)
  338. if err != nil {
  339. c.JSON(http.StatusOK, gin.H{
  340. "success": false,
  341. "message": err.Error(),
  342. })
  343. return
  344. }
  345. c.JSON(http.StatusOK, gin.H{
  346. "success": true,
  347. "message": "",
  348. "data": channel,
  349. })
  350. return
  351. }
  352. func AddChannel(c *gin.Context) {
  353. channel := model.Channel{}
  354. err := c.ShouldBindJSON(&channel)
  355. if err != nil {
  356. c.JSON(http.StatusOK, gin.H{
  357. "success": false,
  358. "message": err.Error(),
  359. })
  360. return
  361. }
  362. err = channel.ValidateSettings()
  363. if err != nil {
  364. c.JSON(http.StatusOK, gin.H{
  365. "success": false,
  366. "message": "channel setting 格式错误:" + err.Error(),
  367. })
  368. return
  369. }
  370. channel.CreatedTime = common.GetTimestamp()
  371. keys := strings.Split(channel.Key, "\n")
  372. if channel.Type == constant.ChannelTypeVertexAi {
  373. if channel.Other == "" {
  374. c.JSON(http.StatusOK, gin.H{
  375. "success": false,
  376. "message": "部署地区不能为空",
  377. })
  378. return
  379. } else {
  380. if common.IsJsonStr(channel.Other) {
  381. // must have default
  382. regionMap := common.StrToMap(channel.Other)
  383. if regionMap["default"] == nil {
  384. c.JSON(http.StatusOK, gin.H{
  385. "success": false,
  386. "message": "部署地区必须包含default字段",
  387. })
  388. return
  389. }
  390. }
  391. }
  392. keys = []string{channel.Key}
  393. }
  394. channels := make([]model.Channel, 0, len(keys))
  395. for _, key := range keys {
  396. if key == "" {
  397. continue
  398. }
  399. localChannel := channel
  400. localChannel.Key = key
  401. // Validate the length of the model name
  402. models := strings.Split(localChannel.Models, ",")
  403. for _, model := range models {
  404. if len(model) > 255 {
  405. c.JSON(http.StatusOK, gin.H{
  406. "success": false,
  407. "message": fmt.Sprintf("模型名称过长: %s", model),
  408. })
  409. return
  410. }
  411. }
  412. channels = append(channels, localChannel)
  413. }
  414. err = model.BatchInsertChannels(channels)
  415. if err != nil {
  416. c.JSON(http.StatusOK, gin.H{
  417. "success": false,
  418. "message": err.Error(),
  419. })
  420. return
  421. }
  422. c.JSON(http.StatusOK, gin.H{
  423. "success": true,
  424. "message": "",
  425. })
  426. return
  427. }
  428. func DeleteChannel(c *gin.Context) {
  429. id, _ := strconv.Atoi(c.Param("id"))
  430. channel := model.Channel{Id: id}
  431. err := channel.Delete()
  432. if err != nil {
  433. c.JSON(http.StatusOK, gin.H{
  434. "success": false,
  435. "message": err.Error(),
  436. })
  437. return
  438. }
  439. c.JSON(http.StatusOK, gin.H{
  440. "success": true,
  441. "message": "",
  442. })
  443. return
  444. }
  445. func DeleteDisabledChannel(c *gin.Context) {
  446. rows, err := model.DeleteDisabledChannel()
  447. if err != nil {
  448. c.JSON(http.StatusOK, gin.H{
  449. "success": false,
  450. "message": err.Error(),
  451. })
  452. return
  453. }
  454. c.JSON(http.StatusOK, gin.H{
  455. "success": true,
  456. "message": "",
  457. "data": rows,
  458. })
  459. return
  460. }
  461. type ChannelTag struct {
  462. Tag string `json:"tag"`
  463. NewTag *string `json:"new_tag"`
  464. Priority *int64 `json:"priority"`
  465. Weight *uint `json:"weight"`
  466. ModelMapping *string `json:"model_mapping"`
  467. Models *string `json:"models"`
  468. Groups *string `json:"groups"`
  469. }
  470. func DisableTagChannels(c *gin.Context) {
  471. channelTag := ChannelTag{}
  472. err := c.ShouldBindJSON(&channelTag)
  473. if err != nil || channelTag.Tag == "" {
  474. c.JSON(http.StatusOK, gin.H{
  475. "success": false,
  476. "message": "参数错误",
  477. })
  478. return
  479. }
  480. err = model.DisableChannelByTag(channelTag.Tag)
  481. if err != nil {
  482. c.JSON(http.StatusOK, gin.H{
  483. "success": false,
  484. "message": err.Error(),
  485. })
  486. return
  487. }
  488. c.JSON(http.StatusOK, gin.H{
  489. "success": true,
  490. "message": "",
  491. })
  492. return
  493. }
  494. func EnableTagChannels(c *gin.Context) {
  495. channelTag := ChannelTag{}
  496. err := c.ShouldBindJSON(&channelTag)
  497. if err != nil || channelTag.Tag == "" {
  498. c.JSON(http.StatusOK, gin.H{
  499. "success": false,
  500. "message": "参数错误",
  501. })
  502. return
  503. }
  504. err = model.EnableChannelByTag(channelTag.Tag)
  505. if err != nil {
  506. c.JSON(http.StatusOK, gin.H{
  507. "success": false,
  508. "message": err.Error(),
  509. })
  510. return
  511. }
  512. c.JSON(http.StatusOK, gin.H{
  513. "success": true,
  514. "message": "",
  515. })
  516. return
  517. }
  518. func EditTagChannels(c *gin.Context) {
  519. channelTag := ChannelTag{}
  520. err := c.ShouldBindJSON(&channelTag)
  521. if err != nil {
  522. c.JSON(http.StatusOK, gin.H{
  523. "success": false,
  524. "message": "参数错误",
  525. })
  526. return
  527. }
  528. if channelTag.Tag == "" {
  529. c.JSON(http.StatusOK, gin.H{
  530. "success": false,
  531. "message": "tag不能为空",
  532. })
  533. return
  534. }
  535. err = model.EditChannelByTag(channelTag.Tag, channelTag.NewTag, channelTag.ModelMapping, channelTag.Models, channelTag.Groups, channelTag.Priority, channelTag.Weight)
  536. if err != nil {
  537. c.JSON(http.StatusOK, gin.H{
  538. "success": false,
  539. "message": err.Error(),
  540. })
  541. return
  542. }
  543. c.JSON(http.StatusOK, gin.H{
  544. "success": true,
  545. "message": "",
  546. })
  547. return
  548. }
  549. type ChannelBatch struct {
  550. Ids []int `json:"ids"`
  551. Tag *string `json:"tag"`
  552. }
  553. func DeleteChannelBatch(c *gin.Context) {
  554. channelBatch := ChannelBatch{}
  555. err := c.ShouldBindJSON(&channelBatch)
  556. if err != nil || len(channelBatch.Ids) == 0 {
  557. c.JSON(http.StatusOK, gin.H{
  558. "success": false,
  559. "message": "参数错误",
  560. })
  561. return
  562. }
  563. err = model.BatchDeleteChannels(channelBatch.Ids)
  564. if err != nil {
  565. c.JSON(http.StatusOK, gin.H{
  566. "success": false,
  567. "message": err.Error(),
  568. })
  569. return
  570. }
  571. c.JSON(http.StatusOK, gin.H{
  572. "success": true,
  573. "message": "",
  574. "data": len(channelBatch.Ids),
  575. })
  576. return
  577. }
  578. func UpdateChannel(c *gin.Context) {
  579. channel := model.Channel{}
  580. err := c.ShouldBindJSON(&channel)
  581. if err != nil {
  582. c.JSON(http.StatusOK, gin.H{
  583. "success": false,
  584. "message": err.Error(),
  585. })
  586. return
  587. }
  588. err = channel.ValidateSettings()
  589. if err != nil {
  590. c.JSON(http.StatusOK, gin.H{
  591. "success": false,
  592. "message": "channel setting 格式错误:" + err.Error(),
  593. })
  594. return
  595. }
  596. if channel.Type == constant.ChannelTypeVertexAi {
  597. if channel.Other == "" {
  598. c.JSON(http.StatusOK, gin.H{
  599. "success": false,
  600. "message": "部署地区不能为空",
  601. })
  602. return
  603. } else {
  604. if common.IsJsonStr(channel.Other) {
  605. // must have default
  606. regionMap := common.StrToMap(channel.Other)
  607. if regionMap["default"] == nil {
  608. c.JSON(http.StatusOK, gin.H{
  609. "success": false,
  610. "message": "部署地区必须包含default字段",
  611. })
  612. return
  613. }
  614. }
  615. }
  616. }
  617. err = channel.Update()
  618. if err != nil {
  619. c.JSON(http.StatusOK, gin.H{
  620. "success": false,
  621. "message": err.Error(),
  622. })
  623. return
  624. }
  625. channel.Key = ""
  626. c.JSON(http.StatusOK, gin.H{
  627. "success": true,
  628. "message": "",
  629. "data": channel,
  630. })
  631. return
  632. }
  633. func FetchModels(c *gin.Context) {
  634. var req struct {
  635. BaseURL string `json:"base_url"`
  636. Type int `json:"type"`
  637. Key string `json:"key"`
  638. }
  639. if err := c.ShouldBindJSON(&req); err != nil {
  640. c.JSON(http.StatusBadRequest, gin.H{
  641. "success": false,
  642. "message": "Invalid request",
  643. })
  644. return
  645. }
  646. baseURL := req.BaseURL
  647. if baseURL == "" {
  648. baseURL = constant.ChannelBaseURLs[req.Type]
  649. }
  650. client := &http.Client{}
  651. url := fmt.Sprintf("%s/v1/models", baseURL)
  652. request, err := http.NewRequest("GET", url, nil)
  653. if err != nil {
  654. c.JSON(http.StatusInternalServerError, gin.H{
  655. "success": false,
  656. "message": err.Error(),
  657. })
  658. return
  659. }
  660. // remove line breaks and extra spaces.
  661. key := strings.TrimSpace(req.Key)
  662. // If the key contains a line break, only take the first part.
  663. key = strings.Split(key, "\n")[0]
  664. request.Header.Set("Authorization", "Bearer "+key)
  665. response, err := client.Do(request)
  666. if err != nil {
  667. c.JSON(http.StatusInternalServerError, gin.H{
  668. "success": false,
  669. "message": err.Error(),
  670. })
  671. return
  672. }
  673. //check status code
  674. if response.StatusCode != http.StatusOK {
  675. c.JSON(http.StatusInternalServerError, gin.H{
  676. "success": false,
  677. "message": "Failed to fetch models",
  678. })
  679. return
  680. }
  681. defer response.Body.Close()
  682. var result struct {
  683. Data []struct {
  684. ID string `json:"id"`
  685. } `json:"data"`
  686. }
  687. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  688. c.JSON(http.StatusInternalServerError, gin.H{
  689. "success": false,
  690. "message": err.Error(),
  691. })
  692. return
  693. }
  694. var models []string
  695. for _, model := range result.Data {
  696. models = append(models, model.ID)
  697. }
  698. c.JSON(http.StatusOK, gin.H{
  699. "success": true,
  700. "data": models,
  701. })
  702. }
  703. func BatchSetChannelTag(c *gin.Context) {
  704. channelBatch := ChannelBatch{}
  705. err := c.ShouldBindJSON(&channelBatch)
  706. if err != nil || len(channelBatch.Ids) == 0 {
  707. c.JSON(http.StatusOK, gin.H{
  708. "success": false,
  709. "message": "参数错误",
  710. })
  711. return
  712. }
  713. err = model.BatchSetChannelTag(channelBatch.Ids, channelBatch.Tag)
  714. if err != nil {
  715. c.JSON(http.StatusOK, gin.H{
  716. "success": false,
  717. "message": err.Error(),
  718. })
  719. return
  720. }
  721. c.JSON(http.StatusOK, gin.H{
  722. "success": true,
  723. "message": "",
  724. "data": len(channelBatch.Ids),
  725. })
  726. return
  727. }
  728. func GetTagModels(c *gin.Context) {
  729. tag := c.Query("tag")
  730. if tag == "" {
  731. c.JSON(http.StatusBadRequest, gin.H{
  732. "success": false,
  733. "message": "tag不能为空",
  734. })
  735. return
  736. }
  737. channels, err := model.GetChannelsByTag(tag, false) // Assuming false for idSort is fine here
  738. if err != nil {
  739. c.JSON(http.StatusInternalServerError, gin.H{
  740. "success": false,
  741. "message": err.Error(),
  742. })
  743. return
  744. }
  745. var longestModels string
  746. maxLength := 0
  747. // Find the longest models string among all channels with the given tag
  748. for _, channel := range channels {
  749. if channel.Models != "" {
  750. currentModels := strings.Split(channel.Models, ",")
  751. if len(currentModels) > maxLength {
  752. maxLength = len(currentModels)
  753. longestModels = channel.Models
  754. }
  755. }
  756. }
  757. c.JSON(http.StatusOK, gin.H{
  758. "success": true,
  759. "message": "",
  760. "data": longestModels,
  761. })
  762. return
  763. }