|
| 1 | +package download |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + "strings" |
| 8 | +) |
| 9 | + |
| 10 | +const mirrorURL = "https://mirror.minhareceita.org" |
| 11 | + |
| 12 | +// TODO: do we need to export these structs? |
| 13 | +type MirrorFile struct { |
| 14 | + URL string `json:"url"` |
| 15 | + Size uint `json:"size"` |
| 16 | +} |
| 17 | + |
| 18 | +type MirrorGroup struct { |
| 19 | + Name string `json:"name"` |
| 20 | + URLs []MirrorFile `json:"urls"` |
| 21 | +} |
| 22 | + |
| 23 | +type MirrorResponse struct { |
| 24 | + Data []MirrorGroup `json:"data"` |
| 25 | +} |
| 26 | + |
| 27 | +func getMirrorURLs(t string) ([]string, error) { |
| 28 | + c := &http.Client{} |
| 29 | + req, err := http.NewRequest("GET", mirrorURL, nil) |
| 30 | + if err != nil { |
| 31 | + return []string{}, fmt.Errorf("error creating request for mirror: %w", err) |
| 32 | + } |
| 33 | + req.Header.Set("Accept", "application/json") |
| 34 | + r, err := c.Do(req) |
| 35 | + if err != nil { |
| 36 | + return []string{}, fmt.Errorf("error sending request to mirror: %w", err) |
| 37 | + } |
| 38 | + defer r.Body.Close() |
| 39 | + var gs MirrorResponse |
| 40 | + if err = json.NewDecoder(r.Body).Decode(&gs); err != nil { |
| 41 | + return []string{}, fmt.Errorf("error decoding response body: %w", err) |
| 42 | + } |
| 43 | + var urls []string |
| 44 | + var opts []string |
| 45 | + for _, g := range gs.Data { |
| 46 | + if g.Name == t { |
| 47 | + for _, u := range g.URLs { |
| 48 | + if u.Size > 0 { |
| 49 | + urls = append(urls, u.URL) |
| 50 | + } |
| 51 | + } |
| 52 | + break |
| 53 | + } |
| 54 | + opts = append(opts, g.Name) |
| 55 | + } |
| 56 | + if len(urls) == 0 { |
| 57 | + return []string{}, fmt.Errorf("unknown mirror identifier `%s`, options are: %s", t, strings.Join(opts, ", ")) |
| 58 | + } |
| 59 | + return urls, nil |
| 60 | +} |
0 commit comments