-
Notifications
You must be signed in to change notification settings - Fork 0
/
scraping.go
88 lines (73 loc) · 1.83 KB
/
scraping.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package wallpapers
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
)
var ErrUnrecognisedWallpaperRepoType = fmt.Errorf("unrecognised wallpaper repo type")
// Will get all download links to files located in the directory
// Ignores subdirectories.
func GetFiles(repoType WallpaperRepoType, Url string) ([]string, error) {
switch repoType {
case Eyy_Indexer:
return getEyyIndexerFiles(Url)
default:
return nil, ErrUnrecognisedWallpaperRepoType
}
}
// This will always work, spacing doesnt change - its generated by a php script
var findFiles = regexp.MustCompile(`<td data-raw="image" class="download"><a href="([^"]*)"`)
func getEyyIndexerFiles(Url string) (urls []string, err error) {
content, err := CloudProxyGetContent(Url)
if err != nil {
return nil, err
}
parsed, err := url.Parse(Url)
if err != nil {
return nil, err
}
matches := findFiles.FindAllStringSubmatch(content, -1)
baseURL := "https://" + parsed.Host
for _, match := range matches {
urls = append(urls, baseURL+match[1])
}
return urls, nil
}
// returns whether the file exists
func exists(path string) bool {
_, err := os.Stat(path)
return !errors.Is(err, os.ErrNotExist)
}
// download a file with HTTP GET and (if code 2xx) set the response as the contents of the path, if path doesnt exist.
// Otherwise you will get an error
func DownloadFile(url, path string) error {
if exists(path) {
return os.ErrExist
}
res, err := http.Get(url)
if err != nil {
return err
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
return errors.New("non-200 status code")
}
// create parent directories
err = os.MkdirAll(filepath.Dir(path), 0)
if err != nil {
return err
}
file, err := os.Create(path)
if err != nil {
return err
}
_, err = io.Copy(file, res.Body)
if err != nil {
return err
}
return file.Close()
}