subController.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. a := &SUBController{
  26. subPath: subPath,
  27. subJsonPath: jsonPath,
  28. subEncrypt: encrypt,
  29. updateInterval: update,
  30. subService: NewSubService(showInfo, rModel),
  31. subJsonService: NewSubJsonService(jsonFragment),
  32. }
  33. a.initRouter(g)
  34. return a
  35. }
  36. func (a *SUBController) initRouter(g *gin.RouterGroup) {
  37. gLink := g.Group(a.subPath)
  38. gJson := g.Group(a.subJsonPath)
  39. gLink.GET(":subid", a.subs)
  40. gJson.GET(":subid", a.subJsons)
  41. }
  42. func (a *SUBController) subs(c *gin.Context) {
  43. subId := c.Param("subid")
  44. host := strings.Split(c.Request.Host, ":")[0]
  45. subs, header, err := a.subService.GetSubs(subId, host)
  46. if err != nil || len(subs) == 0 {
  47. c.String(400, "Error!")
  48. } else {
  49. result := ""
  50. for _, sub := range subs {
  51. result += sub + "\n"
  52. }
  53. // Add headers
  54. c.Writer.Header().Set("Subscription-Userinfo", header)
  55. c.Writer.Header().Set("Profile-Update-Interval", a.updateInterval)
  56. c.Writer.Header().Set("Profile-Title", subId)
  57. if a.subEncrypt {
  58. c.String(200, base64.StdEncoding.EncodeToString([]byte(result)))
  59. } else {
  60. c.String(200, result)
  61. }
  62. }
  63. }
  64. func (a *SUBController) subJsons(c *gin.Context) {
  65. subId := c.Param("subid")
  66. host := strings.Split(c.Request.Host, ":")[0]
  67. jsonSub, header, err := a.subJsonService.GetJson(subId, host)
  68. if err != nil || len(jsonSub) == 0 {
  69. c.String(400, "Error!")
  70. } else {
  71. // Add headers
  72. c.Writer.Header().Set("Subscription-Userinfo", header)
  73. c.Writer.Header().Set("Profile-Update-Interval", a.updateInterval)
  74. c.Writer.Header().Set("Profile-Title", subId)
  75. c.String(200, jsonSub)
  76. }
  77. }