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