Alkerss

Main

May 6th, 2014
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 13.38 KB | None | 0 0
  1. local tArgs, gUser, gRepo, gPath, gBranch = {...}, nil, nil, "", "master"
  2.  
  3. local usage = [[
  4.  github [path] [remote path] [branch]
  5.  user is hardcoded to "Akuukis"
  6.  repo is hardcoded to "TurtleColorWars"
  7.  Remote path defaults to the root of the repo.
  8.  Path defaults to the download folder.
  9.  Branch defaults to master.
  10.  If you want to leave an option empty use a dot.
  11.  Example: github johnsmith hello-world . foo
  12.  Everything inside the directory foo will be
  13.  downloaded to downloads/hello-world/.
  14.   ]]
  15. local blackList = [[
  16. @blacklistedfile
  17. ]]
  18.  
  19. local title = "Github Repo Downloader"
  20. local fileList = {dirs={},files={}}
  21. local x , y = term.getSize()
  22.  
  23. -- GUI
  24. function printTitle()
  25.     local line = 2
  26.     term.setCursorPos(1,line)
  27.     for i = 2, x, 1 do write("-") end
  28.     term.setCursorPos((x-title:len())/2,line+1)
  29.     print(title)
  30.     for i = 2, x, 1 do write("-") end
  31. end
  32.  
  33. function writeCenter( str )
  34.     term.clear()
  35.     printTitle()
  36.     term.setCursorPos((x-str:len())/2-1,y/2-1)
  37.     for i = -1, str:len(), 1 do write("-") end
  38.     term.setCursorPos((x-str:len())/2-1,y/2)
  39.     print("|"..str.."|")
  40.     term.setCursorPos((x-str:len())/2-1,y/2+1)
  41.     for i = -1, str:len(), 1 do write("-") end
  42. end
  43.  
  44. function printUsage()
  45.     local str = "Press space key to continue"
  46.     term.clear()
  47.     printTitle()
  48.     term.setCursorPos(1,y/2-4)
  49.     print(usage)
  50.     term.setCursorPos((x-str:len())/2,y/2+7)
  51.     print(str)
  52.     while true do
  53.         local event, param1 = os.pullEvent("key")
  54.         if param1 == 57 then
  55.             sleep(0)
  56.             break
  57.         end
  58.     end
  59.     term.clear()
  60.     term.setCursorPos(1,1)
  61. end
  62.  
  63. -- Download File
  64. function downloadFile( path, url, name )
  65.     writeCenter("Downloading File: "..name)
  66.     dirPath = path:gmatch('([%w%_%.% %-%+%,%;%:%*%#%=%/]+)/'..name..'$')()
  67.     if dirPath ~= nil and not fs.isDir(dirPath) then fs.makeDir(dirPath) end
  68.     local content = http.get(url)
  69.     local file = fs.open(path,"w")
  70.     file.write(content.readAll())
  71.     file.close()
  72. end
  73.  
  74. -- Get Directory Contents
  75. function getGithubContents( path )
  76.     local pType, pPath, pName, checkPath = {}, {}, {}, {}
  77.     local response = http.get("https://api.github.com/repos/"..gUser.."/"..gRepo.."/contents/"..path.."/?ref="..gBranch)
  78.     if response then
  79.         response = response.readAll()
  80.         if response ~= nil then
  81.             for str in response:gmatch('"type":"(%w+)"') do table.insert(pType, str) end
  82.             for str in response:gmatch('"path":"([^\"]+)"') do table.insert(pPath, str) end
  83.             for str in response:gmatch('"name":"([^\"]+)"') do table.insert(pName, str) end
  84.         end
  85.     else
  86.         writeCenter( "Error: Can't resolve URL" )
  87.         sleep(2)
  88.         term.clear()
  89.         term.setCursorPos(1,1)
  90.         error()
  91.     end
  92.     return pType, pPath, pName
  93. end
  94.  
  95. -- Blacklist Function
  96. function isBlackListed( path )
  97.     if blackList:gmatch("@"..path)() ~= nil then
  98.         return true
  99.     end
  100. end
  101.  
  102. -- Download Manager
  103. function downloadManager( path )
  104.     local fType, fPath, fName = getGithubContents( path )
  105.     for i,data in pairs(fType) do
  106.         if data == "file" then
  107.             checkPath = http.get("https://raw.github.com/"..gUser.."/"..gRepo.."/"..gBranch.."/"..fPath[i])
  108.             if checkPath == nil then
  109.  
  110.                 fPath[i] = fPath[i].."/"..fName[i]
  111.             end
  112.             local path = "Downloads/GitHub/"..gRepo.."/"..fPath[i]
  113.             if gPath ~= "" then path = gPath.."/"..gRepo.."/"..fPath[i] end
  114.             if not fileList.files[path] and not isBlackListed(fPath[i]) then
  115.                 fileList.files[path] = {"https://raw.github.com/"..gUser.."/"..gRepo.."/"..gBranch.."/"..fPath[i],fName[i]}
  116.             end
  117.         end
  118.     end
  119.     for i, data in pairs(fType) do
  120.         if data == "dir" then
  121.             local path = "Downloads/GitHub/"..gRepo.."/"..fPath[i]
  122.             if gPath ~= "" then path = gPath.."/"..gRepo.."/"..fPath[i] end
  123.             if not fileList.dirs[path] then
  124.                 writeCenter("Listing directory: "..fName[i])
  125.                 fileList.dirs[path] = {"https://raw.github.com/"..gUser.."/"..gRepo.."/"..gBranch.."/"..fPath[i],fName[i]}
  126.                 downloadManager( fPath[i] )
  127.             end
  128.         end
  129.     end
  130. end
  131.  
  132. -- Main Function
  133. function main( path )
  134.     writeCenter("Connecting to Github")
  135.     downloadManager(path)
  136.     for i, data in pairs(fileList.files) do
  137.         downloadFile( i, data[1], data[2] )
  138.     end
  139.     writeCenter("Download completed")
  140.     sleep(2,5)
  141.     term.clear()
  142.     term.setCursorPos(1,1)
  143. end
  144.  
  145. -- Parse User Input
  146. function parseInput( user, repo , dldir, path, branch )
  147.     if path == nil then path = "" end
  148.     if branch ~= nil then gBranch = branch end
  149.     if repo == nil then printUsage()
  150.     else
  151.         gUser = user
  152.         gRepo = repo
  153.         if dldir ~= nil then gPath = dldir end
  154.         main( path )
  155.     end
  156. end
  157.  
  158. function StartDownloaderGitHub()
  159. if not http then
  160.     writeCenter("You need to enable the HTTP API!")
  161.     sleep(3)
  162.     term.clear()
  163.     term.setCursorPos(1,1)
  164. else
  165.     for i=1, 5, 1 do
  166.         if tArgs[i] == "." then tArgs[i] = nil end
  167.     end
  168.     parseInput( "Akuukis", "TurtleColorWars", tArgs[1], tArgs[2], tArgs[3])
  169.  shell.run("Downloads/GitHub/TurtleColorWars/Main", "Downloads/GitHub/TurtleColorWars/")
  170. end
  171. end
  172.  
  173. -------------------------------------------------------------------------------------------------------------------------------
  174.  
  175. local function get(paste)
  176.     --write( "Connecting to pastebin.com... " )
  177.     write("connecting...")
  178.     local cpx,cpy = term.getCursorPos()
  179.     term.setCursorPos(cpx-string.len("Connecting..."), cpy)
  180.     local response = http.get(
  181.         "http://pastebin.com/raw.php?i="..textutils.urlEncode( paste )
  182.     )
  183.            
  184.     if response then
  185.         write( "connected, " )
  186.         local cpx,cpy = term.getCursorPos()
  187.         term.setCursorPos(cpx-string.len("connected, "), cpy)
  188.         local sResponse = response.readAll()
  189.         response.close()
  190.         return sResponse
  191.     else
  192.         write( "Failed connection." )
  193.         sleep(2)
  194.     end
  195. end
  196.  
  197. local function PastebinGet( ... )
  198.     local tArgs = { ... }
  199.     if #tArgs < 2 then return   end
  200.     if not http then
  201.         print( "Pastebin requires http API" )
  202.         print( "Set enableAPI_http to true in ComputerCraft.cfg" )
  203.         return
  204.     end
  205.     -- Download a file from pastebin.com
  206.     -- Determine file to download
  207.     local sCode = tArgs[1]
  208.     local sFile = tArgs[2]
  209.     local sPath = shell.resolve( sFile )
  210.     if fs.exists( sPath ) then
  211.             --write( "File already exists" )
  212.             --return
  213.     end
  214.     -- GET the contents from pastebin
  215.     local res = get(sCode)
  216.     if res then        
  217.             local file = fs.open( sPath, "w" )
  218.             file.write( res )
  219.             file.close()
  220.             --print( "Downloaded as "..sFile )
  221.             write("fetched, ")
  222.     end
  223.     return
  224. end
  225.  
  226. -------------------------------------------------------------------------------------------------------------------------------
  227.  
  228. function StartDownloaderPastebin( ... )
  229.     for i=1,select('#',...) do
  230.         local tmp = select(i,...)
  231.         if tmp == "start" then shell.run("delete Downloads/Pastebin" .. nick) end
  232.         for j=1,12 do
  233.             if tmp == "start" or tmp == "all" or tmp == ApiList[j] then
  234.                 write(ApiList[j] .. ": ") -- 39-8, 31-9, 22-8, 14-9, 5
  235.                 PastebinGet( PastebinList[nick][j], "Downloads/Pastebin/" .. nick .. "/" .. ApiList[j] )
  236.                 local Function, Error = loadfile("Downloads/Pastebin/" .. nick .. "/" .. ApiList[j] )
  237.                 if Function == nil then
  238.                     write("error at loading: \n" .. Error .. "\n")
  239.                     sleep(5)
  240.                 else
  241.                     write("loaded, ")
  242.                     local Ok, Error = pcall(Function)
  243.                     if Ok == false then
  244.                         write("Error at executing: \n" .. Error .. "\n")
  245.                         sleep(5)
  246.                     else
  247.                         write("executed!\n")
  248.                     end
  249.                 end
  250.             end
  251.         end
  252.     end
  253. end
  254.  
  255. nick = ""
  256. PastebinList = {}
  257. ApiList = {
  258. "Gui","Rui","Hud","Logger","Stats",
  259. "Comm","Utils","Nav","Jobs","Resm",
  260. "Logic","Init"
  261. }
  262. --[[ebinList["Nam"] = {
  263. "Gui.....","Rui.....","Hud.....","Logger..","Stats...",
  264. "Comm....","Utils...","Nav.....","Jobs....","Resm....",
  265. "Logic...","Init....",}
  266. --]]
  267. PastebinList["Aku"] = {
  268. "EiNQu1tr","Vf4iEtwA","y9b6Vm0P","Yxhz7Gju","VeVb4816",
  269. "5kqCkMdY","VtBzt7BU","3AKpWFvr","AigXBa8F","TsMtkpDU",
  270. "FMsxxBSe","YqXAK4gf",}
  271. PastebinList["Alk"] = {
  272. "4j3xkFqi","Nhde3VzW","zeJ6qg7L","yJ2TDrAC","W2x8HN2Z",
  273. "de84SYF8","cf9SZvTb","HNAWHYUC","g75ryBk7","QpNgZqDk",
  274. "URjcXVqp","Z2wLpHNw",}
  275. PastebinList["Mox"] = {
  276. "LCzvnrgm","yaz8QfNQ","EaH1rTcN","0jqNejLc","brF1SQX7",
  277. "bpyKQrn4","Y9RjARM5","TbXnTHVs","sKRJw3YD","--------",
  278. "jQizTuJd","--------",}
  279. PastebinList["Hek"] = {
  280. "smpuk04E","LHNWPcXr","5frXRLYb","vfykx5yU","vkqKAC75",
  281. "HYzrtMtW","m684sRqW","4TLXbEAr","ED6JUvXF","--------",
  282. "BVivED7g","--------",}
  283. PastebinList["Mar"] = {
  284. "YwEvnNuv","VqYY94pE","a2pZzJhK","AyQ4RJRy","hTbMg1BG",
  285. "VymxZieZ","gdL40bFx","0rFQyhKi","rz2BBebP","0xMDUvL0",
  286. "3KZ9UcCK","D7mpfTqH",}
  287.  
  288.  
  289. function Start()
  290.     term.clear()
  291.     print("Turtle Color Wars Downloader v1.0")
  292.     print("Choose the source (press the key):")
  293.     print()
  294.     print("1 - GitHub")
  295.     print("2 - Pastebin of Akuukis")
  296.     print("3 - Pastebin of Alkerss")
  297.     print("4 - Pastebin of moxxcrue")
  298.     print("5 - Pastebin of Hekaya")
  299.     print("6 - Pastebin of marchrime")
  300.     event, param1 = os.pullEvent("char")
  301.     if event == "char" and param1 == "1" then nick = "Git"; StartDownloaderGitHub("start") end
  302.     if event == "char" and param1 == "2" then nick = "Aku"; StartDownloaderPastebin("start") end
  303.     if event == "char" and param1 == "3" then nick = "Alk"; StartDownloaderPastebin("start") end
  304.     if event == "char" and param1 == "4" then nick = "Mox"; StartDownloaderPastebin("start") end
  305.     if event == "char" and param1 == "5" then nick = "Hek"; StartDownloaderPastebin("start") end
  306.     if event == "char" and param1 == "6" then nick = "Mar"; StartDownloadetPastebin("start") end
  307. end
  308.  
  309. function UpdateAPI( nick, ... )
  310.     if nick == "Git" then StartDownloaderGitHub( ... )
  311.     else StartDownloaderPastebin( nick, ... )
  312.     end
  313. end
  314.  
  315. -------------------------------------------------------------------------------------------------------------------------------
  316.  
  317. --[[ coroutine.resume Returns:
  318.     1. boolean Ok: true if its ok, false if coroutine error()
  319.     2. string Filter/ErrorMsg/: if Ok=true Filter is event name (may be nil=no filter), if Ok=false then ErrorMsg is error message.
  320.     [3. function Call: if coroutine wants to start another coroutine it will return _Call
  321.      4. boolean noYield: true if coroutine wants to continue without waiting to other coroutines
  322.      [5. table Args: Args to be passed to Call ] ]
  323. --]]
  324.  
  325. -- Warning: functions like: read(), sleep() etc. empty the event stack and you will not be able to pull the event after that
  326.  
  327. local Threads = {}
  328. local tFilters = {}
  329. local Args = {}
  330. local Names = {}
  331. local eventData = {}
  332.  
  333. print("Initialized Main!")
  334. Start()
  335.  
  336. -- The First coroutine
  337. local n = 1
  338. Threads[n] = coroutine.create(Init.Start)
  339. tFilters[Threads[n]] = nil
  340. -- Run until no coroutines left (won't happen normally)
  341. while n > 0 do
  342.     --Logger.Check("inside While, n=%s\n",n)
  343.     -- Cycle through active coroutines. Repeat twice if coroutine kills or calls other coroutine (see "i = i - 1")
  344.     for i=1,n do
  345.         --Logger.Check("inside for, i=%s\n",i)
  346.         --Logger.Check("inside for, Threads[i]=%s\n",Threads[i])
  347.         -- Clean up the table of coroutines - if there's a gap, shift others up.
  348.         if Threads[i] == nil or coroutine.status( Threads[i] ) == "dead" then
  349.             for j=i,n-1 do Threads[j] = Threads[j+1] end
  350.             for j=i,n-1 do Names[j] = Names[j+1] end
  351.             n = n - 1
  352.             i = i - 1
  353.            
  354.         -- Resume one coroutine
  355.         else
  356.             --Logger.Check("inside else, Args[Threads[i]]=%s, tFilters=%s\n",Args[Threads[i]],tFilters[Threads[i]])
  357.             local Ok, Call, Target, Arguments, ArgsNew
  358.             Arguments = eventData
  359.             if Args[Threads[i]] then -- If the coroutine is a new one, call it with original arguments if it has any, otherwise call with eventData
  360.                 --Logger.Check("inside Args, %s\n",Args[Threads[i]])
  361.                 Arguments = Args[Threads[i]]
  362.                 Args[Threads[i]] = nil
  363.             end
  364.             if Arguments[1] ~= nil or tFilters[Threads[i]] == nil then -- Check for filters
  365.                 Ok, tFilters[Threads[i]], Target, ArgsNew = coroutine.resume( Threads[i], unpack(Arguments) ) -- Call a coroutine
  366.                 --Logger.Check("inside resume, Ok=%s, tFilters[Threads[i]]=%s, Target=%s, Args[Threads[i]]=%s\n",Ok, tFilters[Threads[i]], Target, Args[Threads[i]])
  367.                 if not Ok then Logger.Error("Coroutine failed! %s", tFilters[Threads[i]] ) -- Inform if coroutine failed
  368.                 elseif tFilters[Threads[i]] == "_Call" then -- prepare a new coroutine
  369.                     --Logger.Check("inside _Call")
  370.                     n = n + 1
  371.                     Threads[n] = coroutine.create(Target)
  372.                     Args[Threads[n]] = ArgsNew
  373.                     Names[n] = Utils.GenUniqString(16)
  374.                     --Logger.Check("NewThr: %s\n",Threads[n])
  375.                     i = i - 1
  376.                     os.queueEvent("dummy")
  377.                     eventData = Names[n]
  378.                 elseif tFilters[Threads[i]] == "_Stop" or tFilters[Threads[i]] == "_Kill" then
  379.                     --Logger.Check("inside _Stop/Kill")
  380.                     local TargetID = nil
  381.                     for j=1,n do if Names[j] == Target then TargetID = j end end
  382.                     if TargetID == nil then
  383.                         --Logger.Check("StopThread: No such! %s\n",Target)
  384.                     else
  385.                         Ok = coroutine.resume(Threads[TargetID], tFilters[Threads[i]])
  386.                         --Logger.Check("StopThread: %s\n",Threads[Target])
  387.                         Threads[Target] = nil
  388.                         Args[Threads[Target]] = nil
  389.                         n = n - 1
  390.                         i = i - 1
  391.                     end
  392.                     os.queueEvent("dummy")
  393.                 elseif tFilters[Threads[i]] == "_UpdateAPI" then -- updates API. Other APIs cannot call functions of Main directly,
  394.                     Target = Target or ArgsNew
  395.                     UpdateAPI(unpack(Target))
  396.                     i = i - 1
  397.                     os.queueEvent("dummy")                 
  398.                 end
  399.             end -- if Args[Threads[i]] or tFilters[Threads[i]] == nil or tFilters[Threads[i]] == Arguments[1] then
  400.         end -- if Threads[i] == nil or coroutine.status( Threads[i] ) == "dead" then
  401.     end -- for i=1,n do
  402.     --Logger.Check("eventData:\n")
  403.     eventData = { os.pullEventRaw() } -- after a cycle call pullEventRaw ( = coroutine.yield )
  404. end -- while n > 0 do
  405. Logger.Check("Out-of-coroutines!\n")
Advertisement
Add Comment
Please, Sign In to add comment