local mastodon = {} local json = require("json") function url_form_encode(data) local str = "" for k, v in pairs(data) do if #str == 0 then str = k .. "=" .. v else str = str .. "&" .. k .. "=" .. v end end return str end function mastodon.create_app(api_base_url, client_name) if string.sub(api_base_url, -1) == "/" then api_base_url = string.sub(api_base_url, 1, -2) end local request_data = url_form_encode({ client_name = client_name, redirect_uris = "urn:ietf:wg:oauth:2.0:oob", scopes = "read write follow" }) local h = http.post(api_base_url .. "/api/v1/apps", request_data) if h.getResponseCode() == 200 then data = json.decode(h.readAll()) return { client_id = data["client_id"], client_secret = data["client_secret"] } else return nil, "Unexpected response code: " .. h.getResponseCode() end end local Mastodon = {} function mastodon.new(options) local self = { api_base_url = options.api_base_url, client_id = options.client_id, client_secret = options.client_secret, access_token = options.access_token, debug_requests = options.debug_requests or false } if not self.api_base_url then -- read credentials from file local h = fs.open("creds.txt", "r") self.api_base_url = h.readLine() self.client_id = h.readLine() self.client_secret = h.readLine() local last_line = h.readLine() if last_line ~= "" then self.access_token = last_line end end if string.sub(self.api_base_url, -1) == "/" then self.api_base_url = string.sub(self.api_base_url, 1, -2) end return setmetatable(self, {__index = Mastodon}) end function Mastodon:get_auth_url() return self.api_base_url .. "/oauth/authorize?scope=read%20write%20follow&response_type=code&redirect_uri=urn:ietf:wg:oauth:2.0:oob&client_id=" .. self.client_id end function Mastodon:get_access_token(auth_code) local request_data = url_form_encode({ client_id = self.client_id, client_secret = self.client_secret, grant_type = "authorization_code", code = auth_code, redirect_uri = "urn:ietf:wg:oauth:2.0:oob" }) local h = http.post(self.api_base_url .. "/oauth/token", request_data) if h.getResponseCode() == 200 then data = json.decode(h.readAll()) print(data) else return self, "Unexpected response code: " .. h.getResponseCode() end end function Mastodon:get_own_account() local headers = { ["Authorization"] = "Bearer " .. self.access_token } local h = http.get(self.api_base_url .. "/api/v1/accounts/verify_credentials", headers) if h.getResponseCode() == 200 then data = json.decode(h.readAll()) print(data["acct"]) else return nil, "Unexpected response code: " .. h.getResponseCode() end end return mastodon