forked from animenotifier/kitsu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StreamUserLibrary.go
63 lines (47 loc) · 1.25 KB
/
StreamUserLibrary.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
package kitsu
import (
"strings"
"time"
)
// StreamLibraryEntries returns a stream of all library entries (async).
func (user *User) StreamLibraryEntries() chan *LibraryEntry {
channel := make(chan *LibraryEntry)
url := "users/" + user.ID + "/library-entries?page[limit]=500&page[offset]=0&include=anime"
ticker := time.NewTicker(50 * time.Millisecond)
rateLimit := ticker.C
go func() {
defer close(channel)
defer ticker.Stop()
for {
page, err := GetLibraryEntryPage(url)
if err != nil {
panic(err)
}
// Feed entry data from current page to the stream
includedAnime := map[string]*Anime{}
for _, anime := range page.Included {
includedAnime[anime.ID] = anime
}
// Feed entry data from current page to the stream
for _, entry := range page.Data {
animeInfo := entry.Relationships.Anime.Data
if animeInfo != nil {
entry.Anime = includedAnime[animeInfo.ID]
}
channel <- entry
}
nextURL := page.Links.Next
// Did we reach the end?
if nextURL == "" {
break
}
// Cut off API base URL
nextURL = strings.TrimPrefix(nextURL, APIBaseURL)
// Continue with the next page
url = nextURL
// Wait for rate limiter to allow the next request
<-rateLimit
}
}()
return channel
}