1
0

subController.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. package sub
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "strings"
  6. "strconv"
  7. "github.com/mhsanaei/3x-ui/v2/config"
  8. "github.com/gin-gonic/gin"
  9. )
  10. // SUBController handles HTTP requests for subscription links and JSON configurations.
  11. type SUBController struct {
  12. subTitle string
  13. subSupportUrl string
  14. subProfileUrl string
  15. subAnnounce string
  16. subEnableRouting bool
  17. subRoutingRules string
  18. subPath string
  19. subJsonPath string
  20. jsonEnabled bool
  21. subEncrypt bool
  22. updateInterval string
  23. subService *SubService
  24. subJsonService *SubJsonService
  25. }
  26. // NewSUBController creates a new subscription controller with the given configuration.
  27. func NewSUBController(
  28. g *gin.RouterGroup,
  29. subPath string,
  30. jsonPath string,
  31. jsonEnabled bool,
  32. encrypt bool,
  33. showInfo bool,
  34. rModel string,
  35. update string,
  36. jsonFragment string,
  37. jsonNoise string,
  38. jsonMux string,
  39. jsonRules string,
  40. subTitle string,
  41. subSupportUrl string,
  42. subProfileUrl string,
  43. subAnnounce string,
  44. subEnableRouting bool,
  45. subRoutingRules string,
  46. ) *SUBController {
  47. sub := NewSubService(showInfo, rModel)
  48. a := &SUBController{
  49. subTitle: subTitle,
  50. subSupportUrl: subSupportUrl,
  51. subProfileUrl: subProfileUrl,
  52. subAnnounce: subAnnounce,
  53. subEnableRouting: subEnableRouting,
  54. subRoutingRules: subRoutingRules,
  55. subPath: subPath,
  56. subJsonPath: jsonPath,
  57. jsonEnabled: jsonEnabled,
  58. subEncrypt: encrypt,
  59. updateInterval: update,
  60. subService: sub,
  61. subJsonService: NewSubJsonService(jsonFragment, jsonNoise, jsonMux, jsonRules, sub),
  62. }
  63. a.initRouter(g)
  64. return a
  65. }
  66. // initRouter registers HTTP routes for subscription links and JSON endpoints
  67. // on the provided router group.
  68. func (a *SUBController) initRouter(g *gin.RouterGroup) {
  69. gLink := g.Group(a.subPath)
  70. gLink.GET(":subid", a.subs)
  71. if a.jsonEnabled {
  72. gJson := g.Group(a.subJsonPath)
  73. gJson.GET(":subid", a.subJsons)
  74. }
  75. }
  76. // subs handles HTTP requests for subscription links, returning either HTML page or base64-encoded subscription data.
  77. func (a *SUBController) subs(c *gin.Context) {
  78. subId := c.Param("subid")
  79. scheme, host, hostWithPort, hostHeader := a.subService.ResolveRequest(c)
  80. subs, lastOnline, traffic, err := a.subService.GetSubs(subId, host)
  81. if err != nil || len(subs) == 0 {
  82. c.String(400, "Error!")
  83. } else {
  84. result := ""
  85. for _, sub := range subs {
  86. result += sub + "\n"
  87. }
  88. // If the request expects HTML (e.g., browser) or explicitly asked (?html=1 or ?view=html), render the info page here
  89. accept := c.GetHeader("Accept")
  90. if strings.Contains(strings.ToLower(accept), "text/html") || c.Query("html") == "1" || strings.EqualFold(c.Query("view"), "html") {
  91. // Build page data in service
  92. subURL, subJsonURL := a.subService.BuildURLs(scheme, hostWithPort, a.subPath, a.subJsonPath, subId)
  93. if !a.jsonEnabled {
  94. subJsonURL = ""
  95. }
  96. // Get base_path from context (set by middleware)
  97. basePath, exists := c.Get("base_path")
  98. if !exists {
  99. basePath = "/"
  100. }
  101. // Add subId to base_path for asset URLs
  102. basePathStr := basePath.(string)
  103. if basePathStr == "/" {
  104. basePathStr = "/" + subId + "/"
  105. } else {
  106. // Remove trailing slash if exists, add subId, then add trailing slash
  107. basePathStr = strings.TrimRight(basePathStr, "/") + "/" + subId + "/"
  108. }
  109. page := a.subService.BuildPageData(subId, hostHeader, traffic, lastOnline, subs, subURL, subJsonURL, basePathStr)
  110. c.HTML(200, "subpage.html", gin.H{
  111. "title": "subscription.title",
  112. "cur_ver": config.GetVersion(),
  113. "host": page.Host,
  114. "base_path": page.BasePath,
  115. "sId": page.SId,
  116. "download": page.Download,
  117. "upload": page.Upload,
  118. "total": page.Total,
  119. "used": page.Used,
  120. "remained": page.Remained,
  121. "expire": page.Expire,
  122. "lastOnline": page.LastOnline,
  123. "datepicker": page.Datepicker,
  124. "downloadByte": page.DownloadByte,
  125. "uploadByte": page.UploadByte,
  126. "totalByte": page.TotalByte,
  127. "subUrl": page.SubUrl,
  128. "subJsonUrl": page.SubJsonUrl,
  129. "result": page.Result,
  130. })
  131. return
  132. }
  133. // Add headers
  134. header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  135. a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, a.subProfileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules)
  136. if a.subEncrypt {
  137. c.String(200, base64.StdEncoding.EncodeToString([]byte(result)))
  138. } else {
  139. c.String(200, result)
  140. }
  141. }
  142. }
  143. // subJsons handles HTTP requests for JSON subscription configurations.
  144. func (a *SUBController) subJsons(c *gin.Context) {
  145. subId := c.Param("subid")
  146. _, host, _, _ := a.subService.ResolveRequest(c)
  147. jsonSub, header, err := a.subJsonService.GetJson(subId, host)
  148. if err != nil || len(jsonSub) == 0 {
  149. c.String(400, "Error!")
  150. } else {
  151. // Add headers
  152. a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, a.subProfileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules)
  153. c.String(200, jsonSub)
  154. }
  155. }
  156. // ApplyCommonHeaders sets common HTTP headers for subscription responses including user info, update interval, and profile title.
  157. func (a *SUBController) ApplyCommonHeaders(
  158. c *gin.Context,
  159. header,
  160. updateInterval,
  161. profileTitle string,
  162. profileSupportUrl string,
  163. profileUrl string,
  164. profileAnnounce string,
  165. profileEnableRouting bool,
  166. profileRoutingRules string,
  167. ) {
  168. c.Writer.Header().Set("Subscription-Userinfo", header)
  169. c.Writer.Header().Set("Profile-Update-Interval", updateInterval)
  170. c.Writer.Header().Set("Profile-Title", "base64:"+base64.StdEncoding.EncodeToString([]byte(profileTitle)))
  171. c.Writer.Header().Set("Support-Url", profileSupportUrl)
  172. c.Writer.Header().Set("Profile-Web-Page-Url", profileUrl)
  173. c.Writer.Header().Set("Announce", "base64:"+base64.StdEncoding.EncodeToString([]byte(profileAnnounce)))
  174. c.Writer.Header().Set("Routing-Enable", strconv.FormatBool(profileEnableRouting))
  175. c.Writer.Header().Set("Routing", profileRoutingRules)
  176. }