subController.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. println(c.Request.Header["User-Agent"][0])
  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. println(c.Request.Header["User-Agent"][0])
  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. }