require 'micropub' module Micropub::Server::Rails class Middleware class HTTPError < StandardError attr_reader :status def initialize(env, status, body="") @env = env @status = status @body = body end end def initialize(app) @app = app end def call(env) begin @params = request(env).params @headers = {"Content-Type" => "application/x-www-form-urlencoded"} if env["PATH_INFO"] == "/micropub" micropub_call env else @app.call env end rescue HTTPError => env error_response(env.status) end end def check_token(env) token = Micropub::Token.new(auth_token(env)) raise HTTPError.new env, 401 if !token.valid? end def auth_token(env) input = env["HTTP_AUTHORIZATION"] || @params["access_token"] || "" input.split("Bearer ").last end def micropub_call(env) case env["REQUEST_METHOD"] when "GET" then syndicate_to env when "POST" then post env else raise HTTPError.new env, 405 end end def syndicate_to(env) # TODO: Remove hardcoded syndicate link [200, @headers, ["syndicate-to[]=twitter.com%2fbookis"]] end def post(env) check_token env router = Micropub::Homesteading::Router.new(@params) client = Micropub::Client.new(router.as, token: auth_token(env)) response = client.post(@params.except("access_token")) raise HTTPError.new env, response.status if !response.successful? @headers["Location"] = response.location [201, @headers, [""]] end def error_response(status) [status, {}, [""]] end def request(env) Rack::Request.new(env) end end end