-
Notifications
You must be signed in to change notification settings - Fork 4
/
CacheFS.brs
65 lines (48 loc) · 1.9 KB
/
CacheFS.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
' @import /components/rokuComponents/EVPDigest.brs
' WARNING: the service must be used on the Task threads.
function CacheFS() as Object
prototype = {}
prototype._PREFIX = "cachefs:/"
prototype._digest = Invalid
prototype._fileSystem = Invalid
_constructor = function (m as Object) as Object
m._digest = EVPDigest()
m._digest.setup("sha1")
m._fileSystem = CreateObject("roFileSystem")
return m
end function
' Reads data stored in cachefs under the specific key
' @param {String} key
' @returns {Object} Invalid if key is incorrect or is not stored
prototype.read = function (key as String) as Object
if (key = "") then return Invalid
filePath = m._PREFIX + m._hash(key)
if (NOT m._fileSystem.exists(filePath)) then return Invalid
content = ReadAsciiFile(filePath)
return ParseJson(content, "i")
end function
' Writes data into cachefs under the specific key
' @param {String} key
' @param {Object} data - any value acceptable by native FormatJson function except Invalid
' @returns {Boolean} false if data is not parseable, Invalid or if storing failed
prototype.write = function (key as String, data as Object) as Boolean
if (key = "" OR data = Invalid) then return false
content = FormatJson(data)
if (content = "") then return false
return WriteAsciiFile(m._PREFIX + m._hash(key), content)
end function
' Deletes data from cachefs under the specific key
' @param {String} key
' @returns {Boolean} true if data successfully removed
prototype.delete = function (key as String) as Boolean
if (key = "") then return false
return DeleteFile(m._PREFIX + m._hash(key))
end function
' @private
prototype._hash = function (text as String) as String
byteArray = CreateObject("roByteArray")
byteArray.fromAsciiString(text)
return m._digest.process(byteArray)
end function
return _constructor(prototype)
end function