]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/url.rb
0a5ef74ef8c4b5db8819a4dcf00ee4ba1e0dc6af
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / url.rb
1 Url = Struct.new("Url", :channel, :nick, :time, :url)
2 TITLE_RE = /<\s*?title\s*?>(.+?)<\s*?\/title\s*?>/im
3 LINK_INFO = "[Link Info]"
4
5 class UrlPlugin < Plugin
6   BotConfig.register BotConfigIntegerValue.new('url.max_urls',
7     :default => 100, :validate => Proc.new{|v| v > 0},
8     :desc => "Maximum number of urls to store. New urls replace oldest ones.")
9   BotConfig.register BotConfigBooleanValue.new('url.display_link_info',
10     :default => false,
11     :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)")
12   BotConfig.register BotConfigBooleanValue.new('url.titles_only',
13     :default => false,
14     :desc => "Only show info for links that have <title> tags (in other words, don't display info for jpegs, mpegs, etc.)")
15   BotConfig.register BotConfigBooleanValue.new('url.first_par',
16     :default => false,
17     :desc => "Also try to get the first paragraph of a web page")
18
19   def initialize
20     super
21     @registry.set_default(Array.new)
22   end
23
24   def help(plugin, topic="")
25     "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>"
26   end
27
28   def get_title_from_html(pagedata)
29     return unless TITLE_RE.match(pagedata)
30     $1.ircify_html
31   end
32
33   def get_title_for_url(uri_str)
34
35     url = uri_str.kind_of?(URI) ? uri_str : URI.parse(uri_str)
36     return if url.scheme !~ /https?/
37
38     title = nil
39     extra = String.new
40
41     begin
42       debug "+ getting #{url.request_uri}"
43       @bot.httputil.get_response(url) { |resp|
44         case resp
45         when Net::HTTPSuccess
46
47           if resp['content-type'] =~ /^text\/|(?:x|ht)ml/
48             # The page is text or HTML, so we can try finding a title and, if
49             # requested, the first par.
50             #
51             # We act differently depending on whether we want the first par or
52             # not: in the first case we download the initial part and the parse
53             # it; in the second case we only download as much as we need to find
54             # the title
55             #
56             if @bot.config['url.first_par']
57               partial = resp.partial_body(@bot.config['http.info_bytes'])
58               title = get_title_from_html(partial)
59               first_par = Utils.ircify_first_html_par(partial, :strip => title)
60               extra << ", #{Bold}text#{Bold}: #{first_par}" unless first_par.empty?
61               return "#{Bold}title#{Bold}: #{title}#{extra}" if title
62             else
63               resp.partial_body(@bot.config['http.info_bytes']) { |part|
64                 title = get_title_from_html(part)
65                 return "#{Bold}title#{Bold}: #{title}" if title
66               }
67             end
68           # if nothing was found, provide more basic info, as for non-html pages
69           end
70
71           debug resp.to_hash.inspect
72
73           enc = resp['content-encoding']
74
75           extra << ", #{Bold}encoding#{Bold}: #{enc}" if enc
76
77           unless @bot.config['url.titles_only']
78             # content doesn't have title, just display info.
79             size = resp['content-length'].gsub(/(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/,'\1,\2') rescue nil
80             size = size ? ", #{Bold}size#{Bold}: #{size} bytes" : ""
81             return "#{Bold}type#{Bold}: #{resp['content-type']}#{size}#{extra}"
82           end
83         else
84           return "Error getting link (#{resp.code} - #{resp.message})"
85         end
86       }
87     rescue Exception => e
88       error e
89       return "Error connecting to site (#{e.message})"
90     end
91   end
92
93   def listen(m)
94     return unless m.kind_of?(PrivMessage)
95     return if m.address?
96     # TODO support multiple urls in one line
97     if m.message =~ /(f|ht)tps?:\/\//
98       if m.message =~ /((f|ht)tps?:\/\/.*?)(?:\s+|$)/
99         urlstr = $1
100         list = @registry[m.target]
101
102         if @bot.config['url.display_link_info']
103           Thread.start do
104             debug "Getting title for #{urlstr}..."
105             begin
106               title = get_title_for_url urlstr
107               if title
108                 m.reply "#{LINK_INFO} #{title}", :overlong => :truncate
109                 debug "Title found!"
110               else
111                 debug "Title not found!"
112               end
113             rescue => e
114               debug "Failed: #{e}"
115             end
116           end
117         end
118
119         # check to see if this url is already listed
120         return if list.find {|u| u.url == urlstr }
121
122         url = Url.new(m.target, m.sourcenick, Time.new, urlstr)
123         debug "#{list.length} urls so far"
124         if list.length > @bot.config['url.max_urls']
125           list.pop
126         end
127         debug "storing url #{url.url}"
128         list.unshift url
129         debug "#{list.length} urls now"
130         @registry[m.target] = list
131       end
132     end
133   end
134
135   def urls(m, params)
136     channel = params[:channel] ? params[:channel] : m.target
137     max = params[:limit].to_i
138     max = 10 if max > 10
139     max = 1 if max < 1
140     list = @registry[channel]
141     if list.empty?
142       m.reply "no urls seen yet for channel #{channel}"
143     else
144       list[0..(max-1)].each do |url|
145         m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
146       end
147     end
148   end
149
150   def search(m, params)
151     channel = params[:channel] ? params[:channel] : m.target
152     max = params[:limit].to_i
153     string = params[:string]
154     max = 10 if max > 10
155     max = 1 if max < 1
156     regex = Regexp.new(string, Regexp::IGNORECASE)
157     list = @registry[channel].find_all {|url|
158       regex.match(url.url) || regex.match(url.nick)
159     }
160     if list.empty?
161       m.reply "no matches for channel #{channel}"
162     else
163       list[0..(max-1)].each do |url|
164         m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
165       end
166     end
167   end
168 end
169 plugin = UrlPlugin.new
170 plugin.map 'urls search :channel :limit :string', :action => 'search',
171                           :defaults => {:limit => 4},
172                           :requirements => {:limit => /^\d+$/},
173                           :public => false
174 plugin.map 'urls search :limit :string', :action => 'search',
175                           :defaults => {:limit => 4},
176                           :requirements => {:limit => /^\d+$/},
177                           :private => false
178 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
179                           :requirements => {:limit => /^\d+$/},
180                           :public => false
181 plugin.map 'urls :limit', :defaults => {:limit => 4},
182                           :requirements => {:limit => /^\d+$/},
183                           :private => false