summaryrefslogtreecommitdiff
path: root/cmd/bash/main.go
blob: 8ecf2e7288e360cf72c37d219a119ca4612f4424 (plain) (blame)
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
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
	"sync"

	"github.com/antchfx/htmlquery"
)

func main() {
	all := []quoteElem{}
	from := 3472
	wg := sync.WaitGroup{}
	for i := from; i >= 1; i-- {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			quotes, err := parsePage(i)
			if err != nil {
				log.Println(err)
				return
			}
			all = append(all, quotes...)
		}(i)
	}
	wg.Wait()
	b, err := json.Marshal(all)
	if err != nil {
		panic(err)
	}
	if err := os.WriteFile("db/quotes.json", b, os.ModePerm); err != nil {
		panic(err)
	}
	log.Println("ok")
}

func parsePage(num int) ([]quoteElem, error) {
	doc, err := htmlquery.LoadURL(fmt.Sprintf("https://xn--80abh7bk0c.xn--p1ai/index/%d", num))
	if err != nil {
		return nil, err
	}
	quotes := []quoteElem{}
	quotesList, err := htmlquery.QueryAll(doc, "/html/body/div[1]/main/section/article")
	if err != nil {
		return nil, err
	}
	for _, quote := range quotesList {
		header, err := htmlquery.Query(quote, "/div/header/a")
		if err != nil {
			return nil, err
		}
		if header == nil {
			break
		}
		num, _ := strconv.Atoi(header.FirstChild.Data[1:])
		date, err := htmlquery.Query(quote, "/div/header/div")
		dates := ""
		if err != nil {
			return nil, err
		}
		if date != nil {
			dates = date.FirstChild.Data
			dates = strings.Trim(strings.ReplaceAll(dates, "\\n", ""), " ")
		}
		body := htmlquery.FindOne(quote, "/div/div").FirstChild
		text := []string{}
		for {
			if body.DataAtom == 0 {
				text = append(text, body.Data)
			}
			body = body.NextSibling
			if body == nil {
				break
			}
		}
		quotes = append(quotes, quoteElem{
			Body: strings.Trim(strings.Join(text, "\n"), " \n\t"),
			Num:  num,
			Date: dates,
		})
		quote = quote.NextSibling
		if quote == nil {
			break
		}
	}
	return quotes, nil
}

type quoteElem struct {
	Num  int    `json:"num"`
	Body string `json:"body"`
	Date string `json:"date"`
}