forked from Eauldane/SnowcloakUtils
49 lines
1.7 KiB
Go
49 lines
1.7 KiB
Go
package files
|
|
|
|
import (
|
|
"github.com/showwin/speedtest-go/speedtest"
|
|
)
|
|
|
|
type ConnectionStatistics struct {
|
|
downloadBytes uint64 // Server download speed in bytes
|
|
uploadBytes uint64 // Upload speed in bytes
|
|
downloadSlots uint16 // How fany files can be downloaded by the server at once before queueing kicks in
|
|
uploadSlots uint16 // How many uploads we can do at once
|
|
|
|
// Slots are calculated with a minimum acceptable speed of 128KiB/s per slot
|
|
// Using uint16 for this MIGHT get a bit munted if someone tries to use something faster than a 25gbit connection
|
|
// or something but I really, really doubt anyone is going to do that. Problem for later me if it turns into an issue
|
|
}
|
|
|
|
func CalculateConnectionStatistics() ConnectionStatistics {
|
|
var speedtestClient = speedtest.New()
|
|
serverList, _ := speedtestClient.FetchServers()
|
|
// Picks server with the lowest ping
|
|
targets, _ := serverList.FindServer([]int{})
|
|
for _, s := range targets {
|
|
s.PingTest(nil)
|
|
s.DownloadTest()
|
|
s.UploadTest()
|
|
connStats := ConnectionStatistics{
|
|
downloadBytes: uint64(s.DLSpeed), // Casting since speedtest-go dev implemented this as float64
|
|
uploadBytes: uint64(s.ULSpeed),
|
|
downloadSlots: uint16(uint64(s.DLSpeed) / 131072), // 128KiB per slot
|
|
uploadSlots: uint16(uint64(s.ULSpeed) / 131072), // Casting to avoid float
|
|
}
|
|
|
|
if connStats.downloadSlots > 1000 {
|
|
connStats.downloadSlots = 1000 // Max slot count should be 1000 to avoid DDoS-like behaviour
|
|
}
|
|
if connStats.uploadSlots > 1000 {
|
|
connStats.uploadSlots = 1000
|
|
}
|
|
s.Context.Reset()
|
|
return connStats
|
|
|
|
}
|
|
// If all else fails... fuckin' yolo it
|
|
connStats := ConnectionStatistics{0, 0, 1000, 1000}
|
|
return connStats
|
|
|
|
}
|