]> git.lizzy.rs Git - go-anidb.git/blob - filecache.go
anidb: Correct accidental docstring
[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
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 func (adb *AniDB) FileByID(fid FID) <-chan *File {
84         keys := []cacheKey{"fid", fid}
85
86         ch := make(chan *File, 1)
87
88         ic := make(chan Cacheable, 1)
89         go func() { ch <- (<-ic).(*File); close(ch) }()
90         if intentMap.Intent(ic, keys...) {
91                 return ch
92         }
93
94         if !cache.CheckValid(keys...) {
95                 intentMap.Notify((*File)(nil), keys...)
96                 return ch
97         }
98
99         if f := fid.File(); !f.IsStale() {
100                 intentMap.Notify(f, keys...)
101                 return ch
102         }
103
104         go func() {
105                 reply := <-adb.udp.SendRecv("FILE",
106                         paramMap{
107                                 "fid":   fid,
108                                 "fmask": fileFmask,
109                                 "amask": fileAmask,
110                         })
111
112                 var f *File
113                 if reply.Error() == nil {
114                         f = parseFileResponse(reply)
115                 } else if reply.Code() == 320 {
116                         cache.MarkInvalid(keys...)
117                 }
118                 if f != nil {
119                         cache.Set(&ed2kCache{FID: f.FID}, "fid", "by-ed2k", f.Ed2kHash, f.Filesize)
120                         cache.Set(f, keys...)
121                 }
122                 intentMap.Notify(f, keys...)
123         }()
124         return ch
125 }
126
127 func (adb *AniDB) FileByEd2kSize(ed2k string, size int64) <-chan *File {
128         keys := []cacheKey{"fid", "by-ed2k", ed2k, size}
129
130         ch := make(chan *File, 1)
131
132         ic := make(chan Cacheable, 1)
133         go func() {
134                 fid := (<-ic).(FID)
135                 if fid > 0 {
136                         ch <- <-adb.FileByID(fid)
137                 }
138                 close(ch)
139         }()
140         if intentMap.Intent(ic, keys...) {
141                 return ch
142         }
143
144         if !cache.CheckValid(keys...) {
145                 intentMap.Notify(FID(0), keys...)
146                 return ch
147         }
148
149         var ec ed2kCache
150         if cache.Get(&ec, keys...) == nil {
151                 intentMap.Notify(ec.FID, keys...)
152                 return ch
153         }
154
155         go func() {
156                 reply := <-adb.udp.SendRecv("FILE",
157                         paramMap{
158                                 "ed2k":  ed2k,
159                                 "size":  size,
160                                 "fmask": fileFmask,
161                                 "amask": fileAmask,
162                         })
163
164                 fid := FID(0)
165                 var f *File
166                 if reply.Error() == nil {
167                         f = parseFileResponse(reply)
168
169                         fid = f.FID
170
171                         cache.Set(&ed2kCache{FID: fid}, keys...)
172                         cache.Set(f, "fid", fid)
173                 } else if reply.Code() == 320 { // file not found
174                         cache.MarkInvalid(keys...)
175                 } else if reply.Code() == 322 { // multiple files found
176                         panic("Don't know what to do with " + strings.Join(reply.Lines(), "\n"))
177                 }
178
179                 intentMap.Notify(fid, keys...)
180         }()
181         return ch
182 }
183
184 var fileFmask = "77da7fe8"
185 var fileAmask = "00008000"
186
187 const (
188         fileStateCRCOK = 1 << iota
189         fileStateCRCERR
190         fileStateV2
191         fileStateV3
192         fileStateV4
193         fileStateV5
194         fileStateUncensored
195         fileStateCensored
196 )
197
198 func sanitizeCodec(codec string) string {
199         switch codec {
200         case "MP3 CBR":
201                 return "MP3"
202         case "WMV9 (also WMV3)":
203                 return "WMV9"
204         case "Ogg (Vorbis)":
205                 return "Vorbis"
206         case "H264/AVC":
207                 return "H.264"
208         }
209         return codec
210 }
211
212 func parseFileResponse(reply udpapi.APIReply) *File {
213         if reply.Error() != nil {
214                 return nil
215         }
216         if reply.Truncated() {
217                 panic("Truncated")
218         }
219
220         parts := strings.Split(reply.Lines()[1], "|")
221         ints := make([]int64, len(parts))
222         for i, p := range parts {
223                 ints[i], _ = strconv.ParseInt(parts[i], 10, 64)
224                 log.Printf("#%d: %s\n", i, p)
225         }
226
227         // how does epno look like?
228         log.Println("epno: " + parts[23])
229
230         version := FileVersion(1)
231         switch i := ints[6]; {
232         case i&fileStateV5 != 0:
233                 version = 5
234         case i&fileStateV4 != 0:
235                 version = 4
236         case i&fileStateV3 != 0:
237                 version = 3
238         case i&fileStateV2 != 0:
239                 version = 2
240         }
241
242         // codecs (parts[13]), bitrates (ints[14]), langs (parts[19])
243         codecs := strings.Split(parts[13], "'")
244         bitrates := strings.Split(parts[14], "'")
245         alangs := strings.Split(parts[19], "'")
246         streams := make([]AudioStream, len(codecs))
247         for i := range streams {
248                 br, _ := strconv.ParseInt(bitrates[i], 10, 32)
249                 streams[i] = AudioStream{
250                         Bitrate:  int(br),
251                         Codec:    sanitizeCodec(codecs[i]),
252                         Language: Language(alangs[i]),
253                 }
254         }
255
256         sl := strings.Split(parts[20], "'")
257         slangs := make([]Language, len(sl))
258         for i := range sl {
259                 slangs[i] = Language(sl[i])
260         }
261
262         depth := int(ints[11])
263         if depth == 0 {
264                 depth = 8
265         }
266         res := strings.Split(parts[17], "x")
267         width, _ := strconv.ParseInt(res[0], 10, 32)
268         height, _ := strconv.ParseInt(res[1], 10, 32)
269         video := VideoInfo{
270                 Bitrate:    int(ints[16]),
271                 Codec:      sanitizeCodec(parts[15]),
272                 ColorDepth: depth,
273                 Resolution: image.Rect(0, 0, int(width), int(height)),
274         }
275
276         return &File{
277                 FID: FID(ints[0]),
278
279                 AID: AID(ints[1]),
280                 EID: EID(ints[2]),
281                 GID: GID(ints[3]),
282
283                 OtherEpisodes: misc.ParseEpisodeList(parts[4]).Simplify(),
284                 Deprecated:    ints[5] != 0,
285
286                 CRCMatch:   ints[6]&fileStateCRCOK != 0,
287                 BadCRC:     ints[6]&fileStateCRCERR != 0,
288                 Version:    version,
289                 Uncensored: ints[6]&fileStateUncensored != 0,
290                 Censored:   ints[6]&fileStateCensored != 0,
291
292                 Incomplete: video.Resolution.Empty(),
293
294                 Filesize: ints[7],
295                 Ed2kHash: parts[8],
296                 SHA1Hash: parts[9],
297                 CRC32:    parts[10],
298
299                 Source: FileSource(parts[12]),
300
301                 AudioStreams:      streams,
302                 SubtitleLanguages: slangs,
303                 VideoInfo:         video,
304                 FileExtension:     parts[18],
305
306                 Length:  time.Duration(ints[21]) * time.Second,
307                 AirDate: time.Unix(ints[22], 0),
308         }
309 }