6 "github.com/Kovensky/go-anidb/http"
7 "github.com/Kovensky/go-anidb/misc"
8 "github.com/Kovensky/go-anidb/udp"
17 gob.RegisterName("*github.com/Kovensky/go-anidb.Anime", &Anime{})
18 gob.RegisterName("github.com/Kovensky/go-anidb.AID", AID(0))
21 func (a *Anime) Touch() {
25 func (a *Anime) IsStale() bool {
30 return time.Now().Sub(a.Cached) > AnimeIncompleteCacheDuration
32 return time.Now().Sub(a.Cached) > AnimeCacheDuration
35 // Unique Anime IDentifier.
40 func (e AID) Touch() {}
41 func (e AID) IsStale() bool { return false }
43 // Returns a cached Anime. Returns nil if there is no cached Anime with this AID.
44 func (aid AID) Anime() *Anime {
46 if cache.Get(&a, "aid", aid) == nil {
52 type httpAnimeResponse struct {
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)
68 ic := make(chan Cacheable, 1)
69 go func() { ch <- (<-ic).(*Anime); close(ch) }()
70 if intentMap.Intent(ic, keys...) {
74 if !cache.CheckValid(keys...) {
75 intentMap.NotifyClose((*Anime)(nil), keys...)
81 intentMap.NotifyClose(anime, keys...)
86 httpChan := make(chan httpAnimeResponse, 1)
88 log.Printf("HTTP>>> Anime %d", aid)
89 a, err := httpapi.GetAnime(int(aid))
90 httpChan <- httpAnimeResponse{anime: a, err: err}
92 udpChan := adb.udp.SendRecv("ANIME",
98 timeout := time.After(adb.Timeout)
101 anime = &Anime{AID: aid}
103 anime.Incomplete = true
108 for i := 0; i < 2; i++ {
113 log.Printf("HTTP<<< Timeout")
116 case resp := <-httpChan:
118 log.Printf("HTTP<<< %v", resp.err)
123 if resp.anime.Error != "" {
124 log.Printf("HTTP<<< Error %q", resp.anime.Error)
127 if anime.populateFromHTTP(resp.anime) {
128 log.Printf("HTTP<<< Anime %q", anime.PrimaryTitle)
130 // HTTP ok but parsing not ok
131 if anime.PrimaryTitle == "" {
132 cache.MarkInvalid(keys...)
135 if resp.anime.Error == "Anime not found" {
137 cache.Delete(keys...)
145 case reply := <-udpChan:
146 if reply.Code() == 330 {
147 cache.MarkInvalid(keys...)
149 cache.Delete(keys...)
154 anime.Incomplete = !anime.populateFromUDP(reply)
159 if anime.PrimaryTitle != "" {
161 cache.Set(anime, keys...)
163 intentMap.NotifyClose(anime, keys...)
165 intentMap.NotifyClose((*Anime)(nil), keys...)
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...