]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/url.rb
quotes plugin: cleanups
[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               first_par = Utils.ircify_first_html_par(partial, :strip => title)
74               unless first_par.empty?
75                 logopts[:extra] = first_par
76                 extra << ", #{Bold}text#{Bold}: #{first_par}"
77               end
78               call_event(:url_added, url.to_s, logopts)
79               return "#{Bold}title#{Bold}: #{title}#{extra}" if title
80             else
81               resp.partial_body(@bot.config['http.info_bytes']) { |part|
82                 logopts[:title] = title = get_title_from_html(part)
83                 call_event(:url_added, url.to_s, logopts)
84                 return "#{Bold}title#{Bold}: #{title}" if title
85               }
86             end
87           # if nothing was found, provide more basic info, as for non-html pages
88           else
89             resp.no_cache = true
90           end
91
92           enc = resp['content-encoding']
93           logopts[:extra] = String.new
94           logopts[:extra] << "Content Type: #{resp['content-type']}"
95           if enc
96             logopts[:extra] << ", encoding: #{enc}"
97             extra << ", #{Bold}encoding#{Bold}: #{enc}"
98           end
99
100           unless @bot.config['url.titles_only']
101             # content doesn't have title, just display info.
102             size = resp['content-length'].gsub(/(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/,'\1,\2') rescue nil
103             if size
104               logopts[:extra] << ", size: #{size} bytes"
105               size = ", #{Bold}size#{Bold}: #{size} bytes"
106             end
107             call_event(:url_added, url.to_s, logopts)
108             return "#{Bold}type#{Bold}: #{resp['content-type']}#{size}#{extra}"
109           end
110           call_event(:url_added, url.to_s, logopts)
111         else
112           raise UrlLinkError, "getting link (#{resp.code} - #{resp.message})"
113         end
114       }
115       return nil
116     rescue Exception => e
117       case e
118       when UrlLinkError
119         raise e
120       else
121         error e
122         raise "connecting to site/processing information (#{e.message})"
123       end
124     end
125   end
126
127   def listen(m)
128     return unless m.kind_of?(PrivMessage)
129     return if m.address?
130     # TODO support multiple urls in one line
131     if m.message =~ /(f|ht)tps?:\/\//
132       if m.message =~ /((f|ht)tps?:\/\/.*?)(?:\s+|$)/
133         urlstr = $1
134         list = @registry[m.target]
135
136         title = nil
137         if @bot.config['url.display_link_info']
138           Thread.start do
139             debug "Getting title for #{urlstr}..."
140             begin
141               title = get_title_for_url urlstr, m.source.nick, m.channel
142               if title
143                 m.reply "#{LINK_INFO} #{title}", :overlong => :truncate
144                 debug "Title found!"
145               else
146                 debug "Title not found!"
147               end
148             rescue => e
149               m.reply "Error #{e.message}"
150             end
151           end
152         end
153
154         # check to see if this url is already listed
155         return if list.find {|u| u.url == urlstr }
156
157         url = Url.new(m.target, m.sourcenick, Time.new, urlstr, title)
158         debug "#{list.length} urls so far"
159         if list.length > @bot.config['url.max_urls']
160           list.pop
161         end
162         debug "storing url #{url.url}"
163         list.unshift url
164         debug "#{list.length} urls now"
165         @registry[m.target] = list
166       end
167     end
168   end
169
170   def reply_urls(opts={})
171     list = opts[:list]
172     max = opts[:max]
173     channel = opts[:channel]
174     m = opts[:msg]
175     return unless list and max and m
176     list[0..(max-1)].each do |url|
177       disp = "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
178       if @bot.config['url.info_on_list']
179         title = url.info || get_title_for_url(url.url, url.nick, channel) rescue nil
180         # If the url info was missing and we now have some, try to upgrade it
181         if channel and title and not url.info
182           ll = @registry[channel]
183           debug ll
184           if el = ll.find { |u| u.url == url.url }
185             el.info = title
186             @registry[channel] = ll
187           end
188         end
189         disp << " --> #{title}" if title
190       end
191       m.reply disp, :overlong => :truncate
192     end
193   end
194
195   def urls(m, params)
196     channel = params[:channel] ? params[:channel] : m.target
197     max = params[:limit].to_i
198     max = 10 if max > 10
199     max = 1 if max < 1
200     list = @registry[channel]
201     if list.empty?
202       m.reply "no urls seen yet for channel #{channel}"
203     else
204       reply_urls :msg => m, :channel => channel, :list => list, :max => max
205     end
206   end
207
208   def search(m, params)
209     channel = params[:channel] ? params[:channel] : m.target
210     max = params[:limit].to_i
211     string = params[:string]
212     max = 10 if max > 10
213     max = 1 if max < 1
214     regex = Regexp.new(string, Regexp::IGNORECASE)
215     list = @registry[channel].find_all {|url|
216       regex.match(url.url) || regex.match(url.nick) ||
217         (@bot.config['url.info_on_list'] && regex.match(url.info))
218     }
219     if list.empty?
220       m.reply "no matches for channel #{channel}"
221     else
222       reply_urls :msg => m, :channel => channel, :list => list, :max => max
223     end
224   end
225 end
226
227 plugin = UrlPlugin.new
228 plugin.map 'urls search :channel :limit :string', :action => 'search',
229                           :defaults => {:limit => 4},
230                           :requirements => {:limit => /^\d+$/},
231                           :public => false
232 plugin.map 'urls search :limit :string', :action => 'search',
233                           :defaults => {:limit => 4},
234                           :requirements => {:limit => /^\d+$/},
235                           :private => false
236 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
237                           :requirements => {:limit => /^\d+$/},
238                           :public => false
239 plugin.map 'urls :limit', :defaults => {:limit => 4},
240                           :requirements => {:limit => /^\d+$/},
241                           :private => false