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