faubiguy

Code-block retriever

Oct 3rd, 2012
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 7.72 KB | None | 0 0
  1. local function getInfo(label)
  2.  local id
  3.  while true do
  4.   term.clear()
  5.   term.setCursorPos(1, 1)
  6.   print("Enter the " .. label .. " of the post to get code from:")
  7.   id = tonumber(read())
  8.   if id then break end
  9.   print("Error: That is not a number. Please try again.")
  10.   sleep(3)
  11.  end
  12.  term.clear()
  13.  term.setCursorPos(1, 1)
  14.  return id
  15. end
  16.  
  17. local function hasError(page)
  18.  return string.find(page, "<h1 class='ipsType_pagetitle'>An Error Occurred</h1>") and true
  19. end
  20.  
  21. local function getPage(url)
  22.  local page
  23.  for attempts=1,3 do
  24.   print("Downloading Page: Attempt " .. attempts)
  25.   page = http.get(url)
  26.   if page then print("Download Successful!") break
  27.   else print("Download Failed!") end
  28.   if attempts < 3 then print("Retrying...") end
  29.  end
  30.  if not page then return end
  31.  local html = page.readAll()
  32.  page.close()
  33.  return html
  34. end
  35.  
  36. local function contains(tabl, item)
  37.  for _,value in ipairs(tabl) do
  38.   if value == item then return true end
  39.  end
  40.  return false
  41. end
  42.  
  43. local function extractCode(page)
  44.  local codes = {}
  45.  local matches = 0
  46.  print("Extracting Codes.")
  47.  for code in string.gmatch(page, "<pre class='prettyprint'>(.-)</pre>") do
  48.   if not contains(codes, code) then
  49.    table.insert(codes, code)
  50.   end
  51.  end
  52.  print(#codes .. " Code Blocks Found")
  53.  return codes
  54. end
  55.  
  56. local function makeURL(id, pageNum)
  57.  return "http://www.computercraft.info/forums2/index.php?/topic/"..id.."-/page__st_" .. 20*(pageNum-1)
  58. end
  59.  
  60. function unescape(codes)
  61.  replace = {["quot"] = [["]], ["apos"] = [[']], ["amp"] = "&", ["lt"] = "<", ["gt"] = ">"}
  62. newcodes = {}
  63. for i,code in ipairs(codes) do
  64.  table.insert(newcodes, ({string.gsub(code, "&#?(%w-);", function(word) return replace[word] or string.char(tonumber(word)) end)})[1])
  65.  newcodes[#newcodes] = string.gsub(newcodes[#newcodes], "<br />", "\n")
  66. end
  67. return newcodes
  68. end
  69.  
  70. local function displayCodes(codes)
  71. local codeLines = {}
  72. local termHeight = ({term.getSize()})[2]
  73. local lineUp = 0
  74. local lineDown = termHeight+1
  75. local menuOpen = false
  76. local codeNumber = 1
  77. local option = 1
  78. local options = {"[Save]  Delete   Exit", " Save  [Delete]  Exit", " Save   Delete  [Exit]"}
  79. for _,codeString in ipairs(codes) do
  80.  local code={}
  81.  codeString = "\n"..codeString.."\n"
  82.  while true do
  83.   local line, subPos = string.match(codeString, "\n(.-)()\n")
  84.   if not line then break end
  85.   table.insert(code, line)
  86.   codeString = string.sub(codeString, subPos)
  87.  end
  88.  table.insert(codeLines, code)
  89. end
  90. loadDisplay(codeLines[codeNumber])
  91. while true do
  92.  e,p = os.pullEvent("key")
  93.  if not menuOpen then
  94.   if p == keys.up then
  95.    if lineUp >= 0 then
  96.     term.scroll(-1)
  97.     term.setCursorPos(1, 1)
  98.     term.write(codeLines[codeNumber][lineUp])
  99.     lineDown = lineDown - 1
  100.     lineUp = lineUp - 1
  101.    end
  102.   elseif p == keys.down then
  103.    if lineDown <= #codeLines[codeNumber] then
  104.     term.scroll(1)
  105.     term.setCursorPos(1, termHeight)
  106.     term.write(codeLines[codeNumber][lineDown])
  107.     lineDown = lineDown + 1
  108.     lineUp = lineUp + 1
  109.    end
  110.   elseif p == keys.left then
  111.    if codeNumber > 1 then
  112.     codeNumber = codeNumber - 1
  113.     loadDisplay(codeLines[codeNumber])
  114.     lineUp = 0
  115.     lineDown = termHeight+1
  116.    end
  117.   elseif p == keys.right then
  118.    if codeNumber < #codeLines then
  119.     codeNumber = codeNumber + 1
  120.     loadDisplay(codeLines[codeNumber])
  121.     lineUp = 0
  122.     lineDown = termHeight+1
  123.    end
  124.   elseif p == keys.rightCtrl or p == keys.leftCtrl then
  125.    term.setCursorPos(1, termHeight)
  126.    option = 1
  127.     term.clearLine()
  128.    term.write(options[option])
  129.    menuOpen = true
  130.   end
  131.  else
  132.   if p == keys.leftCtrl or p == keys.rightCtrl then
  133.    term.setCursorPos(1, termHeight)
  134.    term.clearLine()
  135.    if codeLines[codeNumber][lineDown-1] then term.write(codeLines[codeNumber][lineDown-1]) end
  136.    menuOpen = false
  137.   elseif p == keys.left then
  138.    option = ((option-2)%3)+1
  139.    term.setCursorPos(1, termHeight)
  140.    term.clearLine()
  141.    term.write(options[option])
  142.   elseif p == keys.right then
  143.    option = ((option)%3)+1
  144.    term.setCursorPos(1, termHeight)
  145.    term.clearLine()
  146.    term.write(options[option])
  147.   elseif p == keys.enter then
  148.    if option == 1 then
  149.     save(codeLines[codeNumber])
  150.      table.remove(codeLines, codeNumber)
  151.     codeNumber = 1
  152.     if #codeLines < 1 then
  153.      return true
  154.     end
  155.     loadDisplay(codeLines[codeNumber])
  156.      menuOpen = false
  157.    elseif option == 2 then
  158.     table.remove(codeLines, codeNumber)
  159.     codeNumber = 1
  160.     if #codeLines < 1 then
  161.      return true
  162.     end
  163.     loadDisplay(codeLines[codeNumber])
  164.     lineUp = 0
  165.     lineDown = termHeight+1
  166.      menuOpen = false
  167.     elseif option == 3 then return false
  168.    end
  169.   end
  170.  end
  171. end
  172. end
  173.  
  174. function loadDisplay(lines, offset)
  175. term.clear()
  176. term.setCursorPos(1, 1)
  177. offset = offset or 0
  178. local height = ({term.getSize()})[2]
  179. term.clear()
  180. term.setCursorPos(1, 1)
  181. for index = 1,height do
  182.  term.setCursorPos(1, index)
  183.  if lines[index+offset] then term.write(lines[index+offset]) else break end
  184. end
  185. end
  186.  
  187. function save(lines)
  188. local saved = false
  189. while not saved do
  190.  while not saved do
  191.   term.clear()
  192.   term.setCursorPos(1, 1)
  193.   print("Please enter a valid filepath:")
  194.   local path = read()
  195.   if string.find(path, "[^%w%-_/]+") or string.find(path, "//") then print("Error: path contains invalid characters") sleep(3) break end
  196.   if string.sub(path, 1, 1) ~= "/" then path = "/"..path end
  197.   if string.sub(path, path:len()) ~= "/" then path = path.."/" end
  198.   local pathParts = {}
  199.   while true do
  200.    local part, subPos = string.match(path, "/(.-)()/")
  201.    if not part then break end
  202.    table.insert(pathParts, part)
  203.    path = string.sub(path, subPos)
  204.   end
  205.   local constructedPath = ""
  206.   if #pathParts < 1 then print("Error: No file specified") sleep(3) end
  207.   for i,pathPart in ipairs(pathParts) do
  208.    if pathPart == "" then
  209.      print("Error: Missing directory in path")
  210.      sleep(3)
  211.      break
  212.     end
  213.     constructedPath = constructedPath .. "/" .. pathPart
  214.     if (not fs.exists(constructedPath)) and (i<#pathParts) then fs.makeDir(constructedPath)
  215.     elseif fs.exists(constructedPath) and (not fs.isDir(constructedPath)) then print("Error: directory\n", constructedPath, "\nis already a file.") sleep(3) break
  216.     elseif fs.exists(constructedPath) and i==#pathParts then print("Error: file\n", constructedPath, "\nalready exists.") sleep(3) break
  217.     else
  218.      print("Path: "..constructedPath)
  219.      local file = fs.open(constructedPath, "w")
  220.      if not file then print("An unknown error occured while opening the file.") sleep(3) break end
  221.      file.write(table.concat(lines, "\n"))
  222.      file.close()
  223.      saved = true
  224.      term.clear()
  225.      term.setCursorPos(1, 1)
  226.      print("Successfully saved code to:")
  227.      print(constructedPath)
  228.      sleep(3)
  229.      break
  230.     end
  231.   end
  232.  end
  233. end
  234. end
  235.  
  236. local function main()
  237. local html
  238. repeat
  239.  local url = makeURL(getInfo("ID#"), getInfo("page"))
  240.  html = getPage(url)
  241.  if not html then print("Too many failed attemps, try again later.") return false end
  242.  local valid = not hasError(html)
  243.  if not valid then print("An error occured. Your ID may be invalid.") end
  244. until valid
  245. local codes = extractCode(html)
  246. local codes = unescape(codes)
  247. if #codes == 0 then print("There is no code on that page") return true end
  248. print("Press any key to view collected code.")
  249. while true do local e,p = os.pullEvent("key") if p~=keys.escape then break end end
  250. if displayCodes(codes) then
  251.  term.clear()
  252.  term.setCursorPos(1, 1)
  253.  print("There is no code left to display")
  254.  print("Press any key to exit")
  255.  while true do local e,p = os.pullEvent("key") if p~=keys.escape then break end end sleep(0)
  256. end
  257. term.clear()
  258. term.setCursorPos(1, 1)
  259. return true
  260. end
  261.  
  262. main()
Advertisement
Add Comment
Please, Sign In to add comment