-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
318 lines (260 loc) · 6.72 KB
/
main.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package main
import (
"encoding/json"
"encoding/xml"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
)
type UrlSet struct {
XMLName xml.Name `xml:"urlset"`
Urls []Url `xml:"url"`
}
type Url struct {
Loc string `xml:"loc"`
}
type Ingredients struct {
Amount string
Name string
}
type Recipe struct {
Title string
Subtitle string
CoverImg string
PdfUrl string
Labels []string
Tags []string
Ingredients []Ingredients
Steps []string
}
func getRecipeUrls(tld string, sourceUrl string) ([]string, error) {
url := sourceUrl
if sourceUrl == "" {
url = fmt.Sprintf("https://www.hellofresh.%s/sitemap_recipe_pages.xml", tld)
}
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("received non-200 status code: %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var urlSet UrlSet
err = xml.Unmarshal(body, &urlSet)
if err != nil {
return nil, err
}
var urls []string
for _, url := range urlSet.Urls {
urls = append(urls, url.Loc)
}
return urls, nil
}
func fetchHtml(url string) (string, error) {
res, err := http.Get(url)
if err != nil {
return "", err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("received non-200 status code: %d", res.StatusCode)
}
body, err := io.ReadAll(res.Body)
if err != nil {
return "", err
}
return string(body), nil
}
func parseHtml(html string) (Recipe, error) {
doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
if err != nil {
return Recipe{}, err
}
descriptionSelection := doc.Find("[data-test-id=recipe-description]").First()
title := descriptionSelection.Find("h1").First().Text()
subtitle := descriptionSelection.Find("h2").First().Text()
coverImg := doc.Find("[data-test-id=recipe-hero-image]").First().Find("img").First().AttrOr("src", "")
pdfUrl := doc.Find("[data-test-id=recipe-pdf]").First().AttrOr("href", "")
labels := make([]string, 0)
doc.Find("[data-test-id=label-text] span").Each(func(i int, s *goquery.Selection) {
labels = append(labels, s.Text())
})
tags := make([]string, 0)
doc.Find("[data-test-id=recipe-description-tag] span").Each(func(i int, s *goquery.Selection) {
text := s.Text()
if text != "•" {
tags = append(tags, text)
}
})
ingredientSelection := doc.Find("[data-test-id=ingredient-item-shipped], [data-test-id=ingredient-item-not-shipped]")
var ingredients []Ingredients
ingredientSelection.Each(func(i int, s *goquery.Selection) {
container := s.Find("div").Last()
amount := container.Find("p").First().Text()
name := container.Find("p").Eq(1).Text()
ingredients = append(ingredients, Ingredients{
Amount: amount,
Name: name,
})
})
var steps []string
doc.Find("[data-test-id=instruction-step]").Each(func(i int, s *goquery.Selection) {
container := s.Find("div").Eq(1)
step := container.Find("p").First().Text()
steps = append(steps, step)
})
return Recipe{
Title: title,
Subtitle: subtitle,
CoverImg: coverImg,
PdfUrl: pdfUrl,
Labels: labels,
Tags: tags,
Ingredients: ingredients,
Steps: steps,
}, nil
}
func storeRecipeAsJSON(recipe Recipe, targetPath string) error {
jsonData, err := json.MarshalIndent(recipe, "", " ")
if err != nil {
return err
}
err = os.WriteFile(targetPath, jsonData, 0644)
return err
}
func downloadFileFromUrl(fileUrl string, targetPath string) error {
resp, err := http.Get(fileUrl)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", resp.Status)
}
outFile, err := os.Create(targetPath)
if err != nil {
return err
}
defer outFile.Close()
_, err = io.Copy(outFile, resp.Body)
if err != nil {
return err
}
return nil
}
func getBaseFromUrl(url string) string {
return path.Base(url)
}
func getFileExtensionFromURL(u string) (string, error) {
parsedURL, err := url.Parse(u)
if err != nil {
return "", err
}
return path.Ext(parsedURL.Path), nil
}
func pathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func getAndSaveRecipe(url string, path string, recipeName string, downloadPdf bool) error {
targetDir := fmt.Sprintf("%s/%s", path, recipeName)
targetRecipePath := fmt.Sprintf("%s/recipe.json", targetDir)
targetRecipePdf := fmt.Sprintf("%s/recipe.pdf", targetDir)
exists, err := pathExists(targetDir)
if err != nil {
return err
}
if exists {
return fmt.Errorf("dir already exists: %s", targetDir)
}
err = os.MkdirAll(targetDir, 0755)
if err != nil {
return err
}
htmlContent, err := fetchHtml(url)
if err != nil {
return err
}
recipe, err := parseHtml(htmlContent)
if err != nil {
return err
}
err = storeRecipeAsJSON(recipe, targetRecipePath)
if err != nil {
return err
}
if downloadPdf && recipe.PdfUrl != "" {
err := downloadFileFromUrl(recipe.PdfUrl, targetRecipePdf)
if err != nil {
return err
}
}
if recipe.CoverImg != "" {
fileExtension, err := getFileExtensionFromURL(recipe.CoverImg)
if err != nil {
return err
}
coverTargetPath := fmt.Sprintf("%s/cover%s", targetDir, fileExtension)
err = downloadFileFromUrl(recipe.CoverImg, coverTargetPath)
if err != nil {
return err
}
}
return nil
}
func getAndSaveAllRecipes(urls []string, delay time.Duration, path string, downloadPdfs bool) {
for i, url := range urls {
recipeName := getBaseFromUrl(url)
err := getAndSaveRecipe(url, path, recipeName, downloadPdfs)
if err != nil {
fmt.Println("Error fetching recipes:", err)
continue
}
fmt.Printf("%d/%d fetched recipe: %s \n", i+1, len(urls)+1, recipeName)
time.Sleep(delay)
}
}
func uniqueStrings(strings []string) []string {
seen := make(map[string]bool)
var result []string
for _, s := range strings {
if !seen[s] {
seen[s] = true
result = append(result, s)
}
}
return result
}
func main() {
outputPath := flag.String("output", "./output", "Path to store the output")
delay := flag.Int("delay", 5000, "Delay per request in ms")
locale := flag.String("tld", "de", "Top level domain of the HelloFresh website")
downloadPdfs := flag.Bool("pdf", false, "Download PDFs")
siteMapUrl := flag.String("sitemapUrl", "", "URL to the sitemap")
flag.Parse()
delayDuration := time.Duration(*delay) * time.Millisecond
recipeUrls, err := getRecipeUrls(*locale, *siteMapUrl)
if err != nil {
fmt.Println("Error fetching URLs:", err)
return
}
getAndSaveAllRecipes(uniqueStrings(recipeUrls), delayDuration, *outputPath, *downloadPdfs)
}