forked from idobata/idobata-hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.rb
89 lines (63 loc) · 1.94 KB
/
app.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
require 'idobata/hook'
require 'net/http'
require 'action_dispatch/http/headers'
require 'action_dispatch/http/request'
require 'sinatra/base'
require 'sinatra/multi_route'
require 'sprockets'
raise 'Missing environment variable: `IDOBATA_HOOK_URL` is required.' unless ENV['IDOBATA_HOOK_URL']
module Idobata::Hook
configure do |config|
config.image_root = '/assets'
config.image_host = ENV['IDOBATA_HOOK_HOST']
end
class Application < Sinatra::Application
register Sinatra::MultiRoute
set :idobata_hook_url, ENV['IDOBATA_HOOK_URL']
set :sprockets, Sprockets::Environment.new
configure do
sprockets.append_path Idobata::Hook.root.join('hooks')
end
get '/' do
'hi from Idobata::Hooks.'
end
route :get, :post, '/:identifier' do
hook = Idobata::Hook.find(params[:identifier])
raw_body = env['rack.input'].read
headers = ActionDispatch::Http::Headers.from_hash(env)
payload = hook.new(raw_body, headers, params).process_payload
post_to_idobata payload
'OK'
end
route :head, '/:identifier' do
Idobata::Hook.find(params[:identifier])
end
error Idobata::Hook::SkipProcessing do |e|
status 200
e.message
end
error Idobata::Hook::BadRequest do |e|
status 422
e.message
end
private
def post_to_idobata(payload)
url = URI(settings.idobata_hook_url)
post = Net::HTTP::Post.new(url)
post.set_form generate_form(payload), 'multipart/form-data'
Net::HTTP.start(url.hostname, url.port, use_ssl: url.scheme == 'https') do |http|
http.request post
end
end
def generate_form(payload)
images = Array(payload[:images]).map {|image|
['image[]', image.tempfile, filename: image.filename, content_type: image.type]
}
[
['source', payload[:source].to_s],
['format', payload[:format].to_s],
*images
]
end
end
end