1 Url = Struct.new("Url", :channel, :nick, :time, :url)
2 TITLE_RE = /<\s*?title\s*?>(.+?)<\s*?\/title\s*?>/im
3 LINK_INFO = "[Link Info]"
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',
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',
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',
17 :desc => "Also try to get the first paragraph of a web page")
21 @registry.set_default(Array.new)
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>"
28 def get_title_from_html(pagedata)
29 return unless TITLE_RE.match(pagedata)
33 def get_title_for_url(uri_str)
35 url = uri_str.kind_of?(URI) ? uri_str : URI.parse(uri_str)
36 return if url.scheme !~ /https?/
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})"
48 if response['content-type'] =~ /^text\//
50 body = response.body.slice(0, range)
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}"
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
63 return "#{Bold}title#{Bold}: #{title}" if title
66 # if nothing was found, provide more basic info
69 debug response.to_hash.inspect
71 enc = response['content-encoding']
73 extra << ", #{Bold}encoding#{Bold}: #{enc}" if enc
75 unless @bot.config['url.titles_only']
76 # content doesn't have title, just display info.
77 size = response['content-length'].gsub(/(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/,'\1,\2') rescue nil
78 if response.code == '206'
79 if response['content-range'] =~ /bytes\s*[^\/]+\/(\d+)/
80 size = $1.to_s.reverse.scan(/\d{1,3}/).join(',').reverse
83 size = size ? ", #{Bold}size#{Bold}: #{size} bytes" : ""
84 return "#{Bold}type#{Bold}: #{response['content-type']}#{size}#{extra}"
88 debug e.backtrace.join("\n")
89 return "Error connecting to site (#{e.message})"
94 return unless m.kind_of?(PrivMessage)
96 # TODO support multiple urls in one line
97 if m.message =~ /(f|ht)tps?:\/\//
98 if m.message =~ /((f|ht)tps?:\/\/.*?)(?:\s+|$)/
100 list = @registry[m.target]
102 if @bot.config['url.display_link_info']
104 debug "Getting title for #{urlstr}..."
106 title = get_title_for_url urlstr
108 m.reply "#{LINK_INFO} #{title}", :overlong => :truncate
111 debug "Title not found!"
119 # check to see if this url is already listed
120 return if list.find {|u| u.url == urlstr }
122 url = Url.new(m.target, m.sourcenick, Time.new, urlstr)
123 debug "#{list.length} urls so far"
124 if list.length > @bot.config['url.max_urls']
127 debug "storing url #{url.url}"
129 debug "#{list.length} urls now"
130 @registry[m.target] = list
136 channel = params[:channel] ? params[:channel] : m.target
137 max = params[:limit].to_i
140 list = @registry[channel]
142 m.reply "no urls seen yet for channel #{channel}"
144 list[0..(max-1)].each do |url|
145 m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
150 def search(m, params)
151 channel = params[:channel] ? params[:channel] : m.target
152 max = params[:limit].to_i
153 string = params[:string]
156 regex = Regexp.new(string, Regexp::IGNORECASE)
157 list = @registry[channel].find_all {|url|
158 regex.match(url.url) || regex.match(url.nick)
161 m.reply "no matches for channel #{channel}"
163 list[0..(max-1)].each do |url|
164 m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
169 plugin = UrlPlugin.new
170 plugin.map 'urls search :channel :limit :string', :action => 'search',
171 :defaults => {:limit => 4},
172 :requirements => {:limit => /^\d+$/},
174 plugin.map 'urls search :limit :string', :action => 'search',
175 :defaults => {:limit => 4},
176 :requirements => {:limit => /^\d+$/},
178 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
179 :requirements => {:limit => /^\d+$/},
181 plugin.map 'urls :limit', :defaults => {:limit => 4},
182 :requirements => {:limit => /^\d+$/},