]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/url.rb
url plugin: only consider http(s) urls found by URI.extract()
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / url.rb
1 define_structure :Url, :channel, :nick, :time, :url, :info
2
3 class ::UrlLinkError < RuntimeError
4 end
5
6 class UrlPlugin < Plugin
7   TITLE_RE = /<\s*?title\s*?>(.+?)<\s*?\/title\s*?>/im
8   LINK_INFO = "[Link Info]"
9
10   BotConfig.register BotConfigIntegerValue.new('url.max_urls',
11     :default => 100, :validate => Proc.new{|v| v > 0},
12     :desc => "Maximum number of urls to store. New urls replace oldest ones.")
13   BotConfig.register BotConfigBooleanValue.new('url.display_link_info',
14     :default => false,
15     :desc => "Get the title of any links pasted to the channel and display it (also tells if the link is broken or the site is down)")
16   BotConfig.register BotConfigBooleanValue.new('url.titles_only',
17     :default => false,
18     :desc => "Only show info for links that have <title> tags (in other words, don't display info for jpegs, mpegs, etc.)")
19   BotConfig.register BotConfigBooleanValue.new('url.first_par',
20     :default => false,
21     :desc => "Also try to get the first paragraph of a web page")
22   BotConfig.register BotConfigBooleanValue.new('url.info_on_list',
23     :default => false,
24     :desc => "Show link info when listing/searching for urls")
25
26
27   def initialize
28     super
29     @registry.set_default(Array.new)
30   end
31
32   def help(plugin, topic="")
33     "urls [<max>=4] => list <max> last urls mentioned in current channel, urls search [<max>=4] <regexp> => search for matching urls. In a private message, you must specify the channel to query, eg. urls <channel> [max], urls search <channel> [max] <regexp>"
34   end
35
36   def get_title_from_html(pagedata)
37     return unless TITLE_RE.match(pagedata)
38     $1.ircify_html
39   end
40
41   def get_title_for_url(uri_str, nick = nil, channel = nil)
42
43     url = uri_str.kind_of?(URI) ? uri_str : URI.parse(uri_str)
44     return if url.scheme !~ /https?/
45
46     logopts = Hash.new
47     logopts[:nick] = nick if nick
48     logopts[:channel] = channel if channel
49
50     title = nil
51     extra = String.new
52
53     begin
54       debug "+ getting #{url.request_uri}"
55       @bot.httputil.get_response(url) { |resp|
56         case resp
57         when Net::HTTPSuccess
58
59           debug resp.to_hash
60
61           if resp['content-type'] =~ /^text\/|(?:x|ht)ml/
62             # The page is text or HTML, so we can try finding a title and, if
63             # requested, the first par.
64             #
65             # We act differently depending on whether we want the first par or
66             # not: in the first case we download the initial part and the parse
67             # it; in the second case we only download as much as we need to find
68             # the title
69             #
70             if @bot.config['url.first_par']
71               partial = resp.partial_body(@bot.config['http.info_bytes'])
72               logopts[:title] = title = get_title_from_html(partial)
73               if url.fragment and not url.fragment.empty?
74                 fragreg = /.*?<a\s+[^>]*name=["']?#{url.fragment}["']?.*?>/im
75                 partial.sub!(fragreg,'')
76               end
77               first_par = Utils.ircify_first_html_par(partial, :strip => title)
78               unless first_par.empty?
79                 logopts[:extra] = first_par
80                 extra << ", #{Bold}text#{Bold}: #{first_par}"
81               end
82               call_event(:url_added, url.to_s, logopts)
83               return "#{Bold}title#{Bold}: #{title}#{extra}" if title
84             else
85               resp.partial_body(@bot.config['http.info_bytes']) { |part|
86                 logopts[:title] = title = get_title_from_html(part)
87                 call_event(:url_added, url.to_s, logopts)
88                 return "#{Bold}title#{Bold}: #{title}" if title
89               }
90             end
91           # if nothing was found, provide more basic info, as for non-html pages
92           else
93             resp.no_cache = true
94           end
95
96           enc = resp['content-encoding']
97           logopts[:extra] = String.new
98           logopts[:extra] << "Content Type: #{resp['content-type']}"
99           if enc
100             logopts[:extra] << ", encoding: #{enc}"
101             extra << ", #{Bold}encoding#{Bold}: #{enc}"
102           end
103
104           unless @bot.config['url.titles_only']
105             # content doesn't have title, just display info.
106             size = resp['content-length'].gsub(/(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/,'\1,\2') rescue nil
107             if size
108               logopts[:extra] << ", size: #{size} bytes"
109               size = ", #{Bold}size#{Bold}: #{size} bytes"
110             end
111             call_event(:url_added, url.to_s, logopts)
112             return "#{Bold}type#{Bold}: #{resp['content-type']}#{size}#{extra}"
113           end
114           call_event(:url_added, url.to_s, logopts)
115         else
116           raise UrlLinkError, "getting link (#{resp.code} - #{resp.message})"
117         end
118       }
119       return nil
120     rescue Exception => e
121       case e
122       when UrlLinkError
123         raise e
124       else
125         error e
126         raise "connecting to site/processing information (#{e.message})"
127       end
128     end
129   end
130
131   def listen(m)
132     return unless m.kind_of?(PrivMessage)
133     return if m.address?
134     urls = URI.extract(m.message)
135     return if urls.empty?
136     debug "found urls #{urls.inspect}"
137     list = @registry[m.target]
138     urls.each { |urlstr|
139       debug "working on #{urlstr}"
140       next unless urlstr =~ /^https?:/
141       title = nil
142       if @bot.config['url.display_link_info']
143         Thread.start do
144           debug "Getting title for #{urlstr}..."
145           begin
146             title = get_title_for_url urlstr, m.source.nick, m.channel
147             if title
148               m.reply "#{LINK_INFO} #{title}", :overlong => :truncate
149               debug "Title found!"
150             else
151               debug "Title not found!"
152             end
153           rescue => e
154             m.reply "Error #{e.message}"
155           end
156         end
157       end
158
159       # check to see if this url is already listed
160       next if list.find {|u| u.url == urlstr }
161
162       url = Url.new(m.target, m.sourcenick, Time.new, urlstr, title)
163       debug "#{list.length} urls so far"
164       if list.length > @bot.config['url.max_urls']
165         list.pop
166       end
167       debug "storing url #{url.url}"
168       list.unshift url
169       debug "#{list.length} urls now"
170     }
171     @registry[m.target] = list
172   end
173
174   def reply_urls(opts={})
175     list = opts[:list]
176     max = opts[:max]
177     channel = opts[:channel]
178     m = opts[:msg]
179     return unless list and max and m
180     list[0..(max-1)].each do |url|
181       disp = "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
182       if @bot.config['url.info_on_list']
183         title = url.info || get_title_for_url(url.url, url.nick, channel) rescue nil
184         # If the url info was missing and we now have some, try to upgrade it
185         if channel and title and not url.info
186           ll = @registry[channel]
187           debug ll
188           if el = ll.find { |u| u.url == url.url }
189             el.info = title
190             @registry[channel] = ll
191           end
192         end
193         disp << " --> #{title}" if title
194       end
195       m.reply disp, :overlong => :truncate
196     end
197   end
198
199   def urls(m, params)
200     channel = params[:channel] ? params[:channel] : m.target
201     max = params[:limit].to_i
202     max = 10 if max > 10
203     max = 1 if max < 1
204     list = @registry[channel]
205     if list.empty?
206       m.reply "no urls seen yet for channel #{channel}"
207     else
208       reply_urls :msg => m, :channel => channel, :list => list, :max => max
209     end
210   end
211
212   def search(m, params)
213     channel = params[:channel] ? params[:channel] : m.target
214     max = params[:limit].to_i
215     string = params[:string]
216     max = 10 if max > 10
217     max = 1 if max < 1
218     regex = Regexp.new(string, Regexp::IGNORECASE)
219     list = @registry[channel].find_all {|url|
220       regex.match(url.url) || regex.match(url.nick) ||
221         (@bot.config['url.info_on_list'] && regex.match(url.info))
222     }
223     if list.empty?
224       m.reply "no matches for channel #{channel}"
225     else
226       reply_urls :msg => m, :channel => channel, :list => list, :max => max
227     end
228   end
229 end
230
231 plugin = UrlPlugin.new
232 plugin.map 'urls search :channel :limit :string', :action => 'search',
233                           :defaults => {:limit => 4},
234                           :requirements => {:limit => /^\d+$/},
235                           :public => false
236 plugin.map 'urls search :limit :string', :action => 'search',
237                           :defaults => {:limit => 4},
238                           :requirements => {:limit => /^\d+$/},
239                           :private => false
240 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
241                           :requirements => {:limit => /^\d+$/},
242                           :public => false
243 plugin.map 'urls :limit', :defaults => {:limit => 4},
244                           :requirements => {:limit => /^\d+$/},
245                           :private => false