]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/url.rb
* (plugins/ri) acknoledge the '!ri tell (whom)' command
[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
40     begin
41       range = @bot.config['http.info_bytes']
42       response = @bot.httputil.get_response(url, :range => "bytes=0-#{range}")
43       if response.code != "206" && response.code != "200"
44         return "Error getting link (#{response.code} - #{response.message})"
45       end
46       extra = String.new
47
48       if response['content-type'] =~ /^text\//
49
50         body = response.body.slice(0, range)
51         title = String.new
52
53         # since the content is 'text/*' and is small enough to
54         # be a webpage, retrieve the title from the page
55         debug "+ getting #{url.request_uri}"
56
57         title = get_title_from_html(body)
58         if @bot.config['url.first_par']
59           first_par = Utils.ircify_first_html_par(body, :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           return "#{Bold}title#{Bold}: #{title}" if title
64         end
65
66         # if nothing was found, provide more basic info
67       end
68
69       debug response.to_hash.inspect
70       unless @bot.config['url.titles_only']
71         # content doesn't have title, just display info.
72         size = response['content-length'].gsub(/(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/,'\1,\2') rescue nil
73         if response.code == '206'
74           if response['content-range'] =~ /bytes\s*[^\/]+\/(\d+)/
75             size = $1.to_s.reverse.scan(/\d{1,3}/).join(',').reverse
76           end
77         end
78         size = size ? ", #{Bold}size#{Bold}: #{size} bytes" : ""
79         return "#{Bold}type#{Bold}: #{response['content-type']}#{size}#{extra}"
80       end
81     rescue Exception => e
82       error e.inspect
83       debug e.backtrace.join("\n")
84       return "Error connecting to site (#{e.message})"
85     end
86   end
87
88   def listen(m)
89     return unless m.kind_of?(PrivMessage)
90     return if m.address?
91     # TODO support multiple urls in one line
92     if m.message =~ /(f|ht)tps?:\/\//
93       if m.message =~ /((f|ht)tps?:\/\/.*?)(?:\s+|$)/
94         urlstr = $1
95         list = @registry[m.target]
96
97         if @bot.config['url.display_link_info']
98           Thread.start do
99             debug "Getting title for #{urlstr}..."
100             begin
101               title = get_title_for_url urlstr
102               if title
103                 m.reply "#{LINK_INFO} #{title}", :overlong => :truncate
104                 debug "Title found!"
105               else
106                 debug "Title not found!"
107               end
108             rescue => e
109               debug "Failed: #{e}"
110             end
111           end
112         end
113
114         # check to see if this url is already listed
115         return if list.find {|u| u.url == urlstr }
116
117         url = Url.new(m.target, m.sourcenick, Time.new, urlstr)
118         debug "#{list.length} urls so far"
119         if list.length > @bot.config['url.max_urls']
120           list.pop
121         end
122         debug "storing url #{url.url}"
123         list.unshift url
124         debug "#{list.length} urls now"
125         @registry[m.target] = list
126       end
127     end
128   end
129
130   def urls(m, params)
131     channel = params[:channel] ? params[:channel] : m.target
132     max = params[:limit].to_i
133     max = 10 if max > 10
134     max = 1 if max < 1
135     list = @registry[channel]
136     if list.empty?
137       m.reply "no urls seen yet for channel #{channel}"
138     else
139       list[0..(max-1)].each do |url|
140         m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
141       end
142     end
143   end
144
145   def search(m, params)
146     channel = params[:channel] ? params[:channel] : m.target
147     max = params[:limit].to_i
148     string = params[:string]
149     max = 10 if max > 10
150     max = 1 if max < 1
151     regex = Regexp.new(string, Regexp::IGNORECASE)
152     list = @registry[channel].find_all {|url|
153       regex.match(url.url) || regex.match(url.nick)
154     }
155     if list.empty?
156       m.reply "no matches for channel #{channel}"
157     else
158       list[0..(max-1)].each do |url|
159         m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
160       end
161     end
162   end
163 end
164 plugin = UrlPlugin.new
165 plugin.map 'urls search :channel :limit :string', :action => 'search',
166                           :defaults => {:limit => 4},
167                           :requirements => {:limit => /^\d+$/},
168                           :public => false
169 plugin.map 'urls search :limit :string', :action => 'search',
170                           :defaults => {:limit => 4},
171                           :requirements => {:limit => /^\d+$/},
172                           :private => false
173 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
174                           :requirements => {:limit => /^\d+$/},
175                           :public => false
176 plugin.map 'urls :limit', :defaults => {:limit => 4},
177                           :requirements => {:limit => /^\d+$/},
178                           :private => false