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