-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathpremailer_app.rb
223 lines (177 loc) · 5.64 KB
/
premailer_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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# frozen_string_literal: true
$LOAD_PATH << File.join(File.dirname(__FILE__), 'lib')
require 'dotenv/load'
require 'sinatra'
require 'nokogiri'
require 'builder'
require 'json'
require 'digest'
require 'htmlentities'
require 'premailer'
require 'aws-sdk-s3'
require 'rack/throttle'
require 'redis'
use Rack::Throttle::Minute, cache: Redis.new(url: ENV["REDIS_URL"]), key_prefix: :throttle
set :show_exceptions, false
@url = ''
AWS_BUCKET = ENV['AWS_BUCKET']
error do
e = env['sinatra.error']
backtrace = "Application error\n#{e}\n#{e.backtrace.join("\n")}"
warn backtrace
warn e.inspect
status 500
'Sorry there was an error'
end
not_found do
@message = 'This is nowhere to be found'
erb :error
end
get '/' do
@initial_doc = 'https://dialect.ca/premailer-tests/base.html'
if !params[:bookmarklet].nil?
do_request
erb :results
else
erb :index
end
end
post '/' do
res = do_request
if res[:status] == 201
@analytics_page = '/success'
erb :results
else
@message = @results[:message]
@analytics_page = '/error/processing'
erb :error
end
end
get '/api' do
erb :api
end
post '/api/0.1/documents' do
content_type 'application/json', charset: 'utf-8'
opts = {}
source = nil
if params[:html] && !params[:html].empty?
opts[:with_html_string] = true
source = params[:html]
elsif params[:url] && !params[:url].empty?
source = params[:url]
else
return 400, [{ message: 'No input file specified', version: '0.1', status: 400 }.to_json]
end
opts[:adapter] = :nokogiri
opts[:base_url] = params[:base_url].strip if params[:base_url]
opts[:line_length] = params[:line_length].strip.to_i if params[:line_length]
opts[:link_query_string] = params[:link_query_string].strip if params[:link_query_string]
opts[:preserve_styles] = params[:preserve_styles] && (params[:preserve_styles] == 'false') ? false : true
opts[:remove_ids] = params[:remove_ids] && (params[:remove_ids] == 'true') ? true : false
opts[:remove_classes] = params[:remove_classes] && (params[:remove_classes] == 'true') ? true : false
opts[:remove_comments] = params[:remove_comments] && (params[:remove_comments] == 'true') ? true : false
result = process_url(source, opts.merge(io_exceptions: false))
output = {
version: '0.1',
status: result[:status].to_i,
message: result[:message],
options: opts,
documents: {
html: result[:output][:html_file],
txt: result[:output][:txt_file]
}
}
if output[:status] == 500
status 500
else
response.header['Location'] = result[:output][:html_file]
expires 7200, :private
status 201
end
body(output.to_json)
end
get '/feedback' do
erb :feedback
end
def do_request
@source_description = ''
@html = ''
@opts = {}
if (params[:content_source] == 'html') && !params[:html].empty?
@opts[:with_html_string] = true
html = params[:html]
@source_description = 'your HTML content'
elsif !params[:url].empty?
html = params[:url].to_s.strip
@source_description = html
else
@message = 'No input file specified'
@analytics_page = '/error/no_input'
erb :error
end
@opts[:link_query_string] = params[:querystring].strip if params[:querystring]
@opts[:preserve_styles] = true if params[:preserve_styles] && (params[:preserve_styles] == 'yes')
@opts[:remove_ids] = true if params[:remove_ids] && (params[:remove_ids] == 'yes')
@opts[:remove_classes] = true if params[:remove_classes] && (params[:remove_classes] == 'yes')
@opts[:remove_comments] = true if params[:remove_comments] && (params[:remove_comments] == 'yes')
@opts[:adapter] = :nokogiri
warn "- sending opts #{@opts.inspect}"
res = process_url(html, @opts)
@results = res
@results
end
def is_valid_api_key?(_api_key)
true
end
def process_url(url, opts = {})
@options = { warn_level: Premailer::Warnings::SAFE,
text_line_length: 65,
link_query_string: nil,
verbose: true,
adapter: :nokogiri }.merge(opts)
return_status = 201
message = 'Created'
warnings = {}
output = {}
begin
warn "- with opts #{@options.inspect}"
output_base_url = 'http://' + @env['HTTP_HOST'] + '/_out/'
premailer = Premailer.new(url, @options)
outfile = generate_request_id(url)
out_plaintext = premailer.to_plain_text
out_html = premailer.to_inline_css
Aws.config.update(
region: ENV['AWS_REGION'],
credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'])
)
s3 = Aws::S3::Resource.new(region: ENV['AWS_REGION'])
text_obj = s3.bucket(AWS_BUCKET).object("#{outfile}.txt")
text_obj.put(body: out_plaintext, content_type: 'text/plain', acl: 'authenticated-read', expires: Time.now + 7200)
html_obj = s3.bucket(AWS_BUCKET).object("#{outfile}.html")
html_obj.put(body: out_html, content_type: 'text/html', acl: 'authenticated-read', expires: Time.now + 7200)
warnings = premailer.warnings
output = {
html_file: html_obj.presigned_url(:get, expires_in: 7200),
txt_file: text_obj.presigned_url(:get, expires_in: 7200),
html: out_html,
txt: out_plaintext
}
warn "Saved HTML output to #{output[:html_file]}"
rescue OpenURI::HTTPError => e
return_status = 500
message = 'Source file not found'
rescue Exception => e
raise e
return_status = 500
message = e.message
end
{ status: return_status,
message: message,
url: url,
options: @options,
warnings: warnings,
output: output }
end
def generate_request_id(url)
Digest::MD5.hexdigest("#{url}#{inspect}#{Time.now}#{rand}")
end