-
Notifications
You must be signed in to change notification settings - Fork 0
/
book.go
134 lines (106 loc) · 2.26 KB
/
book.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
package goodreads
import (
"errors"
"regexp"
"strconv"
"strings"
"github.com/ketabchi/goodreads/api"
"github.com/ketabchi/util"
"github.com/PuerkitoBio/goquery"
)
type Book struct {
url string
doc *goquery.Document
api.Book
}
func NewBookByISBN(isbn string) (*Book, error) {
gb, err := api.GetBookByISBN(isbn)
if err != nil {
return nil, err
}
book, err := newBook(gb.URL)
if err != nil {
return nil, err
}
book.Book = *gb
return book, nil
}
func NewBookByTitle(title string) (*Book, error) {
gb, err := api.GetBookByTitle(title)
if err != nil {
return nil, err
}
book, err := newBook(gb.URL)
if err != nil {
return nil, err
}
book.Book = *gb
return book, nil
}
func NewBook(url string) (*Book, error) {
id := bookID(url)
if len(id) == 0 {
return nil, errors.New("can't get book id from url")
}
gb, err := api.GetBookByID(id)
if err != nil {
return nil, err
}
book, err := newBook(gb.URL)
if err != nil {
return nil, err
}
book.Book = *gb
return book, nil
}
func newBook(url string) (*Book, error) {
doc, err := api.GetDoc(url)
if err != nil {
return nil, err
}
return &Book{url: url, doc: doc}, nil
}
var bookIDRe = regexp.MustCompile(`goodreads\.com\/book\/show\/([0-9]+)`)
func bookID(url string) string {
ss := bookIDRe.FindStringSubmatch(url)
if len(ss) < 2 {
return ""
}
return ss[1]
}
func (b *Book) Genres() []string {
genres := make([]string, 0)
b.doc.Find(".left .bookPageGenreLink").Each(func(i int, sel *goquery.Selection) {
g := sel.Text()
if util.SliceContains(genres, g) {
return
}
s := sel.ParentsUntil(".elementList").Parent().Find(".right .bookPageGenreLink").Text()
s = strings.Trim(s, "\n ")
s = strings.ReplaceAll(s, " users", "")
s = strings.ReplaceAll(s, ",", "")
count, _ := strconv.Atoi(s)
if count > 80 {
genres = append(genres, g)
}
})
return genres
}
func (b *Book) HasAuthor(name string) bool {
authors := b.Authors
for _, author := range authors {
if author.Name == name {
return true
}
}
return false
}
func (b *Book) Link() string {
return b.url
}
var serieNumRe = regexp.MustCompile(" #([0-9]+)$")
func (b *Book) Serie() string {
s := b.doc.Find("#bookSeries a").Text()
s = strings.Trim(s, "()\n ")
return serieNumRe.ReplaceAllString(s, "")
}