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 switch resp.anime.Error {
136 case "Anime not found", "aid Missing or Invalid":
138 cache.Delete(keys...)
146 case reply := <-udpChan:
147 if reply.Code() == 330 {
148 cache.MarkInvalid(keys...)
150 cache.Delete(keys...)
155 anime.Incomplete = !anime.populateFromUDP(reply)
160 if anime.PrimaryTitle != "" {
162 cache.Set(anime, keys...)
164 intentMap.NotifyClose(anime, keys...)
166 intentMap.NotifyClose((*Anime)(nil), keys...)
172 func (a *Anime) populateFromHTTP(reply httpapi.Anime) bool {
173 if reply.Error != "" {
177 if a.AID != AID(reply.ID) {
178 panic(fmt.Sprintf("Requested AID %d different from received AID %d", a.AID, reply.ID))
182 a.Type = AnimeType(reply.Type)
183 // skip episode count since it's unreliable; UDP API handles that
185 // UDP API has more precise versions
187 if st, err := time.Parse(httpapi.DateFormat, reply.StartDate); err == nil {
190 if et, err := time.Parse(httpapi.DateFormat, reply.EndDate); err == nil {
195 for _, title := range reply.Titles {
198 a.PrimaryTitle = title.Title
200 if a.OfficialTitles == nil {
201 a.OfficialTitles = make(UniqueTitleMap)
203 a.OfficialTitles[Language(title.Lang)] = title.Title
205 if a.ShortTitles == nil {
206 a.ShortTitles = make(TitleMap)
208 a.ShortTitles[Language(title.Lang)] = append(a.ShortTitles[Language(title.Lang)], title.Title)
210 if a.Synonyms == nil {
211 a.Synonyms = make(TitleMap)
213 a.Synonyms[Language(title.Lang)] = append(a.Synonyms[Language(title.Lang)], title.Title)
217 a.OfficialURL = reply.URL
218 if reply.Picture != "" {
219 a.Picture = httpapi.AniDBImageBaseURL + reply.Picture
222 a.Description = reply.Description
225 Rating: reply.Ratings.Permanent.Rating,
226 VoteCount: reply.Ratings.Permanent.Count,
228 a.TemporaryVotes = Rating{
229 Rating: reply.Ratings.Temporary.Rating,
230 VoteCount: reply.Ratings.Temporary.Count,
233 Rating: reply.Ratings.Review.Rating,
234 VoteCount: reply.Ratings.Review.Count,
237 a.populateResources(reply.Resources)
239 counts := map[misc.EpisodeType]int{}
241 sort.Sort(reply.Episodes)
242 for _, ep := range reply.Episodes {
243 ad, _ := time.Parse(httpapi.DateFormat, ep.AirDate)
245 titles := make(UniqueTitleMap)
246 for _, title := range ep.Titles {
247 titles[Language(title.Lang)] = title.Title
254 Episode: *misc.ParseEpisode(ep.EpNo.EpNo),
256 Length: time.Duration(ep.Length) * time.Minute,
260 Rating: ep.Rating.Rating,
261 VoteCount: ep.Rating.Votes,
268 a.Episodes = append(a.Episodes, e)
271 a.EpisodeCount = misc.EpisodeCount{
272 RegularCount: counts[misc.EpisodeTypeRegular],
273 SpecialCount: counts[misc.EpisodeTypeSpecial],
274 CreditsCount: counts[misc.EpisodeTypeCredits],
275 OtherCount: counts[misc.EpisodeTypeOther],
276 TrailerCount: counts[misc.EpisodeTypeTrailer],
277 ParodyCount: counts[misc.EpisodeTypeParody],
281 if !a.EndDate.IsZero() {
282 a.TotalEpisodes = a.EpisodeCount.RegularCount
289 func (a *Anime) populateResources(list []httpapi.Resource) {
290 a.Resources.AniDB = Resource{fmt.Sprintf("http://anidb.net/a%v", a.AID)}
292 for _, res := range list {
293 args := make([][]interface{}, len(res.ExternalEntity))
294 for i, e := range res.ExternalEntity {
295 args[i] = make([]interface{}, len(e.Identifiers))
296 for j := range args[i] {
297 args[i][j] = e.Identifiers[j]
303 for i := range res.ExternalEntity {
305 append(a.Resources.ANN, fmt.Sprintf(httpapi.ANNFormat, args[i]...))
307 case 2: // MyAnimeList
308 for i := range res.ExternalEntity {
309 a.Resources.MyAnimeList =
310 append(a.Resources.MyAnimeList, fmt.Sprintf(httpapi.MyAnimeListFormat, args[i]...))
313 for i := range res.ExternalEntity {
314 a.Resources.AnimeNfo =
315 append(a.Resources.AnimeNfo, fmt.Sprintf(httpapi.AnimeNfoFormat, args[i]...))
317 case 4: // OfficialJapanese
318 for _, e := range res.ExternalEntity {
319 for _, url := range e.URL {
320 a.Resources.OfficialJapanese = append(a.Resources.OfficialJapanese, url)
323 case 5: // OfficialEnglish
324 for _, e := range res.ExternalEntity {
325 for _, url := range e.URL {
326 a.Resources.OfficialEnglish = append(a.Resources.OfficialEnglish, url)
329 case 6: // WikipediaEnglish
330 for i := range res.ExternalEntity {
331 a.Resources.WikipediaEnglish =
332 append(a.Resources.WikipediaEnglish, fmt.Sprintf(httpapi.WikiEnglishFormat, args[i]...))
334 case 7: // WikipediaJapanese
335 for i := range res.ExternalEntity {
336 a.Resources.WikipediaJapanese =
337 append(a.Resources.WikipediaJapanese, fmt.Sprintf(httpapi.WikiJapaneseFormat, args[i]...))
339 case 8: // SyoboiSchedule
340 for i := range res.ExternalEntity {
341 a.Resources.SyoboiSchedule =
342 append(a.Resources.SyoboiSchedule, fmt.Sprintf(httpapi.SyoboiFormat, args[i]...))
345 for i := range res.ExternalEntity {
346 a.Resources.AllCinema =
347 append(a.Resources.AllCinema, fmt.Sprintf(httpapi.AllCinemaFormat, args[i]...))
350 for i := range res.ExternalEntity {
352 append(a.Resources.Anison, fmt.Sprintf(httpapi.AnisonFormat, args[i]...))
355 for i := range res.ExternalEntity {
357 append(a.Resources.VNDB, fmt.Sprintf(httpapi.VNDBFormat, args[i]...))
359 case 15: // MaruMegane
360 for i := range res.ExternalEntity {
361 a.Resources.MaruMegane =
362 append(a.Resources.MaruMegane, fmt.Sprintf(httpapi.MaruMeganeFormat, args[i]...))
368 // http://wiki.anidb.info/w/UDP_API_Definition#ANIME:_Retrieve_Anime_Data
369 // Everything that we can't easily get through the HTTP API, or that has more accuracy:
370 // episodes, air date, end date, award list, update date,
371 const animeAMask = "0000980201"
373 func (a *Anime) populateFromUDP(reply udpapi.APIReply) bool {
374 if reply != nil && reply.Error() == nil {
375 parts := strings.Split(reply.Lines()[1], "|")
377 ints := make([]int64, len(parts))
378 for i, p := range parts {
379 ints[i], _ = strconv.ParseInt(p, 10, 32)
382 a.TotalEpisodes = int(ints[0]) // episodes
383 st := time.Unix(ints[1], 0) // air date
384 et := time.Unix(ints[2], 0) // end date
385 aw := strings.Split(parts[3], "'") // award list
386 ut := time.Unix(ints[4], 0) // update date
388 if len(parts[3]) > 0 {
392 // 0 does not actually mean the Epoch here...