subController.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package sub
  2. import (
  3. "encoding/base64"
  4. "strings"
  5. "github.com/gin-gonic/gin"
  6. )
  7. type SUBController struct {
  8. subPath string
  9. subJsonPath string
  10. subEncrypt bool
  11. updateInterval string
  12. subService *SubService
  13. subJsonService *SubJsonService
  14. }
  15. func NewSUBController(
  16. g *gin.RouterGroup,
  17. subPath string,
  18. jsonPath string,
  19. encrypt bool,
  20. showInfo bool,
  21. rModel string,
  22. update string,
  23. jsonFragment string,
  24. ) *SUBController {
  25. sub := NewSubService(showInfo, rModel)
  26. a := &SUBController{
  27. subPath: subPath,
  28. subJsonPath: jsonPath,
  29. subEncrypt: encrypt,
  30. updateInterval: update,
  31. subService: sub,
  32. subJsonService: NewSubJsonService(jsonFragment, sub),
  33. }
  34. a.initRouter(g)
  35. return a
  36. }
  37. func (a *SUBController) initRouter(g *gin.RouterGroup) {
  38. gLink := g.Group(a.subPath)
  39. gJson := g.Group(a.subJsonPath)
  40. gLink.GET(":subid", a.subs)
  41. gJson.GET(":subid", a.subJsons)
  42. }
  43. func (a *SUBController) subs(c *gin.Context) {
  44. subId := c.Param("subid")
  45. host := strings.Split(c.Request.Host, ":")[0]
  46. subs, header, err := a.subService.GetSubs(subId, host)
  47. if err != nil || len(subs) == 0 {
  48. c.String(400, "Error!")
  49. } else {
  50. result := ""
  51. for _, sub := range subs {
  52. result += sub + "\n"
  53. }
  54. // Add headers
  55. c.Writer.Header().Set("Subscription-Userinfo", header)
  56. c.Writer.Header().Set("Profile-Update-Interval", a.updateInterval)
  57. c.Writer.Header().Set("Profile-Title", subId)
  58. if a.subEncrypt {
  59. c.String(200, base64.StdEncoding.EncodeToString([]byte(result)))
  60. } else {
  61. c.String(200, result)
  62. }
  63. }
  64. }
  65. func (a *SUBController) subJsons(c *gin.Context) {
  66. subId := c.Param("subid")
  67. host := strings.Split(c.Request.Host, ":")[0]
  68. jsonSub, header, err := a.subJsonService.GetJson(subId, host)
  69. if err != nil || len(jsonSub) == 0 {
  70. c.String(400, "Error!")
  71. } else {
  72. // Add headers
  73. c.Writer.Header().Set("Subscription-Userinfo", header)
  74. c.Writer.Header().Set("Profile-Update-Interval", a.updateInterval)
  75. c.Writer.Header().Set("Profile-Title", subId)
  76. c.String(200, jsonSub)
  77. }
  78. }