3 Url = Struct.new("Url", :channel, :nick, :time, :url)
4 TITLE_RE = /<\s*?title\s*?>(.+?)<\s*?\/title\s*?>/im
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',
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',
15 :desc => "Only show info for links that have <title> tags (in other words, don't display info for jpegs, mpegs, etc.)")
19 @registry.set_default(Array.new)
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>"
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}"
34 def read_data_from_response(response, amount)
39 response.read_body do |chunk| # read body now
41 amount_read += chunk.length
43 if amount_read > amount
44 amount_of_overflow = amount_read - amount
45 chunk = chunk[0...-amount_of_overflow]
50 break if amount_read >= amount
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. :~(
63 raise "Error: Maximum redirects hit."
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?/
72 debug "+ connecting to #{url.host}:#{url.port}"
73 http = @bot.httputil.get_proxy(url)
76 http.request_get(url.request_uri(), @bot.httputil.headers) { |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)
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)
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}"
103 return "[Link Info] Error getting link (#{response.code} - #{response.message})"
104 end # end of "case response"
106 } # end of request block
107 } # end of http start block
111 rescue SocketError => e
112 return "[Link Info] Error connecting to site (#{e.message})"
116 return unless m.kind_of?(PrivMessage)
118 # TODO support multiple urls in one line
119 if m.message =~ /(f|ht)tps?:\/\//
120 if m.message =~ /((f|ht)tps?:\/\/.*?)(?:\s+|$)/
122 list = @registry[m.target]
124 if @bot.config['url.display_link_info']
125 debug "Getting title for #{urlstr}..."
127 title = get_title_for_url urlstr
132 debug "Title not found!"
139 # check to see if this url is already listed
140 return if list.find {|u| u.url == urlstr }
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']
147 debug "storing url #{url.url}"
149 debug "#{list.length} urls now"
150 @registry[m.target] = list
156 channel = params[:channel] ? params[:channel] : m.target
157 max = params[:limit].to_i
160 list = @registry[channel]
162 m.reply "no urls seen yet for channel #{channel}"
164 list[0..(max-1)].each do |url|
165 m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
170 def search(m, params)
171 channel = params[:channel] ? params[:channel] : m.target
172 max = params[:limit].to_i
173 string = params[:string]
176 regex = Regexp.new(string, Regexp::IGNORECASE)
177 list = @registry[channel].find_all {|url|
178 regex.match(url.url) || regex.match(url.nick)
181 m.reply "no matches for channel #{channel}"
183 list[0..(max-1)].each do |url|
184 m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
189 plugin = UrlPlugin.new
190 plugin.map 'urls search :channel :limit :string', :action => 'search',
191 :defaults => {:limit => 4},
192 :requirements => {:limit => /^\d+$/},
194 plugin.map 'urls search :limit :string', :action => 'search',
195 :defaults => {:limit => 4},
196 :requirements => {:limit => /^\d+$/},
198 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
199 :requirements => {:limit => /^\d+$/},
201 plugin.map 'urls :limit', :defaults => {:limit => 4},
202 :requirements => {:limit => /^\d+$/},