-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauthors.go
121 lines (102 loc) · 2.37 KB
/
authors.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
package gol
import (
"encoding/json"
"errors"
"fmt"
"sync"
)
type Author struct {
Container
keyCovers []string
works []Work
Key string
}
// GetAuthor returns an Author struct
func GetAuthor(id string) (a Author, err error) {
a.Container, err = MakeAuthorRequest(id)
if err != nil {
return a, err
}
if HasError(a.Container) != nil {
return a, errors.New("Author not found")
}
a.Key = id
return
}
// works returns all the works of the author
func (a *Author) Works() ([]Work, error) {
if len(a.works) > 0 {
return a.works, nil
}
ws, err := a._Works("")
if err != nil {
return nil, err
}
a.works = ws
return ws, err
}
func (a Author) _Works(offset string) ([]Work, error) {
var s string
if offset != "" {
s = fmt.Sprintf("https://openlibrary.org%s", offset)
} else {
s = fmt.Sprintf("https://openlibrary.org/authors/%s/works.json", a.Key)
}
container, err := Request(s)
if err != nil {
return nil, err
}
if HasError(container) != nil {
return nil, errors.New("Author not found")
}
entries := []Work{}
var wg sync.WaitGroup
entriesJSON := container.Path("entries").Children()
wg.Add(len(entriesJSON))
for _, child := range entriesJSON {
work := Work{
Container: child,
}
go func(wg *sync.WaitGroup) {
work.Load()
wg.Done()
}(&wg)
entries = append(entries, work)
}
// Use the next field If there are still another works to request from the API
if next, ok := container.Path("links.next").Data().(string); ok && next != "" {
nextEntries, err := a._Works(next)
if err != nil {
return entries, err
}
entries = append(entries, nextEntries...)
}
wg.Wait()
return entries, err
}
// KeyCovers returns (if they exists) the key covers/photo of the author
func (a *Author) KeyCovers() ([]string, error) {
if len(a.keyCovers) > 0 {
return a.keyCovers, nil
}
for _, child := range a.S("photos").Children() {
id, err := child.Data().(json.Number).Int64()
if err == nil {
a.keyCovers = append(a.keyCovers, fmt.Sprintf("%v", id))
}
}
if len(a.keyCovers) == 0 {
return a.keyCovers, fmt.Errorf("Could not find the key covers")
}
return a.keyCovers, nil
}
func (a Author) FirstCoverKey() string {
if keys, ok := a.KeyCovers(); ok == nil {
return keys[0]
}
return ""
}
// Cover returns (if it exists) the URL of the first Author's Photo/Cover
func (a Author) Cover(size string) string {
return Cover(a, size)
}