smigger22

Untitled

Feb 25th, 2015
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.05 KB | None | 0 0
  1. _jstr = [[
  2. local base = _G
  3.  
  4. -----------------------------------------------------------------------------
  5. -- Module declaration
  6. -----------------------------------------------------------------------------
  7.  
  8. -- Public functions
  9.  
  10. -- Private functions
  11. local decode_scanArray
  12. local decode_scanComment
  13. local decode_scanConstant
  14. local decode_scanNumber
  15. local decode_scanObject
  16. local decode_scanString
  17. local decode_scanWhitespace
  18. local encodeString
  19. local isArray
  20. local isEncodable
  21.  
  22. -----------------------------------------------------------------------------
  23. -- PUBLIC FUNCTIONS
  24. -----------------------------------------------------------------------------
  25. --- Encodes an arbitrary Lua object / variable.
  26. -- @param v The Lua object / variable to be JSON encoded.
  27. -- @return String containing the JSON encoding in internal Lua string format (i.e. not unicode)
  28. function encode (v)
  29. -- Handle nil values
  30. if v==nil then
  31. return "null"
  32. end
  33.  
  34. local vtype = base.type(v)
  35.  
  36. -- Handle strings
  37. if vtype=='string' then
  38. return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string
  39. end
  40.  
  41. -- Handle booleans
  42. if vtype=='number' or vtype=='boolean' then
  43. return base.tostring(v)
  44. end
  45.  
  46. -- Handle tables
  47. if vtype=='table' then
  48. local rval = {}
  49. -- Consider arrays separately
  50. local bArray, maxCount = isArray(v)
  51. if bArray then
  52. for i = 1,maxCount do
  53. table.insert(rval, encode(v[i]))
  54. end
  55. else -- An object, not an array
  56. for i,j in base.pairs(v) do
  57. if isEncodable(i) and isEncodable(j) then
  58. table.insert(rval, '"' .. encodeString(i) .. '":' .. encode(j))
  59. end
  60. end
  61. end
  62. if bArray then
  63. return '[' .. table.concat(rval,',') ..']'
  64. else
  65. return '{' .. table.concat(rval,',') .. '}'
  66. end
  67. end
  68.  
  69. -- Handle null values
  70. if vtype=='function' and v==null then
  71. return 'null'
  72. end
  73.  
  74. base.assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. base.tostring(v))
  75. end
  76.  
  77.  
  78. --- Decodes a JSON string and returns the decoded value as a Lua data structure / value.
  79. -- @param s The string to scan.
  80. -- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1.
  81. -- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil,
  82. -- and the position of the first character after
  83. -- the scanned JSON object.
  84. function decode(s, startPos)
  85. startPos = startPos and startPos or 1
  86. startPos = decode_scanWhitespace(s,startPos)
  87. base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']')
  88. local curChar = string.sub(s,startPos,startPos)
  89. -- Object
  90. if curChar=='{' then
  91. return decode_scanObject(s,startPos)
  92. end
  93. -- Array
  94. if curChar=='[' then
  95. return decode_scanArray(s,startPos)
  96. end
  97. -- Number
  98. if string.find("+-0123456789.e", curChar, 1, true) then
  99. return decode_scanNumber(s,startPos)
  100. end
  101. -- String
  102. if curChar=='"' or curChar=="'" then
  103. return decode_scanString(s,startPos)
  104. end
  105. if string.sub(s,startPos,startPos+1)=='/*' then
  106. return decode(s, decode_scanComment(s,startPos))
  107. end
  108. -- Otherwise, it must be a constant
  109. return decode_scanConstant(s,startPos)
  110. end
  111.  
  112. --- The null function allows one to specify a null value in an associative array (which is otherwise
  113. -- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null }
  114. function null()
  115. return null -- so json.null() will also return null ;-)
  116. end
  117. -----------------------------------------------------------------------------
  118. -- Internal, PRIVATE functions.
  119. -- Following a Python-like convention, I have prefixed all these 'PRIVATE'
  120. -- functions with an underscore.
  121. -----------------------------------------------------------------------------
  122.  
  123. --- Scans an array from JSON into a Lua object
  124. -- startPos begins at the start of the array.
  125. -- Returns the array and the next starting position
  126. -- @param s The string being scanned.
  127. -- @param startPos The starting position for the scan.
  128. -- @return table, int The scanned array as a table, and the position of the next character to scan.
  129. function decode_scanArray(s,startPos)
  130. local array = {} -- The return value
  131. local stringLen = string.len(s)
  132. base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s )
  133. startPos = startPos + 1
  134. -- Infinite loop for array elements
  135. repeat
  136. startPos = decode_scanWhitespace(s,startPos)
  137. base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.')
  138. local curChar = string.sub(s,startPos,startPos)
  139. if (curChar==']') then
  140. return array, startPos+1
  141. end
  142. if (curChar==',') then
  143. startPos = decode_scanWhitespace(s,startPos+1)
  144. end
  145. base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.')
  146. object, startPos = decode(s,startPos)
  147. table.insert(array,object)
  148. until false
  149. end
  150.  
  151. --- Scans a comment and discards the comment.
  152. -- Returns the position of the next character following the comment.
  153. -- @param string s The JSON string to scan.
  154. -- @param int startPos The starting position of the comment
  155. function decode_scanComment(s, startPos)
  156. base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos)
  157. local endPos = string.find(s,'*/',startPos+2)
  158. base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos)
  159. return endPos+2
  160. end
  161.  
  162. --- Scans for given constants: true, false or null
  163. -- Returns the appropriate Lua type, and the position of the next character to read.
  164. -- @param s The string being scanned.
  165. -- @param startPos The position in the string at which to start scanning.
  166. -- @return object, int The object (true, false or nil) and the position at which the next character should be
  167. -- scanned.
  168. function decode_scanConstant(s, startPos)
  169. local consts = { ["true"] = true, ["false"] = false, ["null"] = nil }
  170. local constNames = {"true","false","null"}
  171.  
  172. for i,k in base.pairs(constNames) do
  173. --print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k)
  174. if string.sub(s,startPos, startPos + string.len(k) -1 )==k then
  175. return consts[k], startPos + string.len(k)
  176. end
  177. end
  178. base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos)
  179. end
  180.  
  181. --- Scans a number from the JSON encoded string.
  182. -- (in fact, also is able to scan numeric +- eqns, which is not
  183. -- in the JSON spec.)
  184. -- Returns the number, and the position of the next character
  185. -- after the number.
  186. -- @param s The string being scanned.
  187. -- @param startPos The position at which to start scanning.
  188. -- @return number, int The extracted number and the position of the next character to scan.
  189. function decode_scanNumber(s,startPos)
  190. local endPos = startPos+1
  191. local stringLen = string.len(s)
  192. local acceptableChars = "+-0123456789.e"
  193. while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true)
  194. and endPos<=stringLen
  195. ) do
  196. endPos = endPos + 1
  197. end
  198. local stringValue = 'return ' .. string.sub(s,startPos, endPos-1)
  199. local stringEval = base.loadstring(stringValue)
  200. base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos)
  201. return stringEval(), endPos
  202. end
  203.  
  204. --- Scans a JSON object into a Lua object.
  205. -- startPos begins at the start of the object.
  206. -- Returns the object and the next starting position.
  207. -- @param s The string being scanned.
  208. -- @param startPos The starting position of the scan.
  209. -- @return table, int The scanned object as a table and the position of the next character to scan.
  210. function decode_scanObject(s,startPos)
  211. local object = {}
  212. local stringLen = string.len(s)
  213. local key, value
  214. base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s)
  215. startPos = startPos + 1
  216. repeat
  217. startPos = decode_scanWhitespace(s,startPos)
  218. base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.')
  219. local curChar = string.sub(s,startPos,startPos)
  220. if (curChar=='}') then
  221. return object,startPos+1
  222. end
  223. if (curChar==',') then
  224. startPos = decode_scanWhitespace(s,startPos+1)
  225. end
  226. base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.')
  227. -- Scan the key
  228. key, startPos = decode(s,startPos)
  229. base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
  230. startPos = decode_scanWhitespace(s,startPos)
  231. base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
  232. base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos)
  233. startPos = decode_scanWhitespace(s,startPos+1)
  234. base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
  235. value, startPos = decode(s,startPos)
  236. object[key]=value
  237. until false -- infinite loop while key-value pairs are found
  238. end
  239.  
  240. --- Scans a JSON string from the opening inverted comma or single quote to the
  241. -- end of the string.
  242. -- Returns the string extracted as a Lua string,
  243. -- and the position of the next non-string character
  244. -- (after the closing inverted comma or single quote).
  245. -- @param s The string being scanned.
  246. -- @param startPos The starting position of the scan.
  247. -- @return string, int The extracted string as a Lua string, and the next character to parse.
  248. function decode_scanString(s,startPos)
  249. base.assert(startPos, 'decode_scanString(..) called without start position')
  250. local startChar = string.sub(s,startPos,startPos)
  251. base.assert(startChar=="'" or startChar=='"','decode_scanString called for a non-string')
  252. local escaped = false
  253. local endPos = startPos + 1
  254. local bEnded = false
  255. local stringLen = string.len(s)
  256. repeat
  257. local curChar = string.sub(s,endPos,endPos)
  258. -- Character escaping is only used to escape the string delimiters
  259. if not escaped then
  260. if curChar=='\\' then
  261. escaped = true
  262. else
  263. bEnded = curChar==startChar
  264. end
  265. else
  266. -- If we're escaped, we accept the current character come what may
  267. escaped = false
  268. end
  269. endPos = endPos + 1
  270. base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos)
  271. until bEnded
  272. local stringValue = 'return ' .. string.sub(s, startPos, endPos-1)
  273. local stringEval = base.loadstring(stringValue)
  274. base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos)
  275. return stringEval(), endPos
  276. end
  277.  
  278. --- Scans a JSON string skipping all whitespace from the current start position.
  279. -- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached.
  280. -- @param s The string being scanned
  281. -- @param startPos The starting position where we should begin removing whitespace.
  282. -- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string
  283. -- was reached.
  284. function decode_scanWhitespace(s,startPos)
  285. local whitespace=" \n\r\t"
  286. local stringLen = string.len(s)
  287. while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do
  288. startPos = startPos + 1
  289. end
  290. return startPos
  291. end
  292.  
  293. --- Encodes a string to be JSON-compatible.
  294. -- This just involves back-quoting inverted commas, back-quotes and newlines, I think ;-)
  295. -- @param s The string to return as a JSON encoded (i.e. backquoted string)
  296. -- @return The string appropriately escaped.
  297. function encodeString(s)
  298. s = string.gsub(s,'\\','\\\\')
  299. s = string.gsub(s,'"','\\"')
  300. s = string.gsub(s,"'","\\'")
  301. s = string.gsub(s,'\n','\\n')
  302. s = string.gsub(s,'\t','\\t')
  303. return s
  304. end
  305.  
  306. -- Determines whether the given Lua type is an array or a table / dictionary.
  307. -- We consider any table an array if it has indexes 1..n for its n items, and no
  308. -- other data in the table.
  309. -- I think this method is currently a little 'flaky', but can't think of a good way around it yet...
  310. -- @param t The table to evaluate as an array
  311. -- @return boolean, number True if the table can be represented as an array, false otherwise. If true,
  312. -- the second returned value is the maximum
  313. -- number of indexed elements in the array.
  314. function isArray(t)
  315. -- Next we count all the elements, ensuring that any non-indexed elements are not-encodable
  316. -- (with the possible exception of 'n')
  317. local maxIndex = 0
  318. for k,v in base.pairs(t) do
  319. if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair
  320. if (not isEncodable(v)) then return false end -- All array elements must be encodable
  321. maxIndex = math.max(maxIndex,k)
  322. else
  323. if (k=='n') then
  324. if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements
  325. else -- Else of (k=='n')
  326. if isEncodable(v) then return false end
  327. end -- End of (k~='n')
  328. end -- End of k,v not an indexed pair
  329. end -- End of loop across all pairs
  330. return true, maxIndex
  331. end
  332.  
  333. --- Determines whether the given Lua object / table / variable can be JSON encoded. The only
  334. -- types that are JSON encodable are: string, boolean, number, nil, table and json.null.
  335. -- In this implementation, all other types are ignored.
  336. -- @param o The object to examine.
  337. -- @return boolean True if the object should be JSON encoded, false if it should be ignored.
  338. function isEncodable(o)
  339. local t = base.type(o)
  340. return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null)
  341. end
  342. ]]
  343.  
  344. function loadJSON()
  345. local sName = 'JSON'
  346.  
  347. local tEnv = {}
  348. setmetatable( tEnv, { __index = _G } )
  349. local fnAPI, err = loadstring(_jstr)
  350. if fnAPI then
  351. setfenv( fnAPI, tEnv )
  352. fnAPI()
  353. else
  354. printError( err )
  355. return false
  356. end
  357.  
  358. local tAPI = {}
  359. for k,v in pairs( tEnv ) do
  360. tAPI[k] = v
  361. end
  362.  
  363. _G[sName] = tAPI
  364. return true
  365. end
  366.  
  367. function downloadJSON(path)
  368. local _json = http.get(path)
  369. if not _json then
  370. error('Could not download: '..path..' Check your connection.')
  371. end
  372. return JSON.decode(_json.readAll())
  373. end
  374.  
  375. function draw(main, sub)
  376. term.setBackgroundColour(colours.white)
  377. term.setTextColour(colours.black)
  378. term.clear()
  379. term.setBackgroundColour(colours.grey)
  380. for i = 1, 3 do
  381. term.setCursorPos(1, i)
  382. term.clearLine()
  383. end
  384. term.setCursorPos(2, 2)
  385. term.setTextColour(colours.white)
  386. write("RetroOS Installer")
  387. term.setBackgroundColour(colours.black)
  388. term.setCursorPos(51 / 2 - #main / 2, 19 / 2 - 2)
  389. write(main)
  390. term.setCursorPos(51 / 2 - #sub / 2, 19 / 2 + 2)
  391. write(sub)
  392. end
  393.  
  394. loadJSON()
  395.  
  396. details = {
  397. repo = "RetroOS",
  398. user = "smigger22",
  399. path = "/",
  400. TBytes = 0,
  401. DBytes = 0
  402. }
  403.  
  404. release = downloadJSON('https://api.github.com/repos/'..details.user..'/'..details.repo..'/releases')
  405. releaseTag = nil
  406. for k, v in pairs(release) do
  407. if not v.prerelease then
  408. releaseTag = v.tag_name
  409. break
  410. end
  411. end
  412.  
  413. refs = downloadJSON('https://api.github.com/repos/'..details.user..'/'..details.repo..'/git/refs/tags/'..releaseTag)
  414. releaseSHA = refs.object.sha
  415.  
  416. tree = downloadJSON('https://api.github.com/repos/'..details.user..'/'..details.repo..'/git/trees/'..releaseSHA..'?recursive=1').tree
  417.  
  418. details.TFiles = 0
  419. details.TBytes = 0
  420.  
  421. for k, v in pairs(tree) do
  422. if v.size then
  423. details.TBytes = details.TBytes + v.size
  424. details.TFiles = details.TFiles + 1
  425. end
  426. end
  427.  
  428. details.DFiles = 0
  429. details.DBytes = 0
  430.  
  431. function downloadB(v)
  432. tries, f = 0
  433. repeat
  434. f = http.get(('https://raw.github.com/'..details.user..'/'..details.repo..'/'..releaseTag..details.path..v.path):gsub(' ','%%20'))
  435. if not f then sleep(5) end
  436. tries = tries + 1
  437. until tries > 5 or f
  438.  
  439. if not f then
  440. error('Downloading failed, try again. '..('https://raw.github.com/'..details.user..'/'..details.repo..'/'..releaseTag..details.path..v.path):gsub(' ','%%20'))
  441. end
  442.  
  443. local h = fs.open('/'..details.path..v.path, 'w')
  444. h.write(f.readAll())
  445. h.close()
  446. draw('Downloading', math.floor(100*(details.DFiles / details.TFiles))..'%')
  447.  
  448. if v.size then
  449. details.DBytes = details.DBytes + v.size
  450. details.DFiles = details.DFiles + 1
  451. end
  452. end
  453.  
  454. downloads = {}
  455. cLimit = 5
  456. for i, v in ipairs(tree) do
  457. local queueNumber = math.ceil(i / cLimit)
  458. if not downloads[queueNumber] then
  459. downloads[queueNumber] = {}
  460. end
  461. table.insert(downloads[queueNumber], function() downloadB(v) end)
  462. end
  463.  
  464. for i, queue in ipairs(downloads) do
  465. parallel.waitForAll(unpack(queue))
  466. end
  467.  
  468. draw("Complete!", "Rebooting")
  469. sleep(1)
  470. os.reboot()
Advertisement
Add Comment
Please, Sign In to add comment