|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "math/rand" |
| 6 | + "net/url" |
| 7 | + "regexp" |
| 8 | + "strings" |
| 9 | + |
| 10 | + "github.com/ipfs/go-cid" |
| 11 | + "github.com/pkg/errors" |
| 12 | +) |
| 13 | + |
| 14 | +// Hash - separate IPFS hash from link |
| 15 | +func Hash(link string) (string, error) { |
| 16 | + hash := FindAllLinks([]byte(link)) |
| 17 | + if len(hash) != 1 { |
| 18 | + return "", errors.Errorf("invalid IPFS link: %s", link) |
| 19 | + } |
| 20 | + _, err := cid.Decode(hash[0]) |
| 21 | + return hash[0], err |
| 22 | +} |
| 23 | + |
| 24 | +// Link - get gateway link |
| 25 | +func Link(gateway, hash string) string { |
| 26 | + return fmt.Sprintf("%s/ipfs/%s", gateway, hash) |
| 27 | +} |
| 28 | + |
| 29 | +// Path - get path without protocol |
| 30 | +func Path(link string) string { |
| 31 | + return strings.TrimPrefix(link, "ipfs://") |
| 32 | +} |
| 33 | + |
| 34 | +var ipfsURL = regexp.MustCompile(`ipfs:\/\/(?P<hash>(baf[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{56})|Qm[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{44})`) |
| 35 | + |
| 36 | +// FindAllLinks - |
| 37 | +func FindAllLinks(data []byte) []string { |
| 38 | + matches := ipfsURL.FindAllSubmatch(data, -1) |
| 39 | + if len(matches) == 0 { |
| 40 | + return nil |
| 41 | + } |
| 42 | + |
| 43 | + res := make([]string, 0) |
| 44 | + for i := range matches { |
| 45 | + if len(matches[i]) != 2 { |
| 46 | + continue |
| 47 | + } |
| 48 | + res = append(res, string(matches[i][1])) |
| 49 | + } |
| 50 | + return res |
| 51 | +} |
| 52 | + |
| 53 | +// ShuffleGateways - shuffle gateways for different request order for different files |
| 54 | +func ShuffleGateways(gateways []string) []string { |
| 55 | + if len(gateways) < 2 { |
| 56 | + return gateways |
| 57 | + } |
| 58 | + |
| 59 | + shuffled := make([]string, len(gateways)) |
| 60 | + copy(shuffled, gateways) |
| 61 | + rand.Shuffle(len(shuffled), func(i, j int) { shuffled[i], shuffled[j] = shuffled[j], shuffled[i] }) |
| 62 | + return shuffled |
| 63 | +} |
| 64 | + |
| 65 | +// Is - |
| 66 | +func Is(link string) bool { |
| 67 | + u, err := url.Parse(link) |
| 68 | + if err != nil { |
| 69 | + return false |
| 70 | + } |
| 71 | + _, err = cid.Decode(u.Host) |
| 72 | + return err == nil |
| 73 | +} |
0 commit comments