PSanf2

Lua Pastebin in OOP for ComputerCraft

May 16th, 2013
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 9.86 KB | None | 0 0
  1. --[[ This is a Lua object to handle interacting with the Pastebin API via HTTP.
  2.    
  3.     To use this in a program do the following (assuming this file is in the CraftOS root directory)
  4.         class = assert(loadfile("pastebin_obj"))
  5.         class()
  6.         Object = Pastebin:new()
  7.    
  8.     Member functions can now be called by doing Object:function(arg1,arg2,...)
  9.     Member variables can be set and accessed with Object.member_variable
  10.    
  11.     See http://www.computercraft.info/forums2/index.php?/topic/8393-oop-in-lua/ for more info on the OOP practices
  12.     See http://www.computercraft.info/forums2/index.php?/topic/10450-handling-errors-creating-controlled-errors-creating-a-bsod/
  13.         for information on how to handle errors.
  14.        
  15.     WHAT THIS THING CAN DO
  16.         Gets a user API key from Pastebin.com so the user can be logged in
  17.         allows you to create pastes (anonymously, and under a username, some arguments require the user to be logged in)
  18.         allows you to get a paste from Pastebin.com as a fs.open() handle
  19.         allows you to get a raw XML list of a users posts off Pastebin.com as a fs.open() handle (must be logged in)
  20.         allows you to get a list of a users posts in table form (must be logged in)
  21.         allows you to delete a paste (must be logged in)
  22. ]]
  23.  
  24. Pastebin = {}
  25. Pastebin.__index = Pastebin
  26.  
  27. -- Member variables being declared
  28.  
  29. Pastebin.api_dev_key = ""
  30. Pastebin.api_user_key = ""
  31.  
  32. -- Member functions
  33.  
  34. -- Constructor
  35. function Pastebin.new(self, dev_key)
  36.     if not http then
  37.         error("Error constructing Pastebin object. Pastebin requires http API. Set enableAPI_http to 1 in mod_ComputerCraft.cfg")
  38.     end
  39.     local PastebinObject = {}
  40.     setmetatable(PastebinObject, Pastebin)
  41.     self.api_dev_key = dev_key
  42.     return PastebinObject
  43. end
  44.  
  45. -- This attempts to get an API key for the user and returns true on success, false on failure.
  46. function Pastebin.login(self, user_name, user_password)
  47.     local response = http.post(
  48.         "http://pastebin.com/api/api_login.php",
  49.         "api_dev_key="..textutils.urlEncode(self.api_dev_key).."&"..
  50.         "api_user_name="..textutils.urlEncode(user_name).."&"..
  51.         "api_user_password="..textutils.urlEncode(user_password)
  52.     )
  53.     if response then
  54.         local sResponse = response.readAll()
  55.         response.close()
  56.         self.api_user_key = string.match(sResponse,"[^/]+$")
  57.         return true
  58.     else
  59.         return false
  60.     end
  61. end
  62.  
  63. -- gets a raw paste off Pastebin, and returns it.
  64. -- Returns a http handle that uses handle.close(), handle.readLine() and handle.readAll() to work with.
  65. -- be sure to close the handle when you're done!
  66. function Pastebin.get_raw(self, sCode)
  67.     local response = http.get("http://pastebin.com/raw.php?i="..textutils.urlEncode(sCode))
  68.     if response then
  69.         -- the response should be saved in a member variable, and a bool returned
  70.         return response
  71.     else
  72.         error("Bad response from Pastebin.com. Unable to get data.")
  73.     end
  74. end
  75.  
  76. -- same as put(), but paste_code is replaced by a file path.
  77. function Pastebin.put_file(...)
  78.    
  79.     local args = { ... }
  80.     local self = args[1]
  81.     local sPath = args[2]
  82.     local paste_name = args[3] or ""
  83.     local paste_format = args[4] or "text"
  84.     local paste_private = args[5] or "0"
  85.     local paste_expire_date = args[6] or "N"
  86.    
  87.     if #args < 2 or #args > 6 then
  88.         error("Invalid number of arguments provided to Pastebin.put()")
  89.     end
  90.  
  91.     if not fs.exists( sPath ) or fs.isDir( sPath ) then
  92.         error( "No such file" )
  93.     end
  94.    
  95.     -- Read in the file
  96.     local sName = fs.getName( sPath )
  97.     local file = fs.open( sPath, "r" )
  98.     local sText = file.readAll()
  99.     file.close()
  100.    
  101.     return self:put(sText,paste_name,paste_format,paste_private,paste_expire_date)
  102.    
  103. end
  104.  
  105. -- used to put stuff on pastebin
  106. --[[ argument format is Obj.put(paste_code, paste_name, paste_format, paste_private, paste_expire)
  107.     paste_code is the text of the paste (required)
  108.     paste_name is the name of the paste (optional, use "" to leave blank)
  109.     paste_format is the syntax highlighting, which is "text" by default (see Pastebin.com API documentation for other options)
  110.     paste_private is the privacy code, which is "0" by default (0=public, 1=unlisted, 2=private, if using 2 then you must be logged in before calling this function)
  111.     paste_expire is the expire for the paste (see Pastebin.com API documentation for other options)
  112.     http://pastebin.com/api
  113.     returns the code of the created paste
  114. ]]
  115.  
  116. function Pastebin.put(...)
  117.     local args = { ... }
  118.     local self = args[1]
  119.     local paste_code = args[2]
  120.     local paste_name = args[3] or ""
  121.     local paste_format = args[4] or "text"
  122.     local paste_private = args[5] or "0"
  123.     local paste_expire_date = args[6] or "N"
  124.    
  125.     if #args < 2 or #args > 6 then
  126.         error("Invalid number of arguments provided to Pastebin.put()")
  127.     end
  128.    
  129.     if paste_code == "" then
  130.         error("No paste_code provided to Pastebin.put method.")
  131.     end
  132.    
  133.     local url = "http://pastebin.com/api/api_post.php"
  134.    
  135.     local params = "api_dev_key="..textutils.urlEncode(self.api_dev_key).."&"..
  136.                     "api_option=paste&"..
  137.                     "api_paste_code="..textutils.urlEncode(paste_code)
  138.    
  139.     if self.api_user_key ~= "" then
  140.         params = params.."&api_user_key="..textutils.urlEncode(self.api_user_key)
  141.     end
  142.    
  143.     if paste_name ~= "" then
  144.         params = params.."&api_paste_name="..textutils.urlEncode(paste_name)
  145.     end
  146.    
  147.     params = params.."&api_paste_format="..textutils.urlEncode(paste_format)
  148.    
  149.     if paste_private == "0" then
  150.         -- do nothing
  151.     elseif paste_private == "1" then
  152.         params = params.."&api_paste_private="..textutils.urlEncode(paste_private)
  153.     elseif paste_private == "2" then
  154.         if self.api_user_key ~= "" then
  155.             params = params.."&api_paste_private="..textutils.urlEncode(paste_private)
  156.         else
  157.             error("User must be logged in before they can create a private paste.")
  158.         end
  159.     else
  160.         error("Invalid value provided to Pastebin.put(). paste_private can be the string 0, 1, or 2.")
  161.     end
  162.    
  163.     if paste_expire_date ~= "N" and paste_expire_date ~= "10M" and paste_expire_date ~= "1H" and paste_expire_date ~= "1D" and paste_expire_date ~= "1W" and paste_expire_date ~= "2W" and paste_expire_date ~= "1M" then
  164.         error("Invalid argument provided to Pastebin.put(). paste_expire date can be N, 10M, 1H, 1D, 1W, 2W, or 1M.")
  165.     else
  166.         params = params.."&api_paste_expire="..textutils.urlEncode(paste_expire_date)
  167.     end
  168.    
  169.     local response = http.post(url,params)
  170.     if response then
  171.         local sResponse = response.readAll()
  172.         response.close()
  173.         return string.match(sResponse,"[^/]+$")
  174.     else
  175.         error("Bad response from Pastebin. Unable to put data on server.")
  176.     end
  177.    
  178. end
  179.  
  180. -- fetches and returns the list of posts for the logged in user. Returns a http handle that uses handle.close(), handle.readLine() and handle.readAll() to work with.
  181. -- be sure to close the handle when you're done!
  182. function Pastebin.list_raw(self,results_limit)
  183.     if self.api_user_key == "" then
  184.         error("User must be logged in before attempting to retrieve list of pastes.")
  185.     end
  186.    
  187.     local sLimit = results_limit or "50"
  188.     if sLimit ~= "50" then
  189.         if tonumber(sLimit) < 1 or tonumber(sLimit) > 1000 then
  190.             error("Invalid argument provided to Pastebin.list(). results_limit must be a string integer between 1 and 1000.")
  191.         end
  192.     end
  193.    
  194.     local params = "api_dev_key="..textutils.urlEncode(self.api_dev_key).."&api_user_key="..textutils.urlEncode(self.api_user_key).."&api_option=list&api_results_limit="..textutils.urlEncode(sLimit)
  195.    
  196.     local response = http.post("http://pastebin.com/api/api_post.php",params)
  197.     if response then
  198.         -- the response should be saved in a member variable, and a bool returned.
  199.         return response
  200.     else
  201.         error("Bad response from Pastebin. Unable to retirieve list.")
  202.     end
  203. end
  204.  
  205. --gets a list of a users posts, and returns it in a 2-dimensional table.
  206. function Pastebin.list_table(self, results_limit)
  207.     local tResult = {}
  208.     local raw_list = self:list_raw(results_limit)
  209.     local index = 0
  210.     local sLine = raw_list.readLine()
  211.     while sLine do
  212.         tResult[index] = {}
  213.         tResult[index]["paste_key"] = string.sub(raw_list.readLine(),12,-13)
  214.         tResult[index]["paste_date"] = string.sub(raw_list.readLine(),13,-14)
  215.         tResult[index]["paste_title"] = string.sub(raw_list.readLine(),14,-15)
  216.         tResult[index]["paste_size"] = string.sub(raw_list.readLine(),13,-14)
  217.         tResult[index]["paste_expire_date"] = string.sub(raw_list.readLine(),20,-21)
  218.         tResult[index]["paste_private"] = string.sub(raw_list.readLine(),16,-17)
  219.         tResult[index]["paste_format_long"] = string.sub(raw_list.readLine(),20,-21)
  220.         tResult[index]["paste_format_short"] = string.sub(raw_list.readLine(),21,-22)
  221.         tResult[index]["paste_url"] = string.sub(raw_list.readLine(),12,-13)
  222.         tResult[index]["paste_hits"] = string.sub(raw_list.readLine(),13,-14)
  223.         sLine = raw_list.readLine()
  224.         sLine = raw_list.readLine()
  225.         index = index + 1
  226.     end
  227.     raw_list.close()
  228.     return tResult
  229. end
  230.  
  231. -- deletes a paste off Pastebin.com (must be logged in)
  232. function Pastebin.delete(self,code)
  233.  
  234.     if self.api_user_key == "" then
  235.         print("User must be logged in before attempting to delete a paste.")
  236.     end
  237.    
  238.     local url = "http://pastebin.com/api/api_post.php"
  239.     local params =  "api_dev_key="..textutils.urlEncode(self.api_dev_key)..
  240.                     "&api_user_key="..textutils.urlEncode(self.api_user_key)..
  241.                     "&api_paste_key="..textutils.urlEncode(code)..
  242.                     "&api_option=delete"
  243.    
  244.     local response = http.post(url,params)
  245.     if response then
  246.         local sResponse = response.readAll()
  247.         response.close()
  248.         if sResponse == "Paste Removed" then
  249.             return true
  250.         else
  251.             error("Unable to remove paste. Pastebin says \""..sResponse.."\"")
  252.         end
  253.     else
  254.         error("Bad resposne from Pastebin. Unable to delete paste")
  255.     end
  256.  
  257. end
  258.  
  259. -- allows you to download a paste into a file.
  260. function Pastebin.get_file(self,sCode,sPath)
  261.     if fs.exists(sPath) then
  262.         error("File already exists")
  263.     end
  264.     local response = self:get_raw(sCode)
  265.     if response then
  266.         local sResponse = response.readAll()
  267.         response.close()
  268.         local file = fs.open(sPath,"w")
  269.         file.write(sResponse)
  270.         file.close()
  271.         return true
  272.     else
  273.         error("Failed to paste "..sPath)
  274.     end
  275. end
Advertisement
Add Comment
Please, Sign In to add comment