· 6 years ago · Mar 24, 2020, 05:48 AM
1-- Python Web | Lua API
2local PYWEB_ADR = "https://pythonweb.reactified.repl.co/"
3local STORE_KEY = false
4
5-- Functions
6function ping()
7 local h = http.get(PYWEB_ADR)
8 if h then
9 local data = h.readAll()
10 h.close()
11 if data == "invalid usage" then
12 return true,"Server online"
13 else
14 return false,"Server offline"
15 end
16 else
17 return false,"Server offline"
18 end
19end
20function setKey(key)
21 local h = http.get(PYWEB_ADR.."?key="..key)
22 if h then
23 data = h.readLine()
24 h.close()
25 if data ~= "key valid" then
26 return false,"Key invalid"
27 else
28 STORE_KEY = key
29 return true,"Key validated"
30 end
31 else
32 return false,"Server offline"
33 end
34end
35function save(file,data)
36 if not STORE_KEY then
37 return false,"Key not set"
38 end
39 if type(file) ~= "string" then
40 return false,"Invalid file"
41 end
42 if type(data) == "boolean" then
43 data = "!BOO:"..tostring(data)
44 elseif type(data) == "number" then
45 data = "!NUM:"..tostring(data)
46 elseif type(data) == "table" then
47 data = textutils.serialise(data)
48 local newTbl = ""
49 for i=1,#data do
50 char = string.sub(data,i,i)
51 newTbl = newTbl..tostring(string.byte(char))..","
52 end
53 data = "!TBL:"..newTbl
54 elseif type(data) == "string" then
55 data = "!STR:"..data
56 end
57 local h = http.get(PYWEB_ADR.."?key="..STORE_KEY.."&write="..file.."&data="..data)
58 if h then
59 local data = h.readAll()
60 h.close()
61 if data == "data written" then
62 return true,"Data written"
63 end
64 else
65 return false,"Server offline",data
66 end
67end
68function load(file)
69 if not STORE_KEY then
70 return false,"Key not set"
71 end
72 if type(file) ~= "string" then
73 return false,"Invalid file"
74 end
75 local h = http.get(PYWEB_ADR.."?key="..STORE_KEY.."&read="..file)
76 if h then
77 local data = h.readAll()
78 local datatype = string.sub(data,1,5)
79 data = string.sub(data,6,#data)
80 h.close()
81 if datatype == "!STR:" then
82 return true,data
83 elseif datatype == "!BOO:" then
84 if data == "true" then
85 return true,true
86 else
87 return true,false
88 end
89 elseif datatype == "!NUM:" then
90 return true,tonumber(data)
91 elseif datatype == "!TBL:" then
92 local newTbl = ""
93 local str = ""
94 for i=1,#data do
95 local char = string.sub(data,i,i)
96 if char == "," then
97 newTbl = newTbl .. string.char(tonumber(str))
98 str = ""
99 else
100 str = str .. char
101 end
102 end
103 return true,textutils.unserialise(newTbl)
104 else
105 return true,data
106 end
107 else
108 if ping() then
109 return false,"Invalid file"
110 else
111 return false,"Server offline"
112 end
113 end
114end