gostations/browser.go

104 lines
2.2 KiB
Go
Raw Normal View History

2021-03-16 13:09:27 +00:00
package main
import (
"encoding/json"
"fmt"
2023-12-13 12:00:28 +00:00
"io"
"log"
"math/rand"
"net"
"net/http"
"net/url"
"time"
)
2021-03-16 13:09:27 +00:00
type stationRecord struct {
2023-12-13 12:00:28 +00:00
Name string `json:"name"`
Codec string `json:"codec"`
Bitrate json.Number `json:"bitrate"`
2023-12-13 12:00:28 +00:00
Countrycode string `json:"countrycode"`
Tags string `json:"tags"`
Url string `json:"url"`
Lastcheck int `json:"lastcheckok"`
}
func RandomIP(iplist []net.IP) net.IP {
2023-12-13 12:00:28 +00:00
rand.NewSource(time.Now().Unix())
randomIndex := rand.Intn(len(iplist))
return iplist[randomIndex]
}
func nslookup(hostname string) net.IP {
iprecords, _ := net.LookupIP(hostname)
randomIp := RandomIP(iprecords)
return randomIp
}
func reverseLookup(ipAddr net.IP) string {
ptr, _ := net.LookupAddr(ipAddr.String())
return ptr[0]
}
func GetApiHost() string {
appHostIp := nslookup(api())
apiHost := reverseLookup(appHostIp)
return apiHost
}
2023-12-13 12:00:28 +00:00
func GetStations(qstring string) ([]stationRecord, error) {
urlstr := fmt.Sprintf("https://%s/json/stations/search?%s&limit=%d", GetApiHost(), qstring, maxitems())
resp, err := http.Get(urlstr)
if err != nil {
2021-03-17 13:45:54 +00:00
log.Print(err.Error())
}
2023-12-13 12:00:28 +00:00
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Print(err.Error())
}
}(resp.Body)
var data []stationRecord
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return data, err
}
return data, err
}
func pruneStations(stations []stationRecord) []stationRecord {
filteredStations := stations[:0]
for _, station := range stations {
if station.Lastcheck == 1 {
filteredStations = append(filteredStations, station)
}
}
return filteredStations
}
func StationSearch(name string, country string, state string, tags string, notok bool) ([]stationRecord, error) {
params := url.Values{}
2023-12-13 12:00:28 +00:00
if name != "" {
params.Add("name", name)
}
if country != "" {
params.Add("country", country)
}
2023-12-13 12:00:28 +00:00
if state != "" {
params.Add("state", state)
}
2023-12-13 12:00:28 +00:00
if tags != "" {
params.Add("tag", tags)
}
stations, err := GetStations(params.Encode())
2023-12-13 12:00:28 +00:00
if err != nil {
return nil, err
}
2023-12-13 12:00:28 +00:00
if notok {
return stations, err
} // otherwise prune the list
prunedStations := pruneStations(stations) // eliminate stations that are reporting down.
return prunedStations, err
}