3 Url = Struct.new("Url", :channel, :nick, :time, :url)
4 TITLE_RE = /<\s*?title\s*?>(.+?)<\s*?\/title\s*?>/im
5 LINK_INFO = "[Link Info]"
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',
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',
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',
19 :desc => "Also try to get the first paragraph of a web page")
23 @registry.set_default(Array.new)
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>"
30 def get_title_from_html(pagedata)
31 return unless TITLE_RE.match(pagedata)
35 def get_title_for_url(uri_str)
37 url = uri_str.kind_of?(URI) ? uri_str : URI.parse(uri_str)
38 return if url.scheme !~ /https?/
43 @bot.httputil.get_response(url) { |response|
48 if response['content-type'] =~ /^text\//
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}"
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)
65 return "title: #{title}#{extra}"
68 response.partial_body(@bot.config['http.info_bytes']) { |part|
69 title = get_title_from_html(part)
70 return "title: #{title}" if title
73 # if nothing was found, provide more basic info
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}"
83 when Net::HTTPResponse
84 return "Error getting link (#{response.code} - #{response.message})"
90 if e.class <= StandardError
92 debug e.backtrace.join("\n")
95 msg = e.respond_to?(:message) ? e.message : e.to_s
96 return "Error connecting to site (#{e.message})"
101 return unless m.kind_of?(PrivMessage)
103 # TODO support multiple urls in one line
104 if m.message =~ /(f|ht)tps?:\/\//
105 if m.message =~ /((f|ht)tps?:\/\/.*?)(?:\s+|$)/
107 list = @registry[m.target]
109 if @bot.config['url.display_link_info']
111 debug "Getting title for #{urlstr}..."
113 title = get_title_for_url urlstr
115 m.reply "#{LINK_INFO} #{title}", :overlong => :truncate
118 debug "Title not found!"
126 # check to see if this url is already listed
127 return if list.find {|u| u.url == urlstr }
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']
134 debug "storing url #{url.url}"
136 debug "#{list.length} urls now"
137 @registry[m.target] = list
143 channel = params[:channel] ? params[:channel] : m.target
144 max = params[:limit].to_i
147 list = @registry[channel]
149 m.reply "no urls seen yet for channel #{channel}"
151 list[0..(max-1)].each do |url|
152 m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
157 def search(m, params)
158 channel = params[:channel] ? params[:channel] : m.target
159 max = params[:limit].to_i
160 string = params[:string]
163 regex = Regexp.new(string, Regexp::IGNORECASE)
164 list = @registry[channel].find_all {|url|
165 regex.match(url.url) || regex.match(url.nick)
168 m.reply "no matches for channel #{channel}"
170 list[0..(max-1)].each do |url|
171 m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
176 plugin = UrlPlugin.new
177 plugin.map 'urls search :channel :limit :string', :action => 'search',
178 :defaults => {:limit => 4},
179 :requirements => {:limit => /^\d+$/},
181 plugin.map 'urls search :limit :string', :action => 'search',
182 :defaults => {:limit => 4},
183 :requirements => {:limit => /^\d+$/},
185 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
186 :requirements => {:limit => /^\d+$/},
188 plugin.map 'urls :limit', :defaults => {:limit => 4},
189 :requirements => {:limit => /^\d+$/},