-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcache.brs
89 lines (70 loc) · 2.34 KB
/
cache.brs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
'
' Cache
'
' Examples:
' @TODO
'
function CacheUtil(key as String, options = invalid as Dynamic) as Object
algorithm = "sha1"
storage = "cachefs:/"
ttl = 5
if options <> invalid then
if options.algorithm <> invalid then algorithm = options.algorithm
if options.storage <> invalid then storage = options.storage
if options.ttl <> invalid then ttl = options.ttl
end if
ba = createObject("roByteArray")
ba.fromAsciiString(key)
digest = createObject("roEVPDigest")
digest.setup(algorithm)
cacheKey = digest.process(ba)
return {
_filePath: storage + cacheKey
_ttl: ttl
_separator: chr(10)
_getNowTimeAsSeconds: function() as Integer
date = createObject("roDateTime")
return date.AsSeconds()
end function
match: function() as Boolean
fs = createObject("roFileSystem")
return fs.exists(m._filePath)
end function
put: function(value as String) as Boolean
if value = invalid then return false
stringToCache = m._getNowTimeAsSeconds().toStr() + m._separator + value
return writeAsciiFile(m._filePath, stringToCache)
end function
delete: function() as Boolean
fs = createObject("roFileSystem")
return fs.delete(m._filePath)
end function
get: function() as Dynamic
if not m.match() then return invalid
cachedData = readAsciiFile(m._filePath)
if cachedData = "" then
m.delete()
return invalid
end if
cachedArray = cachedData.split(m._separator)
if cachedArray.count() <> 2 then
m.delete()
return invalid
end if
cachedValue = cachedArray[1]
if cachedValue = invalid then
m.delete()
return invalid
end if
if m._ttl <> invalid then
cachedTimestamp = cachedArray[0].toInt()
nowTimestamp = m._getNowTimeAsSeconds()
if cachedTimestamp + m._ttl < nowTimestamp then
m.delete()
return invalid
end if
end if
return cachedValue
end function
}
end function