5 "github.com/Kovensky/go-anidb/http"
6 "github.com/Kovensky/go-anidb/misc"
7 "github.com/Kovensky/go-anidb/udp"
8 "github.com/Kovensky/go-fscache"
16 var _ cacheable = &Anime{}
18 func (a *Anime) setCachedTS(ts time.Time) {
22 func (a *Anime) IsStale() bool {
27 diff := now.Sub(a.Cached)
29 return diff > AnimeIncompleteCacheDuration
32 // If the anime ended, and more than AnimeCacheDuration time ago at that
33 if !a.EndDate.IsZero() && now.After(a.EndDate.Add(AnimeCacheDuration)) {
34 return diff > FinishedAnimeCacheDuration
36 return diff > AnimeCacheDuration
39 // Unique Anime IDentifier.
42 // Returns a cached Anime. Returns nil if there is no cached Anime with this AID.
43 func (aid AID) Anime() *Anime {
45 if CacheGet(&a, "aid", aid) == nil {
51 type httpAnimeResponse struct {
56 // Retrieves an Anime by its AID. Uses both the HTTP and UDP APIs,
57 // but can work without the UDP API.
58 func (adb *AniDB) AnimeByID(aid AID) <-chan *Anime {
59 key := []fscache.CacheKey{"aid", aid}
60 ch := make(chan *Anime, 1)
67 ic := make(chan notification, 1)
68 go func() { ch <- (<-ic).(*Anime); close(ch) }()
69 if intentMap.Intent(ic, key...) {
73 if !Cache.IsValid(InvalidKeyCacheDuration, key...) {
74 intentMap.NotifyClose((*Anime)(nil), key...)
80 intentMap.NotifyClose(anime, key...)
85 httpChan := make(chan httpAnimeResponse, 1)
87 log.Printf("HTTP>>> Anime %d", aid)
88 a, err := httpapi.GetAnime(int(aid))
89 httpChan <- httpAnimeResponse{anime: a, err: err}
91 udpChan := adb.udp.SendRecv("ANIME",
97 timeout := time.After(adb.Timeout)
100 anime = &Anime{AID: aid}
102 anime.Incomplete = true
107 for i := 0; i < 2; i++ {
112 log.Printf("HTTP<<< Timeout")
115 case resp := <-httpChan:
117 log.Printf("HTTP<<< %v", resp.err)
122 if resp.anime.Error != "" {
123 log.Printf("HTTP<<< Error %q", resp.anime.Error)
126 if anime.populateFromHTTP(resp.anime) {
127 log.Printf("HTTP<<< Anime %q", anime.PrimaryTitle)
129 // HTTP ok but parsing not ok
130 if anime.PrimaryTitle == "" {
131 Cache.SetInvalid(key...)
134 switch resp.anime.Error {
135 case "Anime not found", "aid Missing or Invalid":
145 case reply := <-udpChan:
146 if reply.Code() == 330 {
147 Cache.SetInvalid(key...)
154 anime.Incomplete = !anime.populateFromUDP(reply)
159 if anime.PrimaryTitle != "" {
161 CacheSet(anime, key...)
163 intentMap.NotifyClose(anime, key...)
165 intentMap.NotifyClose((*Anime)(nil), key...)
171 func (a *Anime) populateFromHTTP(reply httpapi.Anime) bool {
172 if reply.Error != "" {
176 if a.AID != AID(reply.ID) {
177 panic(fmt.Sprintf("Requested AID %d different from received AID %d", a.AID, reply.ID))
181 a.Type = AnimeType(reply.Type)
182 // skip episode count since it's unreliable; UDP API handles that
184 // UDP API has more precise versions
186 if st, err := time.Parse(httpapi.DateFormat, reply.StartDate); err == nil {
189 if et, err := time.Parse(httpapi.DateFormat, reply.EndDate); err == nil {
194 for _, title := range reply.Titles {
197 a.PrimaryTitle = title.Title
199 if a.OfficialTitles == nil {
200 a.OfficialTitles = make(UniqueTitleMap)
202 a.OfficialTitles[Language(title.Lang)] = title.Title
204 if a.ShortTitles == nil {
205 a.ShortTitles = make(TitleMap)
207 a.ShortTitles[Language(title.Lang)] = append(a.ShortTitles[Language(title.Lang)], title.Title)
209 if a.Synonyms == nil {
210 a.Synonyms = make(TitleMap)
212 a.Synonyms[Language(title.Lang)] = append(a.Synonyms[Language(title.Lang)], title.Title)
216 a.OfficialURL = reply.URL
217 if reply.Picture != "" {
218 a.Picture = httpapi.AniDBImageBaseURL + reply.Picture
221 a.Description = reply.Description
224 Rating: reply.Ratings.Permanent.Rating,
225 VoteCount: reply.Ratings.Permanent.Count,
227 a.TemporaryVotes = Rating{
228 Rating: reply.Ratings.Temporary.Rating,
229 VoteCount: reply.Ratings.Temporary.Count,
232 Rating: reply.Ratings.Review.Rating,
233 VoteCount: reply.Ratings.Review.Count,
236 a.populateResources(reply.Resources)
238 counts := map[misc.EpisodeType]int{}
240 sort.Sort(reply.Episodes)
241 for _, ep := range reply.Episodes {
242 ad, _ := time.Parse(httpapi.DateFormat, ep.AirDate)
244 titles := make(UniqueTitleMap)
245 for _, title := range ep.Titles {
246 titles[Language(title.Lang)] = title.Title
253 Episode: *misc.ParseEpisode(ep.EpNo.EpNo),
255 Length: time.Duration(ep.Length) * time.Minute,
259 Rating: ep.Rating.Rating,
260 VoteCount: ep.Rating.Votes,
267 a.Episodes = append(a.Episodes, e)
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],
280 if !a.EndDate.IsZero() {
281 a.TotalEpisodes = a.EpisodeCount.RegularCount
288 func (a *Anime) populateResources(list []httpapi.Resource) {
289 a.Resources.AniDB = Resource{fmt.Sprintf("http://anidb.net/a%v", a.AID)}
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]
302 for i := range res.ExternalEntity {
304 append(a.Resources.ANN, fmt.Sprintf(httpapi.ANNFormat, args[i]...))
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]...))
312 for i := range res.ExternalEntity {
313 a.Resources.AnimeNfo =
314 append(a.Resources.AnimeNfo, fmt.Sprintf(httpapi.AnimeNfoFormat, args[i]...))
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)
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)
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]...))
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]...))
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]...))
344 for i := range res.ExternalEntity {
345 a.Resources.AllCinema =
346 append(a.Resources.AllCinema, fmt.Sprintf(httpapi.AllCinemaFormat, args[i]...))
349 for i := range res.ExternalEntity {
351 append(a.Resources.Anison, fmt.Sprintf(httpapi.AnisonFormat, args[i]...))
354 for i := range res.ExternalEntity {
356 append(a.Resources.VNDB, fmt.Sprintf(httpapi.VNDBFormat, args[i]...))
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]...))
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"
372 func (a *Anime) populateFromUDP(reply udpapi.APIReply) bool {
373 if reply != nil && reply.Error() == nil {
374 parts := strings.Split(reply.Lines()[1], "|")
376 ints := make([]int64, len(parts))
377 for i, p := range parts {
378 ints[i], _ = strconv.ParseInt(p, 10, 32)
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
387 if len(parts[3]) > 0 {
391 // 0 does not actually mean the Epoch here...