1
0

subController.go 2.1 KB

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