server.go 8.3 KB

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