server.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. package server
  2. import (
  3. "be-vpn/internal/dto"
  4. "be-vpn/internal/model"
  5. "be-vpn/internal/storage"
  6. "fmt"
  7. "github.com/gin-gonic/gin"
  8. "log"
  9. "math/rand"
  10. "net/http"
  11. "sort"
  12. "strconv"
  13. "sync"
  14. "time"
  15. )
  16. var nodes = make([]*model.Node, 0)
  17. var locker = sync.RWMutex{}
  18. var totalFreeDuration = uint64((time.Hour * 1).Milliseconds() / 1000)
  19. func Config(c *gin.Context) {
  20. deviceId := c.Query("deviceId")
  21. usedDuration, err := storage.GetUsedDuration(deviceId)
  22. if err != nil {
  23. dto.Error(c, err)
  24. return
  25. }
  26. var node *model.Node
  27. if len(healthNodes()) > 0 {
  28. node = healthNodes()[0]
  29. }
  30. freeTrialDuration := uint64(0)
  31. if usedDuration <= totalFreeDuration {
  32. freeTrialDuration = totalFreeDuration - usedDuration
  33. }
  34. c.JSON(http.StatusOK, dto.ConfigResponse{
  35. Response: dto.NewOkResponse(),
  36. Data: dto.ConfigResult{
  37. FreeTrialDuration: freeTrialDuration,
  38. Timestamp: time.Now().Unix(),
  39. Node: convert2DtoNode(node, 0),
  40. },
  41. })
  42. }
  43. func AddUsedDuration(c *gin.Context) {
  44. deviceId := c.Query("deviceId")
  45. usedDurationStr := c.Query("usedDuration")
  46. log.Printf("deviceId: %s, usedDuration: %s", deviceId, usedDurationStr)
  47. usedDuration, err := strconv.ParseUint(usedDurationStr, 10, 64)
  48. if err != nil {
  49. dto.Error(c, err)
  50. return
  51. }
  52. if existed, err := storage.AddUsedDuration(deviceId, usedDuration); err != nil {
  53. dto.Error(c, err)
  54. return
  55. } else {
  56. freeTrialDuration := totalFreeDuration - existed
  57. if freeTrialDuration > totalFreeDuration || freeTrialDuration < 0 {
  58. freeTrialDuration = 0
  59. }
  60. c.JSON(http.StatusOK, dto.ConfigResponse{
  61. Response: dto.NewOkResponse(),
  62. Data: dto.ConfigResult{
  63. FreeTrialDuration: freeTrialDuration,
  64. Timestamp: time.Now().Unix(),
  65. Node: convert2DtoNode(healthNodes()[0], 0),
  66. },
  67. })
  68. }
  69. }
  70. func Register(c *gin.Context) {
  71. locker.Lock()
  72. defer locker.Unlock()
  73. var request dto.RegisterRequest
  74. if err := c.ShouldBindJSON(&request); err != nil {
  75. dto.BadRequest(c, err)
  76. return
  77. }
  78. for _, node := range nodes {
  79. if node.Ip == request.Ip {
  80. node.Ip = request.Ip
  81. node.Secret = request.Secret
  82. node.CountryCode = request.CountryCode
  83. node.CountryName = request.CountryName
  84. node.City = request.City
  85. node.LastUpdateTime = time.Now()
  86. c.JSON(http.StatusOK, dto.RegisterResponse{
  87. Response: dto.NewOkResponse(),
  88. Data: dto.RegisterResult{
  89. Success: true,
  90. },
  91. })
  92. return
  93. }
  94. }
  95. node := &model.Node{
  96. Ip: request.Ip,
  97. Secret: request.Secret,
  98. LastUpdateTime: time.Now(),
  99. }
  100. nodes = append(nodes, node)
  101. log.Printf("update nodes: %+v", nodes)
  102. }
  103. func List(c *gin.Context) {
  104. locker.RLock()
  105. defer locker.RUnlock()
  106. nodes := healthNodes()
  107. sort.SliceStable(nodes, func(i, j int) bool {
  108. return nodes[i].CountryCode > nodes[j].CountryCode
  109. })
  110. countryLabelSeqs := make(map[string]int)
  111. dtoNodes := make([]*dto.Node, 0)
  112. for _, node := range nodes {
  113. seq, ok := countryLabelSeqs[node.CountryCode]
  114. if !ok {
  115. countryLabelSeqs[node.CountryCode] = 0
  116. } else {
  117. countryLabelSeqs[node.CountryCode] = seq + 1
  118. }
  119. dtoNodes = append(dtoNodes, convert2DtoNode(node, countryLabelSeqs[node.CountryCode]))
  120. }
  121. c.JSON(http.StatusOK, dto.ListResponse{
  122. Response: dto.NewOkResponse(),
  123. Data: dtoNodes,
  124. })
  125. }
  126. func SecretRandom(c *gin.Context) {
  127. locker.RLock()
  128. defer locker.RUnlock()
  129. random := rand.Intn(len(nodes))
  130. for i, node := range nodes {
  131. if i == random {
  132. c.Header("Content-Disposition", "attachment; filename=client.ovpn")
  133. c.Data(http.StatusOK, "plain/text", []byte(node.Secret))
  134. return
  135. }
  136. }
  137. c.JSON(http.StatusNotFound, gin.H{
  138. "message": "not found",
  139. })
  140. }
  141. func Secret(c *gin.Context) {
  142. locker.RLock()
  143. defer locker.RUnlock()
  144. var request dto.DetailRequest
  145. if err := c.ShouldBindQuery(&request); err != nil {
  146. dto.BadRequest(c, err)
  147. return
  148. }
  149. for _, node := range nodes {
  150. if node.Ip == request.Ip {
  151. //secret, err := util.AesEncrypt([]byte(node.Secret))
  152. //if err != nil {
  153. // dto.Error(c, err)
  154. // return
  155. //}
  156. c.Header("Content-Disposition", "attachment; filename=client.ovpn")
  157. c.Data(http.StatusOK, "plain/text", []byte(node.Secret))
  158. return
  159. }
  160. }
  161. c.JSON(http.StatusNotFound, gin.H{
  162. "message": "not found ip",
  163. })
  164. }
  165. func Health(c *gin.Context) {
  166. c.JSON(http.StatusOK, gin.H{"status": "up"})
  167. }
  168. func healthNodes() []*model.Node {
  169. healthNodes := make([]*model.Node, 0)
  170. for _, node := range nodes {
  171. if node.LastUpdateTime.Add(10 * time.Second).After(time.Now()) {
  172. healthNodes = append(healthNodes, node)
  173. }
  174. }
  175. return healthNodes
  176. }
  177. func convert2DtoNode(node *model.Node, seq int) *dto.Node {
  178. if node == nil {
  179. return nil
  180. }
  181. icons := map[string]string{
  182. "BR": "http://v.starttransfernow.com/static/BR.jpg",
  183. "DE": "http://v.starttransfernow.com/static/DE.jpg",
  184. "HK": "http://v.starttransfernow.com/static/HK.jpg",
  185. "JP": "http://v.starttransfernow.com/static/JP.jpg",
  186. "US": "http://v.starttransfernow.com/static/US.jpg",
  187. "UK": "http://v.starttransfernow.com/static/UK.jpg",
  188. "GB": "http://v.starttransfernow.com/static/UK.jpg",
  189. }
  190. countryLabels := map[string]string{
  191. "BR": "Brazil",
  192. "DE": "Germany",
  193. "HK": "Hong Kong",
  194. "JP": "Japan",
  195. "US": "United States",
  196. "UK": "United Kingdom",
  197. "GB": "United Kingdom",
  198. }
  199. return &dto.Node{
  200. Ip: node.Ip,
  201. CountryCode: node.CountryCode,
  202. CountryName: node.CountryName,
  203. City: node.City,
  204. CountryLabel: fmt.Sprintf("%s - %d", countryLabels[node.CountryCode], seq+1),
  205. Icon: icons[node.CountryCode],
  206. SecretUrl: fmt.Sprintf("http://v.starttransfernow.com/secret?ip=%s", node.Ip),
  207. }
  208. }