-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.rb
48 lines (39 loc) · 1.1 KB
/
search.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
require 'json'
require 'net/http'
require 'cgi'
Encoding.default_external = Encoding::UTF_8
# TODO:
# - turn this into a class that runs itself at the bottom of the file
# - handle errors in initial fetch
# - clean up (potentially) brittle chaining e.g. res.body.match().captures[0]
query = ARGV[0]
uri = URI('https://duckduckgo.com/')
params = { q: "#{query} !" }
uri.query = URI.encode_www_form(params)
# get response from duckduckgo
res = Net::HTTP.get_response(uri)
# parse redirect url
result_url = CGI.unescape(res.body.match(/.+uddg=(.+)&rut=.+/).captures[0])
# get the title
title_resp = Net::HTTP.get_response(URI(result_url))
title = if title_resp.is_a?(Net::HTTPSuccess)
# YUCKKKKKK!
title_resp.body.match(%r{<title.*?>(.*)</title>})&.captures&.[](0) || query
else
query
end
out = {
items: [
{
title: title.dup.force_encoding('UTF-8'),
subtitle: result_url,
arg: result_url,
variables: {
title: title.dup.force_encoding('UTF-8'),
url: result_url,
original_query: query,
},
},
],
}
puts out.to_json