server.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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 Group(c *gin.Context) {
  127. locker.RLock()
  128. defer locker.RUnlock()
  129. nodes := healthNodes()
  130. sort.SliceStable(nodes, func(i, j int) bool {
  131. return nodes[i].CountryCode > nodes[j].CountryCode
  132. })
  133. countryLabelSeqs := make(map[string]int)
  134. dtoNodes := make([]*dto.Node, 0)
  135. for _, node := range nodes {
  136. seq, ok := countryLabelSeqs[node.CountryCode]
  137. if !ok {
  138. countryLabelSeqs[node.CountryCode] = 0
  139. } else {
  140. countryLabelSeqs[node.CountryCode] = seq + 1
  141. }
  142. dtoNodes = append(dtoNodes, convert2DtoNode(node, countryLabelSeqs[node.CountryCode]))
  143. }
  144. continents := make(map[string]bool)
  145. for _, node := range nodes {
  146. continents[node.CountryCode] = true
  147. }
  148. // 再遍历出每个 node 对应的 groups
  149. groupDtos := make([]*dto.Group, 0)
  150. for continent := range continents {
  151. groupDto := &dto.Group{
  152. Continent: continent,
  153. Nodes: make([]*dto.Node, 0),
  154. }
  155. for _, dtoNode := range dtoNodes {
  156. if dtoNode.Continent == continent {
  157. groupDto.Nodes = append(groupDto.Nodes, dtoNode)
  158. }
  159. }
  160. groupDtos = append(groupDtos, groupDto)
  161. }
  162. c.JSON(http.StatusOK, dto.GroupResponse{
  163. Response: dto.NewOkResponse(),
  164. Data: groupDtos,
  165. })
  166. }
  167. func SecretRandom(c *gin.Context) {
  168. locker.RLock()
  169. defer locker.RUnlock()
  170. random := rand.Intn(len(nodes))
  171. for i, node := range nodes {
  172. if i == random {
  173. c.Header("Content-Disposition", "attachment; filename=client.ovpn")
  174. c.Data(http.StatusOK, "plain/text", []byte(node.Secret))
  175. return
  176. }
  177. }
  178. c.JSON(http.StatusNotFound, gin.H{
  179. "message": "not found",
  180. })
  181. }
  182. func Secret(c *gin.Context) {
  183. locker.RLock()
  184. defer locker.RUnlock()
  185. var request dto.DetailRequest
  186. if err := c.ShouldBindQuery(&request); err != nil {
  187. dto.BadRequest(c, err)
  188. return
  189. }
  190. for _, node := range nodes {
  191. if node.Ip == request.Ip {
  192. //secret, err := util.AesEncrypt([]byte(node.Secret))
  193. //if err != nil {
  194. // dto.Error(c, err)
  195. // return
  196. //}
  197. c.Header("Content-Disposition", "attachment; filename=client.ovpn")
  198. c.Data(http.StatusOK, "plain/text", []byte(node.Secret))
  199. return
  200. }
  201. }
  202. c.JSON(http.StatusNotFound, gin.H{
  203. "message": "not found ip",
  204. })
  205. }
  206. func Health(c *gin.Context) {
  207. c.JSON(http.StatusOK, gin.H{"status": "up"})
  208. }
  209. func healthNodes() []*model.Node {
  210. healthNodes := make([]*model.Node, 0)
  211. for _, node := range nodes {
  212. if node.LastUpdateTime.Add(10 * time.Second).After(time.Now()) {
  213. healthNodes = append(healthNodes, node)
  214. }
  215. }
  216. return healthNodes
  217. }
  218. func convert2DtoNode(node *model.Node, seq int) *dto.Node {
  219. if node == nil {
  220. return nil
  221. }
  222. icons := map[string]string{
  223. "BR": "http://v.starttransfernow.com/static/BR.jpg",
  224. "DE": "http://v.starttransfernow.com/static/DE.jpg",
  225. "HK": "http://v.starttransfernow.com/static/HK.jpg",
  226. "JP": "http://v.starttransfernow.com/static/JP.jpg",
  227. "US": "http://v.starttransfernow.com/static/US.jpg",
  228. "UK": "http://v.starttransfernow.com/static/UK.jpg",
  229. "GB": "http://v.starttransfernow.com/static/UK.jpg",
  230. "AU": "http://v.starttransfernow.com/static/AU.png",
  231. "CA": "http://v.starttransfernow.com/static/CA.png",
  232. "KR": "http://v.starttransfernow.com/static/KR.png",
  233. "SA": "http://v.starttransfernow.com/static/SA.png",
  234. "SG": "http://v.starttransfernow.com/static/SG.png",
  235. "VN": "http://v.starttransfernow.com/static/VN.png",
  236. "AE": "http://v.starttransfernow.com/static/AE.png",
  237. "BH": "http://v.starttransfernow.com/static/BH.png",
  238. "FR": "http://v.starttransfernow.com/static/FR.png",
  239. "IN": "http://v.starttransfernow.com/static/IN.png",
  240. "NL": "http://v.starttransfernow.com/static/NL.png",
  241. }
  242. countryLabels := map[string]string{
  243. "BR": "Brazil", // aws
  244. "DE": "Germany", // aws
  245. "HK": "Hong Kong", // aws
  246. "JP": "Japan", // aws
  247. "US": "United States", // digitalocean
  248. "UK": "United Kingdom", // aws
  249. "GB": "United Kingdom", // aws
  250. "AU": "Australia", // aws
  251. "CA": "Canada", // digitalocean
  252. "KR": "South Korea", // aws
  253. "SA": "Saudi Arabia", // 无
  254. "SG": "Singapore", // digitalocean
  255. "VN": "Vietnam", // 无
  256. "AE": "United Arab Emirates", // aws
  257. "BH": "Bahrain", // aws
  258. "FR": "France", // aws
  259. "IN": "India", // digitalocean
  260. "NL": "Netherlands", // digitalocean
  261. }
  262. countryContinents := map[string]string{
  263. "BR": "southam",
  264. "DE": "eu",
  265. "HK": "asia",
  266. "JP": "asia",
  267. "US": "northam",
  268. "UK": "eu",
  269. "GB": "eu",
  270. "AU": "oce",
  271. "CA": "northam",
  272. "KR": "asia",
  273. "SA": "asia",
  274. "SG": "asia",
  275. "VN": "asia",
  276. "AE": "asia",
  277. "BH": "asia",
  278. "FR": "eu",
  279. "IN": "asia",
  280. "NL": "eu",
  281. }
  282. countryLabel := fmt.Sprintf("%s", countryLabels[node.CountryCode])
  283. return &dto.Node{
  284. Ip: node.Ip,
  285. CountryCode: node.CountryCode,
  286. CountryName: node.CountryName,
  287. City: node.City,
  288. CountryLabel: countryLabel,
  289. Icon: icons[node.CountryCode],
  290. SecretUrl: fmt.Sprintf("http://v.starttransfernow.com/secret?ip=%s", node.Ip),
  291. Continent: countryContinents[node.CountryCode],
  292. }
  293. }