Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local nick = "rockettek"
- local password = "oauth:c306b08cc06j7foa7uzxez63fyiff4"
- local base = _G
- local decode_scanArray
- local decode_scanComment
- local decode_scanConstant
- local decode_scanNumber
- local decode_scanObject
- local decode_scanString
- local decode_scanWhitespace
- local encodeString
- local isArray
- local isEncodable
- local counter = 0
- local sessionID = ""
- local function encode (v)
- -- Handle nil values
- if v==nil then
- return "null"
- end
- local vtype = base.type(v)
- -- Handle strings
- if vtype=='string' then
- return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string
- end
- -- Handle booleans
- if vtype=='number' or vtype=='boolean' then
- return base.tostring(v)
- end
- -- Handle tables
- if vtype=='table' then
- local rval = {}
- -- Consider arrays separately
- local bArray, maxCount = isArray(v)
- if bArray then
- for i = 1,maxCount do
- table.insert(rval, encode(v[i]))
- end
- else -- An object, not an array
- for i,j in base.pairs(v) do
- if isEncodable(i) and isEncodable(j) then
- table.insert(rval, '"' .. encodeString(i) .. '":' .. encode(j))
- end
- end
- end
- if bArray then
- return '[' .. table.concat(rval,',') ..']'
- else
- return '{' .. table.concat(rval,',') .. '}'
- end
- end
- -- Handle null values
- if vtype=='function' and v==null then
- return 'null'
- end
- base.assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. base.tostring(v))
- end
- local function decode(s, startPos)
- startPos = startPos and startPos or 1
- startPos = decode_scanWhitespace(s,startPos)
- base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']')
- local curChar = string.sub(s,startPos,startPos)
- -- Object
- if curChar=='{' then
- return decode_scanObject(s,startPos)
- end
- -- Array
- if curChar=='[' then
- return decode_scanArray(s,startPos)
- end
- -- Number
- if string.find("+-0123456789.e", curChar, 1, true) then
- return decode_scanNumber(s,startPos)
- end
- -- String
- if curChar==[["]] or curChar==[[']] then
- return decode_scanString(s,startPos)
- end
- if string.sub(s,startPos,startPos+1)=='/*' then
- return decode(s, decode_scanComment(s,startPos))
- end
- -- Otherwise, it must be a constant
- return decode_scanConstant(s,startPos)
- end
- local function null()
- return null -- so json.null() will also return null ;-)
- end
- function decode_scanArray(s,startPos)
- local array = {} -- The return value
- local stringLen = string.len(s)
- base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s )
- startPos = startPos + 1
- -- Infinite loop for array elements
- repeat
- startPos = decode_scanWhitespace(s,startPos)
- base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.')
- local curChar = string.sub(s,startPos,startPos)
- if (curChar==']') then
- return array, startPos+1
- end
- if (curChar==',') then
- startPos = decode_scanWhitespace(s,startPos+1)
- end
- base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.')
- object, startPos = decode(s,startPos)
- table.insert(array,object)
- until false
- end
- function decode_scanComment(s, startPos)
- base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos)
- local endPos = string.find(s,'*/',startPos+2)
- base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos)
- return endPos+2
- end
- function decode_scanConstant(s, startPos)
- local consts = { ["true"] = true, ["false"] = false, ["null"] = nil }
- local constNames = {"true","false","null"}
- for i,k in base.pairs(constNames) do
- --print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k)
- if string.sub(s,startPos, startPos + string.len(k) -1 )==k then
- return consts[k], startPos + string.len(k)
- end
- end
- base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos)
- end
- function decode_scanNumber(s,startPos)
- local endPos = startPos+1
- local stringLen = string.len(s)
- local acceptableChars = "+-0123456789.e"
- while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true)
- and endPos<=stringLen
- ) do
- endPos = endPos + 1
- end
- local stringValue = 'return ' .. string.sub(s,startPos, endPos-1)
- local stringEval = base.loadstring(stringValue)
- base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos)
- return stringEval(), endPos
- end
- function decode_scanObject(s,startPos)
- local object = {}
- local stringLen = string.len(s)
- local key, value
- base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s)
- startPos = startPos + 1
- repeat
- startPos = decode_scanWhitespace(s,startPos)
- base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.')
- local curChar = string.sub(s,startPos,startPos)
- if (curChar=='}') then
- return object,startPos+1
- end
- if (curChar==',') then
- startPos = decode_scanWhitespace(s,startPos+1)
- end
- base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.')
- -- Scan the key
- key, startPos = decode(s,startPos)
- base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
- startPos = decode_scanWhitespace(s,startPos)
- base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
- base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos)
- startPos = decode_scanWhitespace(s,startPos+1)
- base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
- value, startPos = decode(s,startPos)
- object[key]=value
- until false -- infinite loop while key-value pairs are found
- end
- function decode_scanString(s,startPos)
- base.assert(startPos, 'decode_scanString(..) called without start position')
- local startChar = string.sub(s,startPos,startPos)
- base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string')
- local escaped = false
- local endPos = startPos + 1
- local bEnded = false
- local stringLen = string.len(s)
- repeat
- local curChar = string.sub(s,endPos,endPos)
- -- Character escaping is only used to escape the string delimiters
- if not escaped then
- if curChar==[[\]] then
- escaped = true
- else
- bEnded = curChar==startChar
- end
- else
- -- If we're escaped, we accept the current character come what may
- escaped = false
- end
- endPos = endPos + 1
- base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos)
- until bEnded
- local stringValue = 'return ' .. string.sub(s, startPos, endPos-1)
- local stringEval = base.loadstring(stringValue)
- base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos)
- return stringEval(), endPos
- end
- function decode_scanWhitespace(s,startPos)
- local whitespace=" \n\r\t"
- local stringLen = string.len(s)
- while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do
- startPos = startPos + 1
- end
- return startPos
- end
- function encodeString(s)
- s = string.gsub(s,'\\','\\\\')
- s = string.gsub(s,'"','\\"')
- s = string.gsub(s,'\n','\\n')
- s = string.gsub(s,'\t','\\t')
- return s
- end
- function isArray(t)
- -- Next we count all the elements, ensuring that any non-indexed elements are not-encodable
- -- (with the possible exception of 'n')
- local maxIndex = 0
- for k,v in base.pairs(t) do
- if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair
- if (not isEncodable(v)) then return false end -- All array elements must be encodable
- maxIndex = math.max(maxIndex,k)
- else
- if (k=='n') then
- if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements
- else -- Else of (k=='n')
- if isEncodable(v) then return false end
- end -- End of (k~='n')
- end -- End of k,v not an indexed pair
- end -- End of loop across all pairs
- return true, maxIndex
- end
- function isEncodable(o)
- local t = base.type(o)
- return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null)
- end
- local post = function(url,data)
- local cacheAvoidance = "abc"..tostring(math.random(0,10000)) -- not sure if this is needed...
- local resp = http.post("http://86.11.11.101:9090/e/"..url,"r="..cacheAvoidance.."&t="..tostring(counter)..data)
- counter = counter + 1
- return resp
- end
- -- better responsiveness with asynchronous methods as we usually let the recv couroutine handle the responses
- local request = function(url,data)
- local cacheAvoidance = "abc"..tostring(math.random(0,10000)) -- not sure if this is needed...
- http.request("http://86.11.11.101:9090/e/"..url,"r="..cacheAvoidance.."&t="..tostring(counter)..data)
- counter = counter + 1
- end
- -- these special URLs are used by the webchat server for different methods
- local send = function(data)
- return request("p","&s="..sessionID.."&c="..textutils.urlEncode(data))
- end
- local recv = function()
- return post("s","&s="..sessionID)
- end
- local connect = function(password)
- if password ~= nil then
- return post("n","&nick="..nick.."&password="..password)
- else
- return post("n","&nick="..nick)
- end
- end
- local pong = function(data)
- return send("PONG :"..data)
- end
- local quit = function(_reason)
- local reason = _reason or ""
- return send("QUIT :"..reason)
- end
- -- lua default string methods suck :/
- local split = function(str,sep)
- local sep, fields = sep or ":", {}
- local pattern = string.format("([^%s]+)", sep)
- str:gsub(pattern, function(c) fields[#fields+1] = c end)
- return fields
- end
- --[[
- local handleResponse = function(data)
- for i = 1, #data do
- local id = data[i][2]
- if id == "PING" then
- pong(data[i][4][1])
- elseif id == "PRIVMSG" then
- local senderDetails = data[i][3]
- local sender = senderDetails:sub(1,senderDetails:find("!")-1)
- local channel = data[i][4][1]:lower()
- if channel == nick then
- channel = sender
- end
- local msg = data[i][4][2]
- --exec
- print("<"..sender.."> "..msg)
- end
- print("<"..sender.."> "..msg)
- end
- end
- ]]
- local handleResponse = function(data)
- print(textutils.serialize(data))
- for i = 1, #data do
- local id = data[i][2]
- if id == "PING" then
- pong(data[i][4][1])
- elseif id == "PRIVMSG" then
- local senderDetails = data[i][3]
- local sender = senderDetails:sub(1,senderDetails:find("!")-1)
- local channel = data[i][4][1]:lower()
- print(textutils.serialize(data[i]))
- print(channel)
- local msg = data[i][4][2]
- print("<"..sender.."> "..msg)
- else
- print(data[i])
- end
- end
- end
- print("Connecting...")
- resp = connect(password)
- --if not resp then term.clear() term.setCursorPos(1,1) term.write("Unable to connect to IRC bridge!") os.pullEvent() os.reboot() end
- _data = resp.readAll()
- data = decode(_data)
- sessionID = data[2]
- print("Got sessionID: "..sessionID)
- send("JOIN #rockettek")
- local receive = function()
- resp = recv()
- while resp do
- _data = resp.readAll()
- if #_data > 0 then
- data = decode(_data)
- handleResponse(data)
- end
- resp = recv()
- end
- end
- receive()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement