]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/url.rb
6d82099faaa30b0cc78ebe182f3ad978b74d558e
[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)
42
43     url = uri_str.kind_of?(URI) ? uri_str : URI.parse(uri_str)
44     return if url.scheme !~ /https?/
45
46     title = nil
47     extra = String.new
48
49     begin
50       debug "+ getting #{url.request_uri}"
51       @bot.httputil.get_response(url) { |resp|
52         case resp
53         when Net::HTTPSuccess
54
55           debug resp.to_hash
56
57           if resp['content-type'] =~ /^text\/|(?:x|ht)ml/
58             # The page is text or HTML, so we can try finding a title and, if
59             # requested, the first par.
60             #
61             # We act differently depending on whether we want the first par or
62             # not: in the first case we download the initial part and the parse
63             # it; in the second case we only download as much as we need to find
64             # the title
65             #
66             if @bot.config['url.first_par']
67               partial = resp.partial_body(@bot.config['http.info_bytes'])
68               title = get_title_from_html(partial)
69               first_par = Utils.ircify_first_html_par(partial, :strip => title)
70               extra << ", #{Bold}text#{Bold}: #{first_par}" unless first_par.empty?
71               return "#{Bold}title#{Bold}: #{title}#{extra}" if title
72             else
73               resp.partial_body(@bot.config['http.info_bytes']) { |part|
74                 title = get_title_from_html(part)
75                 return "#{Bold}title#{Bold}: #{title}" if title
76               }
77             end
78           # if nothing was found, provide more basic info, as for non-html pages
79           else
80             resp.no_cache = true
81           end
82
83           enc = resp['content-encoding']
84
85           extra << ", #{Bold}encoding#{Bold}: #{enc}" if enc
86
87           unless @bot.config['url.titles_only']
88             # content doesn't have title, just display info.
89             size = resp['content-length'].gsub(/(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/,'\1,\2') rescue nil
90             size = size ? ", #{Bold}size#{Bold}: #{size} bytes" : ""
91             return "#{Bold}type#{Bold}: #{resp['content-type']}#{size}#{extra}"
92           end
93         else
94           raise UrlLinkError, "getting link (#{resp.code} - #{resp.message})"
95         end
96       }
97       return nil
98     rescue Exception => e
99       case e
100       when UrlLinkError
101         raise e
102       else
103         error e
104         raise "connecting to site/processing information (#{e.message})"
105       end
106     end
107   end
108
109   def listen(m)
110     return unless m.kind_of?(PrivMessage)
111     return if m.address?
112     # TODO support multiple urls in one line
113     if m.message =~ /(f|ht)tps?:\/\//
114       if m.message =~ /((f|ht)tps?:\/\/.*?)(?:\s+|$)/
115         urlstr = $1
116         list = @registry[m.target]
117
118         title = nil
119         if @bot.config['url.display_link_info']
120           Thread.start do
121             debug "Getting title for #{urlstr}..."
122             begin
123               title = get_title_for_url urlstr
124               if title
125                 m.reply "#{LINK_INFO} #{title}", :overlong => :truncate
126                 debug "Title found!"
127               else
128                 debug "Title not found!"
129               end
130             rescue => e
131               m.reply "Error #{e.message}"
132             end
133           end
134         end
135
136         # check to see if this url is already listed
137         return if list.find {|u| u.url == urlstr }
138
139         url = Url.new(m.target, m.sourcenick, Time.new, urlstr, title)
140         debug "#{list.length} urls so far"
141         if list.length > @bot.config['url.max_urls']
142           list.pop
143         end
144         debug "storing url #{url.url}"
145         list.unshift url
146         debug "#{list.length} urls now"
147         @registry[m.target] = list
148       end
149     end
150   end
151
152   def reply_urls(opts={})
153     list = opts[:list]
154     max = opts[:max]
155     channel = opts[:channel]
156     m = opts[:msg]
157     return unless list and max and m
158     list[0..(max-1)].each do |url|
159       disp = "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
160       if @bot.config['url.info_on_list']
161         title = url.info || get_title_for_url(url.url) rescue nil
162         # If the url info was missing and we now have some, try to upgrade it
163         if channel and title and not url.info
164           ll = @registry[channel]
165           debug ll
166           if el = ll.find { |u| u.url == url.url }
167             el.info = title
168             @registry[channel] = ll
169           end
170         end
171         disp << " --> #{title}" if title
172       end
173       m.reply disp, :overlong => :truncate
174     end
175   end
176
177   def urls(m, params)
178     channel = params[:channel] ? params[:channel] : m.target
179     max = params[:limit].to_i
180     max = 10 if max > 10
181     max = 1 if max < 1
182     list = @registry[channel]
183     if list.empty?
184       m.reply "no urls seen yet for channel #{channel}"
185     else
186       reply_urls :msg => m, :channel => channel, :list => list, :max => max
187     end
188   end
189
190   def search(m, params)
191     channel = params[:channel] ? params[:channel] : m.target
192     max = params[:limit].to_i
193     string = params[:string]
194     max = 10 if max > 10
195     max = 1 if max < 1
196     regex = Regexp.new(string, Regexp::IGNORECASE)
197     list = @registry[channel].find_all {|url|
198       regex.match(url.url) || regex.match(url.nick) ||
199         (@bot.config['url.info_on_list'] && regex.match(url.info))
200     }
201     if list.empty?
202       m.reply "no matches for channel #{channel}"
203     else
204       reply_urls :msg => m, :channel => channel, :list => list, :max => max
205     end
206   end
207 end
208
209 plugin = UrlPlugin.new
210 plugin.map 'urls search :channel :limit :string', :action => 'search',
211                           :defaults => {:limit => 4},
212                           :requirements => {:limit => /^\d+$/},
213                           :public => false
214 plugin.map 'urls search :limit :string', :action => 'search',
215                           :defaults => {:limit => 4},
216                           :requirements => {:limit => /^\d+$/},
217                           :private => false
218 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
219                           :requirements => {:limit => /^\d+$/},
220                           :public => false
221 plugin.map 'urls :limit', :defaults => {:limit => 4},
222                           :requirements => {:limit => /^\d+$/},
223                           :private => false