1
0

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