]> git.lizzy.rs Git - go-anidb.git/blob - filecache.go
anidb: Document which backend API is used on the Get* methods
[go-anidb.git] / filecache.go
1 package anidb
2
3 import (
4         "encoding/gob"
5         "github.com/Kovensky/go-anidb/misc"
6         "github.com/Kovensky/go-anidb/udp"
7         "image"
8         "log"
9         "strconv"
10         "strings"
11         "time"
12 )
13
14 func init() {
15         gob.RegisterName("*github.com/Kovensky/go-anidb.File", &File{})
16         gob.RegisterName("*github.com/Kovensky/go-anidb.ed2kCache", &ed2kCache{})
17         gob.RegisterName("github.com/Kovensky/go-anidb.FID", FID(0))
18 }
19
20 func (f *File) Touch() {
21         f.Cached = time.Now()
22 }
23
24 func (f *File) IsStale() bool {
25         if f == nil {
26                 return true
27         }
28         if f.Incomplete {
29                 return time.Now().Sub(f.Cached) > FileIncompleteCacheDuration
30         }
31         return time.Now().Sub(f.Cached) > FileCacheDuration
32 }
33
34 type FID int
35
36 // make FID Cacheable
37
38 func (e FID) Touch()        {}
39 func (e FID) IsStale() bool { return false }
40
41 func (fid FID) File() *File {
42         var f File
43         if cache.Get(&f, "fid", fid) == nil {
44                 return &f
45         }
46         return nil
47 }
48
49 type ed2kCache struct {
50         FID
51         Time time.Time
52 }
53
54 func (c *ed2kCache) Touch() {
55         c.Time = time.Now()
56 }
57
58 func (c *ed2kCache) IsStale() bool {
59         return time.Now().Sub(c.Time) > FileCacheDuration
60 }
61
62 // Prefetches the Anime, Episode and Group that this
63 // file is linked to using the given AniDB instance.
64 //
65 // Returns a channel where this file will be sent to
66 // when the prefetching is done; if the file is nil,
67 // the channel will return nil.
68 func (f *File) Prefetch(adb *AniDB) <-chan *File {
69         ch := make(chan *File, 1)
70         go func() {
71                 if f != nil {
72                         a := adb.AnimeByID(f.AID)
73                         g := adb.GroupByID(f.GID)
74                         <-a
75                         <-g
76                         ch <- f
77                 }
78                 close(ch)
79         }()
80         return ch
81 }
82
83 // Retrieves a File by its FID. Uses the UDP API.
84 func (adb *AniDB) FileByID(fid FID) <-chan *File {
85         keys := []cacheKey{"fid", fid}
86
87         ch := make(chan *File, 1)
88
89         ic := make(chan Cacheable, 1)
90         go func() { ch <- (<-ic).(*File); close(ch) }()
91         if intentMap.Intent(ic, keys...) {
92                 return ch
93         }
94
95         if !cache.CheckValid(keys...) {
96                 intentMap.Notify((*File)(nil), keys...)
97                 return ch
98         }
99
100         f := fid.File()
101         if !f.IsStale() {
102                 intentMap.Notify(f, keys...)
103                 return ch
104         }
105
106         go func() {
107                 reply := <-adb.udp.SendRecv("FILE",
108                         paramMap{
109                                 "fid":   fid,
110                                 "fmask": fileFmask,
111                                 "amask": fileAmask,
112                         })
113
114                 if reply.Error() == nil {
115                         f = parseFileResponse(reply)
116
117                         cache.Set(&ed2kCache{FID: f.FID}, "fid", "by-ed2k", f.Ed2kHash, f.Filesize)
118                         cache.Set(f, keys...)
119                 } else if reply.Code() == 320 {
120                         cache.MarkInvalid(keys...)
121                 }
122
123                 intentMap.Notify(f, keys...)
124         }()
125         return ch
126 }
127
128 // Retrieves a File by its Ed2kHash + Filesize combination. Uses the UDP API.
129 func (adb *AniDB) FileByEd2kSize(ed2k string, size int64) <-chan *File {
130         keys := []cacheKey{"fid", "by-ed2k", ed2k, size}
131
132         ch := make(chan *File, 1)
133
134         ic := make(chan Cacheable, 1)
135         go func() {
136                 fid := (<-ic).(FID)
137                 if fid > 0 {
138                         ch <- <-adb.FileByID(fid)
139                 }
140                 close(ch)
141         }()
142         if intentMap.Intent(ic, keys...) {
143                 return ch
144         }
145
146         if !cache.CheckValid(keys...) {
147                 intentMap.Notify(FID(0), keys...)
148                 return ch
149         }
150
151         fid := FID(0)
152
153         var ec ed2kCache
154         if cache.Get(&ec, keys...) == nil && !ec.IsStale() {
155                 intentMap.Notify(ec.FID, keys...)
156                 return ch
157         }
158         fid = ec.FID
159
160         go func() {
161                 reply := <-adb.udp.SendRecv("FILE",
162                         paramMap{
163                                 "ed2k":  ed2k,
164                                 "size":  size,
165                                 "fmask": fileFmask,
166                                 "amask": fileAmask,
167                         })
168
169                 var f *File
170                 if reply.Error() == nil {
171                         f = parseFileResponse(reply)
172
173                         fid = f.FID
174
175                         cache.Set(&ed2kCache{FID: fid}, keys...)
176                         cache.Set(f, "fid", fid)
177                 } else if reply.Code() == 320 { // file not found
178                         cache.MarkInvalid(keys...)
179                 } else if reply.Code() == 322 { // multiple files found
180                         panic("Don't know what to do with " + strings.Join(reply.Lines(), "\n"))
181                 }
182
183                 intentMap.Notify(fid, keys...)
184         }()
185         return ch
186 }
187
188 var fileFmask = "77da7fe8"
189 var fileAmask = "00008000"
190
191 const (
192         fileStateCRCOK = 1 << iota
193         fileStateCRCERR
194         fileStateV2
195         fileStateV3
196         fileStateV4
197         fileStateV5
198         fileStateUncensored
199         fileStateCensored
200 )
201
202 func sanitizeCodec(codec string) string {
203         switch codec {
204         case "MP3 CBR":
205                 return "MP3"
206         case "WMV9 (also WMV3)":
207                 return "WMV9"
208         case "Ogg (Vorbis)":
209                 return "Vorbis"
210         case "H264/AVC":
211                 return "H.264"
212         }
213         return codec
214 }
215
216 func parseFileResponse(reply udpapi.APIReply) *File {
217         if reply.Error() != nil {
218                 return nil
219         }
220         if reply.Truncated() {
221                 panic("Truncated")
222         }
223
224         parts := strings.Split(reply.Lines()[1], "|")
225         ints := make([]int64, len(parts))
226         for i, p := range parts {
227                 ints[i], _ = strconv.ParseInt(parts[i], 10, 64)
228                 log.Printf("#%d: %s\n", i, p)
229         }
230
231         // how does epno look like?
232         log.Println("epno: " + parts[23])
233
234         version := FileVersion(1)
235         switch i := ints[6]; {
236         case i&fileStateV5 != 0:
237                 version = 5
238         case i&fileStateV4 != 0:
239                 version = 4
240         case i&fileStateV3 != 0:
241                 version = 3
242         case i&fileStateV2 != 0:
243                 version = 2
244         }
245
246         // codecs (parts[13]), bitrates (ints[14]), langs (parts[19])
247         codecs := strings.Split(parts[13], "'")
248         bitrates := strings.Split(parts[14], "'")
249         alangs := strings.Split(parts[19], "'")
250         streams := make([]AudioStream, len(codecs))
251         for i := range streams {
252                 br, _ := strconv.ParseInt(bitrates[i], 10, 32)
253                 streams[i] = AudioStream{
254                         Bitrate:  int(br),
255                         Codec:    sanitizeCodec(codecs[i]),
256                         Language: Language(alangs[i]),
257                 }
258         }
259
260         sl := strings.Split(parts[20], "'")
261         slangs := make([]Language, len(sl))
262         for i := range sl {
263                 slangs[i] = Language(sl[i])
264         }
265
266         depth := int(ints[11])
267         if depth == 0 {
268                 depth = 8
269         }
270         res := strings.Split(parts[17], "x")
271         width, _ := strconv.ParseInt(res[0], 10, 32)
272         height, _ := strconv.ParseInt(res[1], 10, 32)
273         video := VideoInfo{
274                 Bitrate:    int(ints[16]),
275                 Codec:      sanitizeCodec(parts[15]),
276                 ColorDepth: depth,
277                 Resolution: image.Rect(0, 0, int(width), int(height)),
278         }
279
280         return &File{
281                 FID: FID(ints[0]),
282
283                 AID: AID(ints[1]),
284                 EID: EID(ints[2]),
285                 GID: GID(ints[3]),
286
287                 OtherEpisodes: misc.ParseEpisodeList(parts[4]).Simplify(),
288                 Deprecated:    ints[5] != 0,
289
290                 CRCMatch:   ints[6]&fileStateCRCOK != 0,
291                 BadCRC:     ints[6]&fileStateCRCERR != 0,
292                 Version:    version,
293                 Uncensored: ints[6]&fileStateUncensored != 0,
294                 Censored:   ints[6]&fileStateCensored != 0,
295
296                 Incomplete: video.Resolution.Empty(),
297
298                 Filesize: ints[7],
299                 Ed2kHash: parts[8],
300                 SHA1Hash: parts[9],
301                 CRC32:    parts[10],
302
303                 Source: FileSource(parts[12]),
304
305                 AudioStreams:      streams,
306                 SubtitleLanguages: slangs,
307                 VideoInfo:         video,
308                 FileExtension:     parts[18],
309
310                 Length:  time.Duration(ints[21]) * time.Second,
311                 AirDate: time.Unix(ints[22], 0),
312         }
313 }