]> git.lizzy.rs Git - go-anidb.git/blob - animecache.go
anidb: Simplify (*AniDB).EpisodeByID()
[go-anidb.git] / animecache.go
1 package anidb
2
3 import (
4         "encoding/gob"
5         "fmt"
6         "github.com/Kovensky/go-anidb/http"
7         "github.com/Kovensky/go-anidb/misc"
8         "github.com/Kovensky/go-anidb/udp"
9         "log"
10         "sort"
11         "strconv"
12         "strings"
13         "time"
14 )
15
16 func init() {
17         gob.RegisterName("*github.com/Kovensky/go-anidb.Anime", &Anime{})
18         gob.RegisterName("github.com/Kovensky/go-anidb.AID", AID(0))
19 }
20
21 func (a *Anime) Touch() {
22         a.Cached = time.Now()
23 }
24
25 func (a *Anime) IsStale() bool {
26         if a == nil {
27                 return true
28         }
29         if a.Incomplete {
30                 return time.Now().Sub(a.Cached) > AnimeIncompleteCacheDuration
31         }
32         return time.Now().Sub(a.Cached) > AnimeCacheDuration
33 }
34
35 // Unique Anime IDentifier.
36 type AID int
37
38 // make AID Cacheable
39
40 func (e AID) Touch()        {}
41 func (e AID) IsStale() bool { return false }
42
43 // Returns a cached Anime. Returns nil if there is no cached Anime with this AID.
44 func (aid AID) Anime() *Anime {
45         var a Anime
46         if cache.Get(&a, "aid", aid) == nil {
47                 return &a
48         }
49         return nil
50 }
51
52 type httpAnimeResponse struct {
53         anime httpapi.Anime
54         err   error
55 }
56
57 // Retrieves an Anime by its AID. Uses both the HTTP and UDP APIs,
58 // but can work without the UDP API.
59 func (adb *AniDB) AnimeByID(aid AID) <-chan *Anime {
60         keys := []cacheKey{"aid", aid}
61         ch := make(chan *Anime, 1)
62
63         if aid < 1 {
64                 ch <- nil
65                 close(ch)
66         }
67
68         ic := make(chan Cacheable, 1)
69         go func() { ch <- (<-ic).(*Anime); close(ch) }()
70         if intentMap.Intent(ic, keys...) {
71                 return ch
72         }
73
74         if !cache.CheckValid(keys...) {
75                 intentMap.NotifyClose((*Anime)(nil), keys...)
76                 return ch
77         }
78
79         anime := aid.Anime()
80         if !anime.IsStale() {
81                 intentMap.NotifyClose(anime, keys...)
82                 return ch
83         }
84
85         go func() {
86                 httpChan := make(chan httpAnimeResponse, 1)
87                 go func() {
88                         log.Printf("HTTP>>> Anime %d", aid)
89                         a, err := httpapi.GetAnime(int(aid))
90                         httpChan <- httpAnimeResponse{anime: a, err: err}
91                 }()
92                 udpChan := adb.udp.SendRecv("ANIME",
93                         paramMap{
94                                 "aid":   aid,
95                                 "amask": animeAMask,
96                         })
97
98                 timeout := time.After(adb.Timeout)
99
100                 if anime == nil {
101                         anime = &Anime{AID: aid}
102                 }
103                 anime.Incomplete = true
104
105                 ok := true
106
107         Loop:
108                 for i := 0; i < 2; i++ {
109                         select {
110                         case <-timeout:
111                                 // HTTP API timeout
112                                 if httpChan != nil {
113                                         log.Printf("HTTP<<< Timeout")
114                                         close(httpChan)
115                                 }
116                         case resp := <-httpChan:
117                                 if resp.err != nil {
118                                         log.Printf("HTTP<<< %v", resp.err)
119                                         ok = false
120                                         break Loop
121                                 }
122
123                                 if resp.anime.Error != "" {
124                                         log.Printf("HTTP<<< Error %q", resp.anime.Error)
125                                 }
126
127                                 if anime.populateFromHTTP(resp.anime) {
128                                         log.Printf("HTTP<<< Anime %q", anime.PrimaryTitle)
129                                 } else {
130                                         // HTTP ok but parsing not ok
131                                         if anime.PrimaryTitle == "" {
132                                                 cache.MarkInvalid(keys...)
133                                         }
134
135                                         if resp.anime.Error == "Anime not found" {
136                                                 // deleted AID?
137                                                 cache.Delete(keys...)
138                                         }
139
140                                         ok = false
141                                         break Loop
142                                 }
143
144                                 httpChan = nil
145                         case reply := <-udpChan:
146                                 if reply.Code() == 330 {
147                                         cache.MarkInvalid(keys...)
148                                         // deleted AID?
149                                         cache.Delete(keys...)
150
151                                         ok = false
152                                         break Loop
153                                 } else {
154                                         anime.Incomplete = !anime.populateFromUDP(reply)
155                                 }
156                                 udpChan = nil
157                         }
158                 }
159                 if anime.PrimaryTitle != "" {
160                         if ok {
161                                 cache.Set(anime, keys...)
162                         }
163                         intentMap.NotifyClose(anime, keys...)
164                 } else {
165                         intentMap.NotifyClose((*Anime)(nil), keys...)
166                 }
167         }()
168         return ch
169 }
170
171 func (a *Anime) populateFromHTTP(reply httpapi.Anime) bool {
172         if reply.Error != "" {
173                 return false
174         }
175
176         if a.AID != AID(reply.ID) {
177                 panic(fmt.Sprintf("Requested AID %d different from received AID %d", a.AID, reply.ID))
178         }
179         a.R18 = reply.R18
180
181         a.Type = AnimeType(reply.Type)
182         // skip episode count since it's unreliable; UDP API handles that
183
184         // UDP API has more precise versions
185         if a.Incomplete {
186                 if st, err := time.Parse(httpapi.DateFormat, reply.StartDate); err == nil {
187                         a.StartDate = st
188                 }
189                 if et, err := time.Parse(httpapi.DateFormat, reply.EndDate); err == nil {
190                         a.EndDate = et
191                 }
192         }
193
194         for _, title := range reply.Titles {
195                 switch title.Type {
196                 case "main":
197                         a.PrimaryTitle = title.Title
198                 case "official":
199                         if a.OfficialTitles == nil {
200                                 a.OfficialTitles = make(UniqueTitleMap)
201                         }
202                         a.OfficialTitles[Language(title.Lang)] = title.Title
203                 case "short":
204                         if a.ShortTitles == nil {
205                                 a.ShortTitles = make(TitleMap)
206                         }
207                         a.ShortTitles[Language(title.Lang)] = append(a.ShortTitles[Language(title.Lang)], title.Title)
208                 case "synonym":
209                         if a.Synonyms == nil {
210                                 a.Synonyms = make(TitleMap)
211                         }
212                         a.Synonyms[Language(title.Lang)] = append(a.Synonyms[Language(title.Lang)], title.Title)
213                 }
214         }
215
216         a.OfficialURL = reply.URL
217         if reply.Picture != "" {
218                 a.Picture = httpapi.AniDBImageBaseURL + reply.Picture
219         }
220
221         a.Description = reply.Description
222
223         a.Votes = Rating{
224                 Rating:    reply.Ratings.Permanent.Rating,
225                 VoteCount: reply.Ratings.Permanent.Count,
226         }
227         a.TemporaryVotes = Rating{
228                 Rating:    reply.Ratings.Temporary.Rating,
229                 VoteCount: reply.Ratings.Temporary.Count,
230         }
231         a.Reviews = Rating{
232                 Rating:    reply.Ratings.Review.Rating,
233                 VoteCount: reply.Ratings.Review.Count,
234         }
235
236         a.populateResources(reply.Resources)
237
238         counts := map[misc.EpisodeType]int{}
239
240         sort.Sort(reply.Episodes)
241         for _, ep := range reply.Episodes {
242                 ad, _ := time.Parse(httpapi.DateFormat, ep.AirDate)
243
244                 titles := make(UniqueTitleMap)
245                 for _, title := range ep.Titles {
246                         titles[Language(title.Lang)] = title.Title
247                 }
248
249                 e := &Episode{
250                         EID: EID(ep.ID),
251                         AID: a.AID,
252
253                         Episode: *misc.ParseEpisode(ep.EpNo.EpNo),
254
255                         Length:  time.Duration(ep.Length) * time.Minute,
256                         AirDate: &ad,
257
258                         Rating: Rating{
259                                 Rating:    ep.Rating.Rating,
260                                 VoteCount: ep.Rating.Votes,
261                         },
262                         Titles: titles,
263                 }
264                 counts[e.Type]++
265                 cacheEpisode(e)
266
267                 a.Episodes = append(a.Episodes, e)
268         }
269
270         a.EpisodeCount = misc.EpisodeCount{
271                 RegularCount: counts[misc.EpisodeTypeRegular],
272                 SpecialCount: counts[misc.EpisodeTypeSpecial],
273                 CreditsCount: counts[misc.EpisodeTypeCredits],
274                 OtherCount:   counts[misc.EpisodeTypeOther],
275                 TrailerCount: counts[misc.EpisodeTypeTrailer],
276                 ParodyCount:  counts[misc.EpisodeTypeParody],
277         }
278
279         if a.Incomplete {
280                 if !a.EndDate.IsZero() {
281                         a.TotalEpisodes = a.EpisodeCount.RegularCount
282                 }
283         }
284
285         return true
286 }
287
288 func (a *Anime) populateResources(list []httpapi.Resource) {
289         a.Resources.AniDB = Resource{fmt.Sprintf("http://anidb.net/a%v", a.AID)}
290
291         for _, res := range list {
292                 args := make([][]interface{}, len(res.ExternalEntity))
293                 for i, e := range res.ExternalEntity {
294                         args[i] = make([]interface{}, len(e.Identifiers))
295                         for j := range args[i] {
296                                 args[i][j] = e.Identifiers[j]
297                         }
298                 }
299
300                 switch res.Type {
301                 case 1: // ANN
302                         for i := range res.ExternalEntity {
303                                 a.Resources.ANN =
304                                         append(a.Resources.ANN, fmt.Sprintf(httpapi.ANNFormat, args[i]...))
305                         }
306                 case 2: // MyAnimeList
307                         for i := range res.ExternalEntity {
308                                 a.Resources.MyAnimeList =
309                                         append(a.Resources.MyAnimeList, fmt.Sprintf(httpapi.MyAnimeListFormat, args[i]...))
310                         }
311                 case 3: // AnimeNfo
312                         for i := range res.ExternalEntity {
313                                 a.Resources.AnimeNfo =
314                                         append(a.Resources.AnimeNfo, fmt.Sprintf(httpapi.AnimeNfoFormat, args[i]...))
315                         }
316                 case 4: // OfficialJapanese
317                         for _, e := range res.ExternalEntity {
318                                 for _, url := range e.URL {
319                                         a.Resources.OfficialJapanese = append(a.Resources.OfficialJapanese, url)
320                                 }
321                         }
322                 case 5: // OfficialEnglish
323                         for _, e := range res.ExternalEntity {
324                                 for _, url := range e.URL {
325                                         a.Resources.OfficialEnglish = append(a.Resources.OfficialEnglish, url)
326                                 }
327                         }
328                 case 6: // WikipediaEnglish
329                         for i := range res.ExternalEntity {
330                                 a.Resources.WikipediaEnglish =
331                                         append(a.Resources.WikipediaEnglish, fmt.Sprintf(httpapi.WikiEnglishFormat, args[i]...))
332                         }
333                 case 7: // WikipediaJapanese
334                         for i := range res.ExternalEntity {
335                                 a.Resources.WikipediaJapanese =
336                                         append(a.Resources.WikipediaJapanese, fmt.Sprintf(httpapi.WikiJapaneseFormat, args[i]...))
337                         }
338                 case 8: // SyoboiSchedule
339                         for i := range res.ExternalEntity {
340                                 a.Resources.SyoboiSchedule =
341                                         append(a.Resources.SyoboiSchedule, fmt.Sprintf(httpapi.SyoboiFormat, args[i]...))
342                         }
343                 case 9: // AllCinema
344                         for i := range res.ExternalEntity {
345                                 a.Resources.AllCinema =
346                                         append(a.Resources.AllCinema, fmt.Sprintf(httpapi.AllCinemaFormat, args[i]...))
347                         }
348                 case 10: // Anison
349                         for i := range res.ExternalEntity {
350                                 a.Resources.Anison =
351                                         append(a.Resources.Anison, fmt.Sprintf(httpapi.AnisonFormat, args[i]...))
352                         }
353                 case 14: // VNDB
354                         for i := range res.ExternalEntity {
355                                 a.Resources.VNDB =
356                                         append(a.Resources.VNDB, fmt.Sprintf(httpapi.VNDBFormat, args[i]...))
357                         }
358                 case 15: // MaruMegane
359                         for i := range res.ExternalEntity {
360                                 a.Resources.MaruMegane =
361                                         append(a.Resources.MaruMegane, fmt.Sprintf(httpapi.MaruMeganeFormat, args[i]...))
362                         }
363                 }
364         }
365 }
366
367 // http://wiki.anidb.info/w/UDP_API_Definition#ANIME:_Retrieve_Anime_Data
368 // Everything that we can't easily get through the HTTP API, or that has more accuracy:
369 // episodes, air date, end date, award list, update date,
370 const animeAMask = "0000980201"
371
372 func (a *Anime) populateFromUDP(reply udpapi.APIReply) bool {
373         if reply != nil && reply.Error() == nil {
374                 parts := strings.Split(reply.Lines()[1], "|")
375
376                 ints := make([]int64, len(parts))
377                 for i, p := range parts {
378                         ints[i], _ = strconv.ParseInt(p, 10, 32)
379                 }
380
381                 a.TotalEpisodes = int(ints[0])     // episodes
382                 st := time.Unix(ints[1], 0)        // air date
383                 et := time.Unix(ints[2], 0)        // end date
384                 aw := strings.Split(parts[3], "'") // award list
385                 ut := time.Unix(ints[4], 0)        // update date
386
387                 if len(parts[3]) > 0 {
388                         a.Awards = aw
389                 }
390
391                 // 0 does not actually mean the Epoch here...
392                 if ints[1] != 0 {
393                         a.StartDate = st
394                 }
395                 if ints[2] != 0 {
396                         a.EndDate = et
397                 }
398                 if ints[4] != 0 {
399                         a.Updated = ut
400                 }
401                 return true
402         }
403         return false
404 }