Uniformize server selection filtering

This commit is contained in:
Quentin McGaw
2020-07-23 01:46:28 +00:00
parent a5c35455d1
commit fec1249293
8 changed files with 245 additions and 184 deletions

View File

@@ -2,7 +2,6 @@ package provider
import (
"fmt"
"net"
"strings"
"github.com/qdm12/golibs/network"
@@ -16,29 +15,24 @@ func newSurfshark() *surfshark {
return &surfshark{}
}
func (s *surfshark) GetOpenVPNConnections(selection models.ServerSelection) (connections []models.OpenVPNConnection, err error) { //nolint:dupl
var IPs []net.IP
func (s *surfshark) filterServers(region string) (servers []models.SurfsharkServer) {
if len(region) == 0 {
return constants.SurfsharkServers()
}
for _, server := range constants.SurfsharkServers() {
if strings.EqualFold(server.Region, selection.Region) {
IPs = server.IPs
if strings.EqualFold(server.Region, region) {
return []models.SurfsharkServer{server}
}
}
if len(IPs) == 0 {
return nil, fmt.Errorf("no IP found for region %q", selection.Region)
}
if selection.TargetIP != nil {
found := false
for i := range IPs {
if IPs[i].Equal(selection.TargetIP) {
found = true
break
}
}
if !found {
return nil, fmt.Errorf("target IP address %q not found in IP addresses", selection.TargetIP)
}
IPs = []net.IP{selection.TargetIP}
return nil
}
func (s *surfshark) GetOpenVPNConnections(selection models.ServerSelection) (connections []models.OpenVPNConnection, err error) { //nolint:dupl
servers := s.filterServers(selection.Region)
if len(servers) == 0 {
return nil, fmt.Errorf("no server found for region %q", selection.Region)
}
var port uint16
switch {
case selection.Protocol == constants.TCP:
@@ -48,9 +42,27 @@ func (s *surfshark) GetOpenVPNConnections(selection models.ServerSelection) (con
default:
return nil, fmt.Errorf("protocol %q is unknown", selection.Protocol)
}
for _, IP := range IPs {
connections = append(connections, models.OpenVPNConnection{IP: IP, Port: port, Protocol: selection.Protocol})
for _, server := range servers {
for _, IP := range server.IPs {
if selection.TargetIP != nil {
if selection.TargetIP.Equal(IP) {
return []models.OpenVPNConnection{{IP: IP, Port: port, Protocol: selection.Protocol}}, nil
}
} else {
connections = append(connections, models.OpenVPNConnection{IP: IP, Port: port, Protocol: selection.Protocol})
}
}
}
if selection.TargetIP != nil {
return nil, fmt.Errorf("target IP %s not found in IP addresses", selection.TargetIP)
}
if len(connections) > 64 {
connections = connections[:64]
}
return connections, nil
}