dyndnsd/lib/dyndnsd/responder/rest_style.rb

73 lines
2.4 KiB
Ruby
Raw Normal View History

2020-03-06 21:33:29 +01:00
# frozen_string_literal: true
2013-04-27 14:07:14 +02:00
module Dyndnsd
module Responder
class RestStyle
2020-02-28 15:13:28 +01:00
# @param app [#call]
def initialize(app)
@app = app
end
2020-02-28 15:13:28 +01:00
# @param env [Hash{String => String}]
# @return [Array{Integer,Hash{String => String},Array{String}}]
def call(env)
@app.call(env).tap do |status_code, headers, body|
2018-02-23 12:54:43 +01:00
if headers.key?('X-DynDNS-Response')
return decorate_dyndnsd_response(status_code, headers, body)
else
return decorate_other_response(status_code, headers, body)
end
end
end
private
2020-02-28 15:13:28 +01:00
# @param status_code [Integer]
# @param headers [Hash{String => String}]
# @param body [Array{String}]
# @return [Array{Integer,Hash{String => String},Array{String}}]
def decorate_dyndnsd_response(status_code, headers, body)
case status_code
when 200
2018-02-23 12:54:43 +01:00
[200, {'Content-Type' => 'text/plain'}, [get_success_body(body[0], body[1])]]
when 422
2018-02-23 12:54:43 +01:00
error_response_map[headers['X-DynDNS-Response']]
end
end
2020-02-28 15:13:28 +01:00
# @param status_code [Integer]
# @param headers [Hash{String => String}]
# @param _body [Array{String}]
# @return [Array{Integer,Hash{String => String},Array{String}}]
2018-02-23 12:54:43 +01:00
def decorate_other_response(status_code, headers, _body)
case status_code
when 400
2018-02-23 12:54:43 +01:00
[status_code, headers, ['Bad Request']]
when 401
2018-02-23 12:54:43 +01:00
[status_code, headers, ['Unauthorized']]
end
end
2020-02-28 15:13:28 +01:00
# @param changes [Array{Symbol}]
# @param myips [Array{String}]
# @return [String]
def get_success_body(changes, myips)
changes.map { |change| change == :good ? "Changed to #{myips.join(' ')}" : "No change needed for #{myips.join(' ')}" }.join("\n")
end
2020-02-28 15:13:28 +01:00
# @return [Hash{String => Object}]
2018-02-23 12:54:43 +01:00
def error_response_map
{
# general http errors
2018-02-23 12:54:43 +01:00
'method_forbidden' => [405, {'Content-Type' => 'text/plain'}, ['Method Not Allowed']],
'not_found' => [404, {'Content-Type' => 'text/plain'}, ['Not Found']],
# specific errors
2018-02-23 12:54:43 +01:00
'hostname_missing' => [422, {'Content-Type' => 'text/plain'}, ['Hostname missing']],
'hostname_malformed' => [422, {'Content-Type' => 'text/plain'}, ['Hostname malformed']],
'host_forbidden' => [403, {'Content-Type' => 'text/plain'}, ['Forbidden']]
}
2013-04-27 14:07:14 +02:00
end
end
end
end