2016-11-08 20:51:39 +00:00
|
|
|
# frozen_string_literal: true
|
2017-11-06 16:15:18 +00:00
|
|
|
|
2016-09-25 15:06:09 +00:00
|
|
|
# bad code that should be checked over before entering one of the
|
|
|
|
# nice files from the right side of this repo
|
2016-09-23 06:29:28 +00:00
|
|
|
class HacksController < ApplicationController
|
|
|
|
include ActionView::Helpers::TextHelper # string truncate method
|
|
|
|
|
2016-09-25 15:06:09 +00:00
|
|
|
# rate limited by rack-attack - currently 5r/s
|
2016-09-23 06:29:28 +00:00
|
|
|
def load_url_title
|
|
|
|
authorize :Hack
|
2016-09-25 15:06:09 +00:00
|
|
|
url = params[:url]
|
2016-09-23 06:29:28 +00:00
|
|
|
response, url = get_with_redirects(url)
|
|
|
|
title = get_encoded_title(response)
|
|
|
|
render json: { success: true, title: title, url: url }
|
2016-11-08 20:51:39 +00:00
|
|
|
rescue StandardError
|
2016-09-25 15:06:09 +00:00
|
|
|
render json: { success: false }
|
2016-09-23 06:29:28 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def get_with_redirects(url)
|
|
|
|
uri = URI.parse(url)
|
|
|
|
response = Net::HTTP.get_response(uri)
|
|
|
|
while response.code == '301'
|
|
|
|
uri = URI.parse(response['location'])
|
|
|
|
response = Net::HTTP.get_response(uri)
|
|
|
|
end
|
|
|
|
[response, uri.to_s]
|
|
|
|
end
|
|
|
|
|
|
|
|
def get_encoded_title(http_response)
|
2016-11-08 20:51:39 +00:00
|
|
|
# ensure there's actually an html title tag
|
|
|
|
title = http_response.body.sub(%r{.*(<title>.*</title>).*}m, '\1')
|
|
|
|
return '' unless title.starts_with?('<title>')
|
|
|
|
return '' unless title.ends_with?('</title>')
|
|
|
|
title = title.sub('<title>', '').sub(%r{</title>$}, '')
|
|
|
|
|
|
|
|
# encode and trim the title to 140 usable characters
|
2016-09-23 06:29:28 +00:00
|
|
|
charset = http_response['content-type'].sub(/.*charset=(.*);?.*/, '\1')
|
|
|
|
charset = nil if charset == 'text/html'
|
|
|
|
title = title.force_encoding(charset) if charset
|
|
|
|
truncate(title, length: 140)
|
|
|
|
end
|
|
|
|
end
|