]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/url.rb
84ee7e436ed5a2c523bb98a1da8fa9e4f6f5792b
[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
6 class UrlPlugin < Plugin
7   BotConfig.register BotConfigIntegerValue.new('url.max_urls',
8     :default => 100, :validate => Proc.new{|v| v > 0},
9     :desc => "Maximum number of urls to store. New urls replace oldest ones.")
10   BotConfig.register BotConfigBooleanValue.new('url.display_link_info',
11     :default => false,
12     :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)")
13   BotConfig.register BotConfigBooleanValue.new('url.titles_only',
14     :default => false,
15     :desc => "Only show info for links that have <title> tags (in other words, don't display info for jpegs, mpegs, etc.)")
16
17   def initialize
18     super
19     @registry.set_default(Array.new)
20   end
21
22   def help(plugin, topic="")
23     "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>"
24   end
25
26   def get_title_from_html(pagedata)
27     return unless TITLE_RE.match(pagedata)
28     title = $1.strip.gsub(/\s*\n+\s*/, " ")
29     title = Utils.decode_html_entities title
30     title = title[0..255] if title.length > 255
31     "[Link Info] title: #{title}"
32   end
33
34   def read_data_from_response(response, amount)
35
36     amount_read = 0
37     chunks = []
38
39     response.read_body do |chunk|   # read body now
40
41       amount_read += chunk.length
42
43       # if amount_read > amount
44       #   amount_of_overflow = amount_read - amount
45       #   chunk = chunk[0...-amount_of_overflow]
46       # end
47
48       chunks << chunk
49
50       break if amount_read >= amount
51
52     end
53
54     chunks.join('')
55
56   end
57
58   def get_title_for_url(uri_str, depth=@bot.config['http.max_redir'])
59     # This god-awful mess is what the ruby http library has reduced me to.
60     # Python's HTTP lib is so much nicer. :~(
61
62     if depth == 0
63         raise "Error: Maximum redirects hit."
64     end
65
66     debug "+ Getting #{uri_str.to_s}"
67     url = uri_str.kind_of?(URI) ? uri_str : URI.parse(uri_str)
68     return if url.scheme !~ /https?/
69
70     title = nil
71
72     debug "+ connecting to #{url.host}:#{url.port}"
73     http = @bot.httputil.get_proxy(url)
74     http.start { |http|
75
76       http.request_get(url.request_uri(), @bot.httputil.headers) { |response|
77
78         case response
79           when Net::HTTPRedirection
80             # call self recursively if this is a redirect
81             redirect_to = response['location']  || '/'
82             debug "+ redirect location: #{redirect_to.inspect}"
83             url = URI.join(url.to_s, redirect_to)
84             debug "+ whee, redirecting to #{url.to_s}!"
85             return get_title_for_url(url, depth-1)
86           when Net::HTTPSuccess
87             if response['content-type'] =~ /^text\//
88               # since the content is 'text/*' and is small enough to
89               # be a webpage, retrieve the title from the page
90               debug "+ getting #{url.request_uri}"
91               # was 5*10^4 ... seems to much to me ... 4k should be enough for everybody ;)
92               data = read_data_from_response(response, 4096)
93               return get_title_from_html(data)
94             else
95               unless @bot.config['url.titles_only']
96                 # content doesn't have title, just display info.
97                 size = response['content-length'].gsub(/(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/,'\1,\2')
98                 size = size ? ", size: #{size} bytes" : ""
99                 return "[Link Info] type: #{response['content-type']}#{size}"
100               end
101             end
102           else
103             return "[Link Info] Error getting link (#{response.code} - #{response.message})"
104           end # end of "case response"
105
106       } # end of request block
107     } # end of http start block
108
109     return title
110
111   rescue SocketError => e
112     return "[Link Info] Error connecting to site (#{e.message})"
113   end
114
115   def listen(m)
116     return unless m.kind_of?(PrivMessage)
117     return if m.address?
118     # TODO support multiple urls in one line
119     if m.message =~ /(f|ht)tps?:\/\//
120       if m.message =~ /((f|ht)tps?:\/\/.*?)(?:\s+|$)/
121         urlstr = $1
122         list = @registry[m.target]
123
124         if @bot.config['url.display_link_info']
125           debug "Getting title for #{urlstr}..."
126           begin
127           title = get_title_for_url urlstr
128           if title
129             m.reply title
130             debug "Title found!"
131           else
132             debug "Title not found!"
133           end
134           rescue => e
135             debug "Failed: #{e}"
136           end
137         end
138
139         # check to see if this url is already listed
140         return if list.find {|u| u.url == urlstr }
141
142         url = Url.new(m.target, m.sourcenick, Time.new, urlstr)
143         debug "#{list.length} urls so far"
144         if list.length > @bot.config['url.max_urls']
145           list.pop
146         end
147         debug "storing url #{url.url}"
148         list.unshift url
149         debug "#{list.length} urls now"
150         @registry[m.target] = list
151       end
152     end
153   end
154
155   def urls(m, params)
156     channel = params[:channel] ? params[:channel] : m.target
157     max = params[:limit].to_i
158     max = 10 if max > 10
159     max = 1 if max < 1
160     list = @registry[channel]
161     if list.empty?
162       m.reply "no urls seen yet for channel #{channel}"
163     else
164       list[0..(max-1)].each do |url|
165         m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
166       end
167     end
168   end
169
170   def search(m, params)
171     channel = params[:channel] ? params[:channel] : m.target
172     max = params[:limit].to_i
173     string = params[:string]
174     max = 10 if max > 10
175     max = 1 if max < 1
176     regex = Regexp.new(string, Regexp::IGNORECASE)
177     list = @registry[channel].find_all {|url|
178       regex.match(url.url) || regex.match(url.nick)
179     }
180     if list.empty?
181       m.reply "no matches for channel #{channel}"
182     else
183       list[0..(max-1)].each do |url|
184         m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
185       end
186     end
187   end
188 end
189 plugin = UrlPlugin.new
190 plugin.map 'urls search :channel :limit :string', :action => 'search',
191                           :defaults => {:limit => 4},
192                           :requirements => {:limit => /^\d+$/},
193                           :public => false
194 plugin.map 'urls search :limit :string', :action => 'search',
195                           :defaults => {:limit => 4},
196                           :requirements => {:limit => /^\d+$/},
197                           :private => false
198 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
199                           :requirements => {:limit => /^\d+$/},
200                           :public => false
201 plugin.map 'urls :limit', :defaults => {:limit => 4},
202                           :requirements => {:limit => /^\d+$/},
203                           :private => false