· 5 years ago · Feb 22, 2021, 12:52 AM
1--1/paste.lua
2--- Provides a pastebin api to interact with pastebin without using the pastebin shell command.
3--
4-- @module cc.http.pastebin
5-- @usage get a string from pastebin
6-- local pastebin = require "cc.http.pastebin"
7-- local paste = pastebin.get("V7F7BPPM")
8-- print(paste)
9--
10-- @usage put a string on pastebin
11-- local pastebin = require "cc.http.pastebin"
12-- local paste = "This is a string that will be put on pastebin!"
13-- local id = pastebin.put(paste)
14-- print(id)
15
16local function extractId(paste)
17 local patterns = {
18 "^([%a%d]+)$",
19 "^https?://pastebin.com/([%a%d]+)$",
20 "^pastebin.com/([%a%d]+)$",
21 "^https?://pastebin.com/raw/([%a%d]+)$",
22 "^pastebin.com/raw/([%a%d]+)$",
23 }
24
25 for i = 1, #patterns do
26 local code = paste:match(patterns[i])
27 if code then return code end
28 end
29
30 return nil
31end
32
33--- get retrieves the paste from pastebin
34-- @tparam string id The paste id that you want to download.
35-- @treturn string|nil The string containing the paste, or nil.
36-- @treturn nil|string The reason why it couldn't be retrieved.
37local function get(url)
38 local paste = extractId(url)
39 if not paste then
40 return nil, "invalid"
41 end
42 -- Add a cache buster so that spam protection is re-checked
43 local cacheBuster = ("%x"):format(math.random(0, 2 ^ 30))
44 local response, err = http.get(
45 "https://pastebin.com/raw/" .. textutils.urlEncode(paste) .. "?cb=" .. cacheBuster
46 )
47
48 if response then
49 -- If spam protection is activated, we get redirected to /paste with Content-Type: text/html
50 local headers = response.getResponseHeaders()
51 if not headers["Content-Type"] or not headers["Content-Type"]:find("^text/plain") then
52 return nil, "captcha"
53 end
54
55 local sResponse = response.readAll()
56 response.close()
57 return sResponse
58 else
59 return nil, err
60 end
61end
62
63--- puts a string onto pastebin
64-- @tparam string string The string that you want to put on pastebin.
65-- @tparam[opt] string name The name of the paste, defaults to "CC:T Paste".
66-- @treturn string|nil A string containing the id of the paste.
67local function put(sText, sName)
68 sName = sName or "CC:T Paste"
69 -- Upload a file to pastebin.com
70
71 -- POST the contents to pastebin
72 local key = "c0c823486cd22b8042775c0009c5ce62"
73 local response = http.post(
74 "https://pastebin.com/api/api_post.php",
75 "api_option=paste&" ..
76 "api_dev_key=" .. key .. "&" ..
77 "api_paste_format=lua&" ..
78 "api_paste_name=" .. textutils.urlEncode(sName) .. "&" ..
79 "api_paste_code=" .. textutils.urlEncode(sText)
80 )
81
82 if response then
83
84 local sResponse = response.readAll()
85 response.close()
86
87 local sCode = string.match(sResponse, "[^/]+$")
88 return sCode
89 else
90 return nil
91 end
92end
93
94return {
95 get = get,
96 put = put,
97}