Improve 'first paragraph' detection in search plugin, and clean up ircify_html method
[rbot] / data / rbot / plugins / search.rb
1 require 'uri'
2
3 Net::HTTP.version_1_2
4
5 GOOGLE_WAP_LINK = /<a accesskey="(\d)" href=".*?u=(.*?)">(.*?)<\/a>/im
6
7 class ::String
8   def omissis_after(len)
9     if self.length > len
10       return self[0...len].sub(/\s+\S*$/,"...")
11     else
12       return self
13     end
14   end
15
16   def ircify_html
17     txt = self
18
19     # bold and strong -> bold
20     txt.gsub!(/<\/?(?:b|strong)\s*>/, "#{Bold}")
21
22     # italic, emphasis and underline -> underline
23     txt.gsub!(/<\/?(?:i|em|u)\s*>/, "#{Underline}")
24
25     ## This would be a nice addition, but the results are horrible
26     ## Maybe make it configurable?
27     # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
28
29     # Paragraph and br tags are converted to whitespace.
30     txt.gsub!(/<\/?(p|br)\s*\/?\s*>/, ' ')
31     txt.gsub!("\n", ' ')
32
33     # All other tags are just removed
34     txt.gsub!(/<[^>]+>/, '')
35
36     # Remove double formatting options, since they only waste bytes
37     txt.gsub!(/#{Bold}\s*#{Bold}/,"")
38     txt.gsub!(/#{Underline}\s*#{Underline}/,"")
39
40     # And finally whitespace is squeezed
41     txt.gsub!(/\s+/, ' ')
42
43     # Decode entities and strip whitespace
44     return Utils.decode_html_entities(txt).strip!
45   end
46 end
47
48 class SearchPlugin < Plugin
49   BotConfig.register BotConfigIntegerValue.new('google.hits',
50     :default => 3,
51     :desc => "Number of hits to return from Google searches")
52   BotConfig.register BotConfigIntegerValue.new('google.first_par',
53     :default => 0,
54     :desc => "When set to n > 0, the bot will return the first paragraph from the first n search hits")
55   BotConfig.register BotConfigIntegerValue.new('wikipedia.hits',
56     :default => 3,
57     :desc => "Number of hits to return from Wikipedia searches")
58   BotConfig.register BotConfigIntegerValue.new('wikipedia.first_par',
59     :default => 1,
60     :desc => "When set to n > 0, the bot will return the first paragraph from the first n wikipedia search hits")
61
62   def help(plugin, topic="")
63     case topic
64     when "search", "google"
65       "#{topic} <string> => search google for <string>"
66     when "wp"
67       "wp [<code>] <string> => search for <string> on Wikipedia. You can select a national <code> to only search the national Wikipedia"
68     else
69       "search <string> (or: google <string>) => search google for <string> | wp <string> => search for <string> on Wikipedia"
70     end
71   end
72
73   def google(m, params)
74     what = params[:words].to_s
75     searchfor = URI.escape what
76     # This method is also called by other methods to restrict searching to some sites
77     if params[:site]
78       site = "site:#{params[:site]}+"
79     else
80       site = ""
81     end
82     # It is also possible to choose a filter to remove constant parts from the titles
83     # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
84     filter = params[:filter] || ""
85
86     url = "http://www.google.com/wml/search?q=#{site}#{searchfor}"
87
88     hits = params[:hits] || @bot.config['google.hits']
89
90     begin
91       wml = @bot.httputil.get_cached(url)
92     rescue => e
93       m.reply "error googling for #{what}"
94       return
95     end
96     results = wml.scan(GOOGLE_WAP_LINK)
97     if results.length == 0
98       m.reply "no results found for #{what}"
99       return
100     end
101     urls = Array.new
102     results = results[0...hits].map { |res|
103       n = res[0]
104       t = Utils.decode_html_entities res[2].gsub(filter, '').strip
105       u = URI.unescape res[1]
106       urls.push(u)
107       "#{n}. #{Bold}#{t}#{Bold}: #{u}"
108     }.join(" | ")
109
110     m.reply "Results for #{what}: #{results}"
111
112     first_pars = params[:firstpar] || @bot.config['google.first_par']
113
114     idx = 0
115     while first_pars > 0 and urls.length > 0
116       url.replace(urls.shift)
117       idx += 1
118       xml = @bot.httputil.get_cached(url)
119       if xml.nil?
120         debug "Unable to retrieve #{url}"
121         next
122       end
123       # We get the first par after the first main heading, if possible
124       header_found = xml.match(/<h1(?:\s+[^>]*)?>(.*?)<\/h1>/im)
125       txt = String.new
126       if header_found
127         debug "Found header: #{header_found[1].inspect}"
128         while txt.empty? 
129           header_found = $'
130           candidate = header_found[/<p(?:\s+[^>]*)?>.*?<\/p>/im].ircify_html
131           break unless candidate
132           txt.replace candidate
133         end
134       end
135       # If we haven't found a first par yet, try to get it from the whole
136       # document
137       if txt.empty?
138         txt = xml[/<p(?:\s+[^>]*)?>.*?<\/p>/im].ircify_html
139         while txt.empty? 
140           header_found = $'
141           candidate = header_found[/<p(?:\s+[^>]*)?>.*?<\/p>/im].ircify_html
142           break unless candidate
143           txt.replace candidate
144         end
145       end
146       # Nothing yet, give up
147       if txt.empty?
148         debug "No first par found\n#{xml}"
149         next
150       end
151       m.reply "[#{idx}] #{txt}".omissis_after(400)
152       first_pars -=1
153     end
154   end
155
156   def wikipedia(m, params)
157     lang = params[:lang]
158     site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
159     debug "Looking up things on #{site}"
160     params[:site] = site
161     params[:filter] = / - Wikipedia.*$/
162     params[:hits] = @bot.config['wikipedia.hits']
163     params[:firstpar] = @bot.config['wikipedia.first_par']
164     return google(m, params)
165   end
166 end
167
168 plugin = SearchPlugin.new
169
170 plugin.map "search *words", :action => 'google'
171 plugin.map "google *words", :action => 'google'
172 plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }
173 plugin.map "wp *words", :action => 'wikipedia'
174